Bug Summary

File:llvm/lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 11030, column 52
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SIISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Target/AMDGPU -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Target/AMDGPU -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Target/AMDGPU -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
1//===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Custom DAG lowering for SI
11//
12//===----------------------------------------------------------------------===//
13
14#include "SIISelLowering.h"
15#include "AMDGPU.h"
16#include "AMDGPUInstrInfo.h"
17#include "AMDGPUTargetMachine.h"
18#include "SIMachineFunctionInfo.h"
19#include "SIRegisterInfo.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22#include "llvm/BinaryFormat/ELF.h"
23#include "llvm/CodeGen/Analysis.h"
24#include "llvm/CodeGen/FunctionLoweringInfo.h"
25#include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
27#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/IntrinsicsAMDGPU.h"
29#include "llvm/IR/IntrinsicsR600.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/KnownBits.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE"si-lower" "si-lower"
36
37STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"si-lower", "NumTailCalls"
, "Number of tail calls"}
;
38
39static cl::opt<bool> DisableLoopAlignment(
40 "amdgpu-disable-loop-alignment",
41 cl::desc("Do not align and prefetch loops"),
42 cl::init(false));
43
44static cl::opt<bool> VGPRReserveforSGPRSpill(
45 "amdgpu-reserve-vgpr-for-sgpr-spill",
46 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
47
48static cl::opt<bool> UseDivergentRegisterIndexing(
49 "amdgpu-use-divergent-register-indexing",
50 cl::Hidden,
51 cl::desc("Use indirect register addressing for divergent indexes"),
52 cl::init(false));
53
54static bool hasFP32Denormals(const MachineFunction &MF) {
55 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
56 return Info->getMode().allFP32Denormals();
57}
58
59static bool hasFP64FP16Denormals(const MachineFunction &MF) {
60 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
61 return Info->getMode().allFP64FP16Denormals();
62}
63
64static unsigned findFirstFreeSGPR(CCState &CCInfo) {
65 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
66 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
67 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
68 return AMDGPU::SGPR0 + Reg;
69 }
70 }
71 llvm_unreachable("Cannot allocate sgpr")::llvm::llvm_unreachable_internal("Cannot allocate sgpr", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 71)
;
72}
73
74SITargetLowering::SITargetLowering(const TargetMachine &TM,
75 const GCNSubtarget &STI)
76 : AMDGPUTargetLowering(TM, STI),
77 Subtarget(&STI) {
78 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
79 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
80
81 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
82 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
83
84 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
85
86 const SIRegisterInfo *TRI = STI.getRegisterInfo();
87 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
88
89 addRegisterClass(MVT::f64, V64RegClass);
90 addRegisterClass(MVT::v2f32, V64RegClass);
91
92 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
93 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
94
95 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
96 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
97
98 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
99 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
100
101 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
102 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
103
104 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
105 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
106
107 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
108 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
109
110 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
111 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
112
113 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
114 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
115
116 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
117 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
118
119 if (Subtarget->has16BitInsts()) {
120 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
121 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
122
123 // Unless there are also VOP3P operations, not operations are really legal.
124 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
125 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
126 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
127 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
128 }
129
130 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
131 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
132
133 computeRegisterProperties(Subtarget->getRegisterInfo());
134
135 // The boolean content concept here is too inflexible. Compares only ever
136 // really produce a 1-bit result. Any copy/extend from these will turn into a
137 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
138 // it's what most targets use.
139 setBooleanContents(ZeroOrOneBooleanContent);
140 setBooleanVectorContents(ZeroOrOneBooleanContent);
141
142 // We need to custom lower vector stores from local memory
143 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
144 setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
145 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
146 setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
147 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
148 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
149 setOperationAction(ISD::LOAD, MVT::i1, Custom);
150 setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
151
152 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
153 setOperationAction(ISD::STORE, MVT::v3i32, Custom);
154 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
155 setOperationAction(ISD::STORE, MVT::v5i32, Custom);
156 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
157 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
158 setOperationAction(ISD::STORE, MVT::i1, Custom);
159 setOperationAction(ISD::STORE, MVT::v32i32, Custom);
160
161 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
162 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
163 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
164 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
165 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
166 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
167 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
168 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
169 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
170 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
171 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
172 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
173 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
174 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
175 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
176 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
177
178 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
179 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
180 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
181 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
182 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
183
184 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
185 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
186
187 setOperationAction(ISD::SELECT, MVT::i1, Promote);
188 setOperationAction(ISD::SELECT, MVT::i64, Custom);
189 setOperationAction(ISD::SELECT, MVT::f64, Promote);
190 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
191
192 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
193 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
194 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
195 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
196 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
197
198 setOperationAction(ISD::SETCC, MVT::i1, Promote);
199 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
200 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
201 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
202
203 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
204 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
205 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
206 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
207 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
208 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
209 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
210 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
211
212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
220
221 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
222 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
223 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
224 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
225 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
226 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
227
228 setOperationAction(ISD::UADDO, MVT::i32, Legal);
229 setOperationAction(ISD::USUBO, MVT::i32, Legal);
230
231 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
232 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
233
234 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
235 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
236 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
237
238#if 0
239 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
240 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
241#endif
242
243 // We only support LOAD/STORE and vector manipulation ops for vectors
244 // with > 4 elements.
245 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
246 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
247 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
248 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
249 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
250 switch (Op) {
251 case ISD::LOAD:
252 case ISD::STORE:
253 case ISD::BUILD_VECTOR:
254 case ISD::BITCAST:
255 case ISD::EXTRACT_VECTOR_ELT:
256 case ISD::INSERT_VECTOR_ELT:
257 case ISD::INSERT_SUBVECTOR:
258 case ISD::EXTRACT_SUBVECTOR:
259 case ISD::SCALAR_TO_VECTOR:
260 break;
261 case ISD::CONCAT_VECTORS:
262 setOperationAction(Op, VT, Custom);
263 break;
264 default:
265 setOperationAction(Op, VT, Expand);
266 break;
267 }
268 }
269 }
270
271 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
272
273 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
274 // is expanded to avoid having two separate loops in case the index is a VGPR.
275
276 // Most operations are naturally 32-bit vector operations. We only support
277 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
278 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
279 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
280 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
281
282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
283 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
284
285 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
286 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
287
288 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
289 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
290 }
291
292 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
293 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
294 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
295
296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
297 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
298
299 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
300 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
301
302 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
303 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
304 }
305
306 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
307 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
308 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
309
310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
311 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
312
313 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
314 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
315
316 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
317 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
318 }
319
320 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
321 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
322 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
323
324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
325 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
326
327 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
328 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
329
330 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
331 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
332 }
333
334 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
335 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
336 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
337 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
338
339 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
340 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
341
342 // Avoid stack access for these.
343 // TODO: Generalize to more vector types.
344 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
345 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
346 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
347 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
348
349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
350 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
353 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
354
355 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
356 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
357 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
358
359 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
360 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
361 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
362 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
363
364 // Deal with vec3 vector operations when widened to vec4.
365 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
366 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
367 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
368 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
369
370 // Deal with vec5 vector operations when widened to vec8.
371 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
372 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
373 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
374 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
375
376 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
377 // and output demarshalling
378 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
379 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
380
381 // We can't return success/failure, only the old value,
382 // let LLVM add the comparison
383 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
384 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
385
386 if (Subtarget->hasFlatAddressSpace()) {
387 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
388 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
389 }
390
391 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
392 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
393
394 // FIXME: This should be narrowed to i32, but that only happens if i64 is
395 // illegal.
396 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
397 setOperationAction(ISD::BSWAP, MVT::i64, Legal);
398 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
399
400 // On SI this is s_memtime and s_memrealtime on VI.
401 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
402 setOperationAction(ISD::TRAP, MVT::Other, Custom);
403 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
404
405 if (Subtarget->has16BitInsts()) {
406 setOperationAction(ISD::FPOW, MVT::f16, Promote);
407 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
408 setOperationAction(ISD::FLOG, MVT::f16, Custom);
409 setOperationAction(ISD::FEXP, MVT::f16, Custom);
410 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
411 }
412
413 if (Subtarget->hasMadMacF32Insts())
414 setOperationAction(ISD::FMAD, MVT::f32, Legal);
415
416 if (!Subtarget->hasBFI()) {
417 // fcopysign can be done in a single instruction with BFI.
418 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
419 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
420 }
421
422 if (!Subtarget->hasBCNT(32))
423 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
424
425 if (!Subtarget->hasBCNT(64))
426 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
427
428 if (Subtarget->hasFFBH())
429 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
430
431 if (Subtarget->hasFFBL())
432 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
433
434 // We only really have 32-bit BFE instructions (and 16-bit on VI).
435 //
436 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
437 // effort to match them now. We want this to be false for i64 cases when the
438 // extraction isn't restricted to the upper or lower half. Ideally we would
439 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
440 // span the midpoint are probably relatively rare, so don't worry about them
441 // for now.
442 if (Subtarget->hasBFE())
443 setHasExtractBitsInsn(true);
444
445 // Clamp modifier on add/sub
446 if (Subtarget->hasIntClamp()) {
447 setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
448 setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
449 }
450
451 if (Subtarget->hasAddNoCarry()) {
452 setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
453 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
454 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
455 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
456 }
457
458 setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
459 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
460 setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
461 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
462
463
464 // These are really only legal for ieee_mode functions. We should be avoiding
465 // them for functions that don't have ieee_mode enabled, so just say they are
466 // legal.
467 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
468 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
469 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
470 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
471
472
473 if (Subtarget->haveRoundOpsF64()) {
474 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
475 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
476 setOperationAction(ISD::FRINT, MVT::f64, Legal);
477 } else {
478 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
479 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
480 setOperationAction(ISD::FRINT, MVT::f64, Custom);
481 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
482 }
483
484 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
485
486 setOperationAction(ISD::FSIN, MVT::f32, Custom);
487 setOperationAction(ISD::FCOS, MVT::f32, Custom);
488 setOperationAction(ISD::FDIV, MVT::f32, Custom);
489 setOperationAction(ISD::FDIV, MVT::f64, Custom);
490
491 if (Subtarget->has16BitInsts()) {
492 setOperationAction(ISD::Constant, MVT::i16, Legal);
493
494 setOperationAction(ISD::SMIN, MVT::i16, Legal);
495 setOperationAction(ISD::SMAX, MVT::i16, Legal);
496
497 setOperationAction(ISD::UMIN, MVT::i16, Legal);
498 setOperationAction(ISD::UMAX, MVT::i16, Legal);
499
500 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
501 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
502
503 setOperationAction(ISD::ROTR, MVT::i16, Expand);
504 setOperationAction(ISD::ROTL, MVT::i16, Expand);
505
506 setOperationAction(ISD::SDIV, MVT::i16, Promote);
507 setOperationAction(ISD::UDIV, MVT::i16, Promote);
508 setOperationAction(ISD::SREM, MVT::i16, Promote);
509 setOperationAction(ISD::UREM, MVT::i16, Promote);
510 setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
511 setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
512
513 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
514
515 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
516 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
517 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
518 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
519 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
520
521 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
522
523 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
524
525 setOperationAction(ISD::LOAD, MVT::i16, Custom);
526
527 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
528
529 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
530 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
531 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
532 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
533
534 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
535 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
536
537 // F16 - Constant Actions.
538 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
539
540 // F16 - Load/Store Actions.
541 setOperationAction(ISD::LOAD, MVT::f16, Promote);
542 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
543 setOperationAction(ISD::STORE, MVT::f16, Promote);
544 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
545
546 // F16 - VOP1 Actions.
547 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
548 setOperationAction(ISD::FCOS, MVT::f16, Custom);
549 setOperationAction(ISD::FSIN, MVT::f16, Custom);
550
551 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
552 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
553
554 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
555 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
556 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
557 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
558 setOperationAction(ISD::FROUND, MVT::f16, Custom);
559
560 // F16 - VOP2 Actions.
561 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
562 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
563
564 setOperationAction(ISD::FDIV, MVT::f16, Custom);
565
566 // F16 - VOP3 Actions.
567 setOperationAction(ISD::FMA, MVT::f16, Legal);
568 if (STI.hasMadF16())
569 setOperationAction(ISD::FMAD, MVT::f16, Legal);
570
571 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
572 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
573 switch (Op) {
574 case ISD::LOAD:
575 case ISD::STORE:
576 case ISD::BUILD_VECTOR:
577 case ISD::BITCAST:
578 case ISD::EXTRACT_VECTOR_ELT:
579 case ISD::INSERT_VECTOR_ELT:
580 case ISD::INSERT_SUBVECTOR:
581 case ISD::EXTRACT_SUBVECTOR:
582 case ISD::SCALAR_TO_VECTOR:
583 break;
584 case ISD::CONCAT_VECTORS:
585 setOperationAction(Op, VT, Custom);
586 break;
587 default:
588 setOperationAction(Op, VT, Expand);
589 break;
590 }
591 }
592 }
593
594 // v_perm_b32 can handle either of these.
595 setOperationAction(ISD::BSWAP, MVT::i16, Legal);
596 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
597 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
598
599 // XXX - Do these do anything? Vector constants turn into build_vector.
600 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
601 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
602
603 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
604 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
605
606 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
607 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
608 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
609 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
610
611 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
612 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
613 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
614 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
615
616 setOperationAction(ISD::AND, MVT::v2i16, Promote);
617 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
618 setOperationAction(ISD::OR, MVT::v2i16, Promote);
619 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
620 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
621 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
622
623 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
624 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
625 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
626 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
627
628 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
629 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
630 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
631 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
632
633 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
634 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
635 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
636 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
637
638 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
639 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
640 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
641
642 if (!Subtarget->hasVOP3PInsts()) {
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
644 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
645 }
646
647 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
648 // This isn't really legal, but this avoids the legalizer unrolling it (and
649 // allows matching fneg (fabs x) patterns)
650 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
651
652 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
653 setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
654 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
655 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
656
657 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
658 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
659
660 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
661 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
662 }
663
664 if (Subtarget->hasVOP3PInsts()) {
665 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
666 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
667 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
668 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
669 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
670 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
671 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
672 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
673 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
674 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
675
676 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
677 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
678 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
679 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
680
681 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
682 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
683 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
684
685 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
686 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
687
688 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
689
690 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
692
693 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
694 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
695
696 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
697 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
698 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
699 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
700 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
701 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
702
703 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
704 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
705 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
706 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
707
708 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
709 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
710 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
711 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
712
713 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
714 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
715 setOperationAction(ISD::FMA, MVT::v4f16, Custom);
716
717 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
718 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
719
720 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
721 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
722 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
723
724 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
725 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
726 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
727
728 if (Subtarget->hasPackedFP32Ops()) {
729 setOperationAction(ISD::FADD, MVT::v2f32, Legal);
730 setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
731 setOperationAction(ISD::FMA, MVT::v2f32, Legal);
732 setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
733
734 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
735 setOperationAction(ISD::FADD, VT, Custom);
736 setOperationAction(ISD::FMUL, VT, Custom);
737 setOperationAction(ISD::FMA, VT, Custom);
738 }
739 }
740 }
741
742 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
743 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
744
745 if (Subtarget->has16BitInsts()) {
746 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
747 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
748 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
749 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
750 } else {
751 // Legalization hack.
752 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
753 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
754
755 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
756 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
757 }
758
759 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
760 setOperationAction(ISD::SELECT, VT, Custom);
761 }
762
763 setOperationAction(ISD::SMULO, MVT::i64, Custom);
764 setOperationAction(ISD::UMULO, MVT::i64, Custom);
765
766 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
767 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
768 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
769 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
773
774 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
775 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
776 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
777 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
785
786 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
787 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
788 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
789 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
790 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
793 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
794 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
795 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
796
797 setTargetDAGCombine(ISD::ADD);
798 setTargetDAGCombine(ISD::ADDCARRY);
799 setTargetDAGCombine(ISD::SUB);
800 setTargetDAGCombine(ISD::SUBCARRY);
801 setTargetDAGCombine(ISD::FADD);
802 setTargetDAGCombine(ISD::FSUB);
803 setTargetDAGCombine(ISD::FMINNUM);
804 setTargetDAGCombine(ISD::FMAXNUM);
805 setTargetDAGCombine(ISD::FMINNUM_IEEE);
806 setTargetDAGCombine(ISD::FMAXNUM_IEEE);
807 setTargetDAGCombine(ISD::FMA);
808 setTargetDAGCombine(ISD::SMIN);
809 setTargetDAGCombine(ISD::SMAX);
810 setTargetDAGCombine(ISD::UMIN);
811 setTargetDAGCombine(ISD::UMAX);
812 setTargetDAGCombine(ISD::SETCC);
813 setTargetDAGCombine(ISD::AND);
814 setTargetDAGCombine(ISD::OR);
815 setTargetDAGCombine(ISD::XOR);
816 setTargetDAGCombine(ISD::SINT_TO_FP);
817 setTargetDAGCombine(ISD::UINT_TO_FP);
818 setTargetDAGCombine(ISD::FCANONICALIZE);
819 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
820 setTargetDAGCombine(ISD::ZERO_EXTEND);
821 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
822 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
823 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
824
825 // All memory operations. Some folding on the pointer operand is done to help
826 // matching the constant offsets in the addressing modes.
827 setTargetDAGCombine(ISD::LOAD);
828 setTargetDAGCombine(ISD::STORE);
829 setTargetDAGCombine(ISD::ATOMIC_LOAD);
830 setTargetDAGCombine(ISD::ATOMIC_STORE);
831 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
832 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
833 setTargetDAGCombine(ISD::ATOMIC_SWAP);
834 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
835 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
836 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
837 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
838 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
839 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
840 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
841 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
842 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
843 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
844 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
845 setTargetDAGCombine(ISD::INTRINSIC_VOID);
846 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
847
848 // FIXME: In other contexts we pretend this is a per-function property.
849 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
850
851 setSchedulingPreference(Sched::RegPressure);
852}
853
854const GCNSubtarget *SITargetLowering::getSubtarget() const {
855 return Subtarget;
856}
857
858//===----------------------------------------------------------------------===//
859// TargetLowering queries
860//===----------------------------------------------------------------------===//
861
862// v_mad_mix* support a conversion from f16 to f32.
863//
864// There is only one special case when denormals are enabled we don't currently,
865// where this is OK to use.
866bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
867 EVT DestVT, EVT SrcVT) const {
868 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
869 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
870 DestVT.getScalarType() == MVT::f32 &&
871 SrcVT.getScalarType() == MVT::f16 &&
872 // TODO: This probably only requires no input flushing?
873 !hasFP32Denormals(DAG.getMachineFunction());
874}
875
876bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
877 // SI has some legal vector types, but no legal vector operations. Say no
878 // shuffles are legal in order to prefer scalarizing some vector operations.
879 return false;
880}
881
882MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
883 CallingConv::ID CC,
884 EVT VT) const {
885 if (CC == CallingConv::AMDGPU_KERNEL)
886 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
887
888 if (VT.isVector()) {
889 EVT ScalarVT = VT.getScalarType();
890 unsigned Size = ScalarVT.getSizeInBits();
891 if (Size == 16) {
892 if (Subtarget->has16BitInsts())
893 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
894 return VT.isInteger() ? MVT::i32 : MVT::f32;
895 }
896
897 if (Size < 16)
898 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
899 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
900 }
901
902 if (VT.getSizeInBits() > 32)
903 return MVT::i32;
904
905 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
906}
907
908unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
909 CallingConv::ID CC,
910 EVT VT) const {
911 if (CC == CallingConv::AMDGPU_KERNEL)
912 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
913
914 if (VT.isVector()) {
915 unsigned NumElts = VT.getVectorNumElements();
916 EVT ScalarVT = VT.getScalarType();
917 unsigned Size = ScalarVT.getSizeInBits();
918
919 // FIXME: Should probably promote 8-bit vectors to i16.
920 if (Size == 16 && Subtarget->has16BitInsts())
921 return (NumElts + 1) / 2;
922
923 if (Size <= 32)
924 return NumElts;
925
926 if (Size > 32)
927 return NumElts * ((Size + 31) / 32);
928 } else if (VT.getSizeInBits() > 32)
929 return (VT.getSizeInBits() + 31) / 32;
930
931 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
932}
933
934unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
935 LLVMContext &Context, CallingConv::ID CC,
936 EVT VT, EVT &IntermediateVT,
937 unsigned &NumIntermediates, MVT &RegisterVT) const {
938 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
939 unsigned NumElts = VT.getVectorNumElements();
940 EVT ScalarVT = VT.getScalarType();
941 unsigned Size = ScalarVT.getSizeInBits();
942 // FIXME: We should fix the ABI to be the same on targets without 16-bit
943 // support, but unless we can properly handle 3-vectors, it will be still be
944 // inconsistent.
945 if (Size == 16 && Subtarget->has16BitInsts()) {
946 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
947 IntermediateVT = RegisterVT;
948 NumIntermediates = (NumElts + 1) / 2;
949 return NumIntermediates;
950 }
951
952 if (Size == 32) {
953 RegisterVT = ScalarVT.getSimpleVT();
954 IntermediateVT = RegisterVT;
955 NumIntermediates = NumElts;
956 return NumIntermediates;
957 }
958
959 if (Size < 16 && Subtarget->has16BitInsts()) {
960 // FIXME: Should probably form v2i16 pieces
961 RegisterVT = MVT::i16;
962 IntermediateVT = ScalarVT;
963 NumIntermediates = NumElts;
964 return NumIntermediates;
965 }
966
967
968 if (Size != 16 && Size <= 32) {
969 RegisterVT = MVT::i32;
970 IntermediateVT = ScalarVT;
971 NumIntermediates = NumElts;
972 return NumIntermediates;
973 }
974
975 if (Size > 32) {
976 RegisterVT = MVT::i32;
977 IntermediateVT = RegisterVT;
978 NumIntermediates = NumElts * ((Size + 31) / 32);
979 return NumIntermediates;
980 }
981 }
982
983 return TargetLowering::getVectorTypeBreakdownForCallingConv(
984 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
985}
986
987static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
988 assert(DMaskLanes != 0)((DMaskLanes != 0) ? static_cast<void> (0) : __assert_fail
("DMaskLanes != 0", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 988, __PRETTY_FUNCTION__))
;
989
990 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
991 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
992 return EVT::getVectorVT(Ty->getContext(),
993 EVT::getEVT(VT->getElementType()),
994 NumElts);
995 }
996
997 return EVT::getEVT(Ty);
998}
999
1000// Peek through TFE struct returns to only use the data size.
1001static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1002 auto *ST = dyn_cast<StructType>(Ty);
1003 if (!ST)
1004 return memVTFromImageData(Ty, DMaskLanes);
1005
1006 // Some intrinsics return an aggregate type - special case to work out the
1007 // correct memVT.
1008 //
1009 // Only limited forms of aggregate type currently expected.
1010 if (ST->getNumContainedTypes() != 2 ||
1011 !ST->getContainedType(1)->isIntegerTy(32))
1012 return EVT();
1013 return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1014}
1015
1016bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1017 const CallInst &CI,
1018 MachineFunction &MF,
1019 unsigned IntrID) const {
1020 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1021 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1022 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1023 (Intrinsic::ID)IntrID);
1024 if (Attr.hasFnAttribute(Attribute::ReadNone))
1025 return false;
1026
1027 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1028
1029 if (RsrcIntr->IsImage) {
1030 Info.ptrVal =
1031 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1032 Info.align.reset();
1033 } else {
1034 Info.ptrVal =
1035 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1036 }
1037
1038 Info.flags = MachineMemOperand::MODereferenceable;
1039 if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1040 unsigned DMaskLanes = 4;
1041
1042 if (RsrcIntr->IsImage) {
1043 const AMDGPU::ImageDimIntrinsicInfo *Intr
1044 = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1045 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1046 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1047
1048 if (!BaseOpcode->Gather4) {
1049 // If this isn't a gather, we may have excess loaded elements in the
1050 // IR type. Check the dmask for the real number of elements loaded.
1051 unsigned DMask
1052 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1053 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1054 }
1055
1056 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1057 } else
1058 Info.memVT = EVT::getEVT(CI.getType());
1059
1060 // FIXME: What does alignment mean for an image?
1061 Info.opc = ISD::INTRINSIC_W_CHAIN;
1062 Info.flags |= MachineMemOperand::MOLoad;
1063 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1064 Info.opc = ISD::INTRINSIC_VOID;
1065
1066 Type *DataTy = CI.getArgOperand(0)->getType();
1067 if (RsrcIntr->IsImage) {
1068 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1069 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1070 Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1071 } else
1072 Info.memVT = EVT::getEVT(DataTy);
1073
1074 Info.flags |= MachineMemOperand::MOStore;
1075 } else {
1076 // Atomic
1077 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1078 ISD::INTRINSIC_W_CHAIN;
1079 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1080 Info.flags = MachineMemOperand::MOLoad |
1081 MachineMemOperand::MOStore |
1082 MachineMemOperand::MODereferenceable;
1083
1084 // XXX - Should this be volatile without known ordering?
1085 Info.flags |= MachineMemOperand::MOVolatile;
1086 }
1087 return true;
1088 }
1089
1090 switch (IntrID) {
1091 case Intrinsic::amdgcn_atomic_inc:
1092 case Intrinsic::amdgcn_atomic_dec:
1093 case Intrinsic::amdgcn_ds_ordered_add:
1094 case Intrinsic::amdgcn_ds_ordered_swap:
1095 case Intrinsic::amdgcn_ds_fadd:
1096 case Intrinsic::amdgcn_ds_fmin:
1097 case Intrinsic::amdgcn_ds_fmax: {
1098 Info.opc = ISD::INTRINSIC_W_CHAIN;
1099 Info.memVT = MVT::getVT(CI.getType());
1100 Info.ptrVal = CI.getOperand(0);
1101 Info.align.reset();
1102 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1103
1104 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1105 if (!Vol->isZero())
1106 Info.flags |= MachineMemOperand::MOVolatile;
1107
1108 return true;
1109 }
1110 case Intrinsic::amdgcn_buffer_atomic_fadd: {
1111 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1112
1113 Info.opc = ISD::INTRINSIC_W_CHAIN;
1114 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1115 Info.ptrVal =
1116 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1117 Info.align.reset();
1118 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1119
1120 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1121 if (!Vol || !Vol->isZero())
1122 Info.flags |= MachineMemOperand::MOVolatile;
1123
1124 return true;
1125 }
1126 case Intrinsic::amdgcn_ds_append:
1127 case Intrinsic::amdgcn_ds_consume: {
1128 Info.opc = ISD::INTRINSIC_W_CHAIN;
1129 Info.memVT = MVT::getVT(CI.getType());
1130 Info.ptrVal = CI.getOperand(0);
1131 Info.align.reset();
1132 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1133
1134 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1135 if (!Vol->isZero())
1136 Info.flags |= MachineMemOperand::MOVolatile;
1137
1138 return true;
1139 }
1140 case Intrinsic::amdgcn_global_atomic_csub: {
1141 Info.opc = ISD::INTRINSIC_W_CHAIN;
1142 Info.memVT = MVT::getVT(CI.getType());
1143 Info.ptrVal = CI.getOperand(0);
1144 Info.align.reset();
1145 Info.flags = MachineMemOperand::MOLoad |
1146 MachineMemOperand::MOStore |
1147 MachineMemOperand::MOVolatile;
1148 return true;
1149 }
1150 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1152 Info.opc = ISD::INTRINSIC_W_CHAIN;
1153 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1154 Info.ptrVal =
1155 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1156 Info.align.reset();
1157 Info.flags = MachineMemOperand::MOLoad |
1158 MachineMemOperand::MODereferenceable;
1159 return true;
1160 }
1161 case Intrinsic::amdgcn_global_atomic_fadd:
1162 case Intrinsic::amdgcn_global_atomic_fmin:
1163 case Intrinsic::amdgcn_global_atomic_fmax:
1164 case Intrinsic::amdgcn_flat_atomic_fadd:
1165 case Intrinsic::amdgcn_flat_atomic_fmin:
1166 case Intrinsic::amdgcn_flat_atomic_fmax: {
1167 Info.opc = ISD::INTRINSIC_W_CHAIN;
1168 Info.memVT = MVT::getVT(CI.getType());
1169 Info.ptrVal = CI.getOperand(0);
1170 Info.align.reset();
1171 Info.flags = MachineMemOperand::MOLoad |
1172 MachineMemOperand::MOStore |
1173 MachineMemOperand::MODereferenceable |
1174 MachineMemOperand::MOVolatile;
1175 return true;
1176 }
1177 case Intrinsic::amdgcn_ds_gws_init:
1178 case Intrinsic::amdgcn_ds_gws_barrier:
1179 case Intrinsic::amdgcn_ds_gws_sema_v:
1180 case Intrinsic::amdgcn_ds_gws_sema_br:
1181 case Intrinsic::amdgcn_ds_gws_sema_p:
1182 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1183 Info.opc = ISD::INTRINSIC_VOID;
1184
1185 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1186 Info.ptrVal =
1187 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1188
1189 // This is an abstract access, but we need to specify a type and size.
1190 Info.memVT = MVT::i32;
1191 Info.size = 4;
1192 Info.align = Align(4);
1193
1194 Info.flags = MachineMemOperand::MOStore;
1195 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1196 Info.flags = MachineMemOperand::MOLoad;
1197 return true;
1198 }
1199 default:
1200 return false;
1201 }
1202}
1203
1204bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1205 SmallVectorImpl<Value*> &Ops,
1206 Type *&AccessTy) const {
1207 switch (II->getIntrinsicID()) {
1208 case Intrinsic::amdgcn_atomic_inc:
1209 case Intrinsic::amdgcn_atomic_dec:
1210 case Intrinsic::amdgcn_ds_ordered_add:
1211 case Intrinsic::amdgcn_ds_ordered_swap:
1212 case Intrinsic::amdgcn_ds_append:
1213 case Intrinsic::amdgcn_ds_consume:
1214 case Intrinsic::amdgcn_ds_fadd:
1215 case Intrinsic::amdgcn_ds_fmin:
1216 case Intrinsic::amdgcn_ds_fmax:
1217 case Intrinsic::amdgcn_global_atomic_fadd:
1218 case Intrinsic::amdgcn_flat_atomic_fadd:
1219 case Intrinsic::amdgcn_flat_atomic_fmin:
1220 case Intrinsic::amdgcn_flat_atomic_fmax:
1221 case Intrinsic::amdgcn_global_atomic_csub: {
1222 Value *Ptr = II->getArgOperand(0);
1223 AccessTy = II->getType();
1224 Ops.push_back(Ptr);
1225 return true;
1226 }
1227 default:
1228 return false;
1229 }
1230}
1231
1232bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1233 if (!Subtarget->hasFlatInstOffsets()) {
1234 // Flat instructions do not have offsets, and only have the register
1235 // address.
1236 return AM.BaseOffs == 0 && AM.Scale == 0;
1237 }
1238
1239 return AM.Scale == 0 &&
1240 (AM.BaseOffs == 0 ||
1241 Subtarget->getInstrInfo()->isLegalFLATOffset(
1242 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1243}
1244
1245bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1246 if (Subtarget->hasFlatGlobalInsts())
1247 return AM.Scale == 0 &&
1248 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1249 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1250 SIInstrFlags::FlatGlobal));
1251
1252 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1253 // Assume the we will use FLAT for all global memory accesses
1254 // on VI.
1255 // FIXME: This assumption is currently wrong. On VI we still use
1256 // MUBUF instructions for the r + i addressing mode. As currently
1257 // implemented, the MUBUF instructions only work on buffer < 4GB.
1258 // It may be possible to support > 4GB buffers with MUBUF instructions,
1259 // by setting the stride value in the resource descriptor which would
1260 // increase the size limit to (stride * 4GB). However, this is risky,
1261 // because it has never been validated.
1262 return isLegalFlatAddressingMode(AM);
1263 }
1264
1265 return isLegalMUBUFAddressingMode(AM);
1266}
1267
1268bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1269 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1270 // additionally can do r + r + i with addr64. 32-bit has more addressing
1271 // mode options. Depending on the resource constant, it can also do
1272 // (i64 r0) + (i32 r1) * (i14 i).
1273 //
1274 // Private arrays end up using a scratch buffer most of the time, so also
1275 // assume those use MUBUF instructions. Scratch loads / stores are currently
1276 // implemented as mubuf instructions with offen bit set, so slightly
1277 // different than the normal addr64.
1278 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1279 return false;
1280
1281 // FIXME: Since we can split immediate into soffset and immediate offset,
1282 // would it make sense to allow any immediate?
1283
1284 switch (AM.Scale) {
1285 case 0: // r + i or just i, depending on HasBaseReg.
1286 return true;
1287 case 1:
1288 return true; // We have r + r or r + i.
1289 case 2:
1290 if (AM.HasBaseReg) {
1291 // Reject 2 * r + r.
1292 return false;
1293 }
1294
1295 // Allow 2 * r as r + r
1296 // Or 2 * r + i is allowed as r + r + i.
1297 return true;
1298 default: // Don't allow n * r
1299 return false;
1300 }
1301}
1302
1303bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1304 const AddrMode &AM, Type *Ty,
1305 unsigned AS, Instruction *I) const {
1306 // No global is ever allowed as a base.
1307 if (AM.BaseGV)
1308 return false;
1309
1310 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1311 return isLegalGlobalAddressingMode(AM);
1312
1313 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1314 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1315 AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1316 // If the offset isn't a multiple of 4, it probably isn't going to be
1317 // correctly aligned.
1318 // FIXME: Can we get the real alignment here?
1319 if (AM.BaseOffs % 4 != 0)
1320 return isLegalMUBUFAddressingMode(AM);
1321
1322 // There are no SMRD extloads, so if we have to do a small type access we
1323 // will use a MUBUF load.
1324 // FIXME?: We also need to do this if unaligned, but we don't know the
1325 // alignment here.
1326 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1327 return isLegalGlobalAddressingMode(AM);
1328
1329 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1330 // SMRD instructions have an 8-bit, dword offset on SI.
1331 if (!isUInt<8>(AM.BaseOffs / 4))
1332 return false;
1333 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1334 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1335 // in 8-bits, it can use a smaller encoding.
1336 if (!isUInt<32>(AM.BaseOffs / 4))
1337 return false;
1338 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1339 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1340 if (!isUInt<20>(AM.BaseOffs))
1341 return false;
1342 } else
1343 llvm_unreachable("unhandled generation")::llvm::llvm_unreachable_internal("unhandled generation", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1343)
;
1344
1345 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1346 return true;
1347
1348 if (AM.Scale == 1 && AM.HasBaseReg)
1349 return true;
1350
1351 return false;
1352
1353 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1354 return isLegalMUBUFAddressingMode(AM);
1355 } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1356 AS == AMDGPUAS::REGION_ADDRESS) {
1357 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1358 // field.
1359 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1360 // an 8-bit dword offset but we don't know the alignment here.
1361 if (!isUInt<16>(AM.BaseOffs))
1362 return false;
1363
1364 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1365 return true;
1366
1367 if (AM.Scale == 1 && AM.HasBaseReg)
1368 return true;
1369
1370 return false;
1371 } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1372 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1373 // For an unknown address space, this usually means that this is for some
1374 // reason being used for pure arithmetic, and not based on some addressing
1375 // computation. We don't have instructions that compute pointers with any
1376 // addressing modes, so treat them as having no offset like flat
1377 // instructions.
1378 return isLegalFlatAddressingMode(AM);
1379 }
1380
1381 // Assume a user alias of global for unknown address spaces.
1382 return isLegalGlobalAddressingMode(AM);
1383}
1384
1385bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1386 const SelectionDAG &DAG) const {
1387 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1388 return (MemVT.getSizeInBits() <= 4 * 32);
1389 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1390 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1391 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1392 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1393 return (MemVT.getSizeInBits() <= 2 * 32);
1394 }
1395 return true;
1396}
1397
1398bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1399 unsigned Size, unsigned AddrSpace, Align Alignment,
1400 MachineMemOperand::Flags Flags, bool *IsFast) const {
1401 if (IsFast)
1402 *IsFast = false;
1403
1404 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1405 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1406 // Check if alignment requirements for ds_read/write instructions are
1407 // disabled.
1408 if (Subtarget->hasUnalignedDSAccessEnabled() &&
1409 !Subtarget->hasLDSMisalignedBug()) {
1410 if (IsFast)
1411 *IsFast = Alignment != Align(2);
1412 return true;
1413 }
1414
1415 if (Size == 64) {
1416 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1417 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1418 // with adjacent offsets.
1419 bool AlignedBy4 = Alignment >= Align(4);
1420 if (IsFast)
1421 *IsFast = AlignedBy4;
1422
1423 return AlignedBy4;
1424 }
1425 if (Size == 96) {
1426 // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1427 bool Aligned = Alignment >= Align(16);
1428 if (IsFast)
1429 *IsFast = Aligned;
1430
1431 return Aligned;
1432 }
1433 if (Size == 128) {
1434 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1435 // can do a 8 byte aligned, 16 byte access in a single operation using
1436 // ds_read2/write2_b64.
1437 bool Aligned = Alignment >= Align(8);
1438 if (IsFast)
1439 *IsFast = Aligned;
1440
1441 return Aligned;
1442 }
1443 }
1444
1445 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1446 bool AlignedBy4 = Alignment >= Align(4);
1447 if (IsFast)
1448 *IsFast = AlignedBy4;
1449
1450 return AlignedBy4 ||
1451 Subtarget->enableFlatScratch() ||
1452 Subtarget->hasUnalignedScratchAccess();
1453 }
1454
1455 // FIXME: We have to be conservative here and assume that flat operations
1456 // will access scratch. If we had access to the IR function, then we
1457 // could determine if any private memory was used in the function.
1458 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1459 !Subtarget->hasUnalignedScratchAccess()) {
1460 bool AlignedBy4 = Alignment >= Align(4);
1461 if (IsFast)
1462 *IsFast = AlignedBy4;
1463
1464 return AlignedBy4;
1465 }
1466
1467 if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1468 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1469 AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1470 // If we have an uniform constant load, it still requires using a slow
1471 // buffer instruction if unaligned.
1472 if (IsFast) {
1473 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1474 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1475 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1476 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1477 Alignment >= Align(4) : Alignment != Align(2);
1478 }
1479
1480 return true;
1481 }
1482
1483 // Smaller than dword value must be aligned.
1484 if (Size < 32)
1485 return false;
1486
1487 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1488 // byte-address are ignored, thus forcing Dword alignment.
1489 // This applies to private, global, and constant memory.
1490 if (IsFast)
1491 *IsFast = true;
1492
1493 return Size >= 32 && Alignment >= Align(4);
1494}
1495
1496bool SITargetLowering::allowsMisalignedMemoryAccesses(
1497 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1498 bool *IsFast) const {
1499 if (IsFast)
1500 *IsFast = false;
1501
1502 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1503 // which isn't a simple VT.
1504 // Until MVT is extended to handle this, simply check for the size and
1505 // rely on the condition below: allow accesses if the size is a multiple of 4.
1506 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1507 VT.getStoreSize() > 16)) {
1508 return false;
1509 }
1510
1511 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1512 Alignment, Flags, IsFast);
1513}
1514
1515EVT SITargetLowering::getOptimalMemOpType(
1516 const MemOp &Op, const AttributeList &FuncAttributes) const {
1517 // FIXME: Should account for address space here.
1518
1519 // The default fallback uses the private pointer size as a guess for a type to
1520 // use. Make sure we switch these to 64-bit accesses.
1521
1522 if (Op.size() >= 16 &&
1523 Op.isDstAligned(Align(4))) // XXX: Should only do for global
1524 return MVT::v4i32;
1525
1526 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1527 return MVT::v2i32;
1528
1529 // Use the default.
1530 return MVT::Other;
1531}
1532
1533bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1534 const MemSDNode *MemNode = cast<MemSDNode>(N);
1535 const Value *Ptr = MemNode->getMemOperand()->getValue();
1536 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1537 return I && I->getMetadata("amdgpu.noclobber");
1538}
1539
1540bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1541 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1542 AS == AMDGPUAS::PRIVATE_ADDRESS;
1543}
1544
1545bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1546 unsigned DestAS) const {
1547 // Flat -> private/local is a simple truncate.
1548 // Flat -> global is no-op
1549 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1550 return true;
1551
1552 const GCNTargetMachine &TM =
1553 static_cast<const GCNTargetMachine &>(getTargetMachine());
1554 return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1555}
1556
1557bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1558 const MemSDNode *MemNode = cast<MemSDNode>(N);
1559
1560 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1561}
1562
1563TargetLoweringBase::LegalizeTypeAction
1564SITargetLowering::getPreferredVectorAction(MVT VT) const {
1565 int NumElts = VT.getVectorNumElements();
1566 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1567 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1568 return TargetLoweringBase::getPreferredVectorAction(VT);
1569}
1570
1571bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1572 Type *Ty) const {
1573 // FIXME: Could be smarter if called for vector constants.
1574 return true;
1575}
1576
1577bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1578 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1579 switch (Op) {
1580 case ISD::LOAD:
1581 case ISD::STORE:
1582
1583 // These operations are done with 32-bit instructions anyway.
1584 case ISD::AND:
1585 case ISD::OR:
1586 case ISD::XOR:
1587 case ISD::SELECT:
1588 // TODO: Extensions?
1589 return true;
1590 default:
1591 return false;
1592 }
1593 }
1594
1595 // SimplifySetCC uses this function to determine whether or not it should
1596 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1597 if (VT == MVT::i1 && Op == ISD::SETCC)
1598 return false;
1599
1600 return TargetLowering::isTypeDesirableForOp(Op, VT);
1601}
1602
1603SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1604 const SDLoc &SL,
1605 SDValue Chain,
1606 uint64_t Offset) const {
1607 const DataLayout &DL = DAG.getDataLayout();
1608 MachineFunction &MF = DAG.getMachineFunction();
1609 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1610
1611 const ArgDescriptor *InputPtrReg;
1612 const TargetRegisterClass *RC;
1613 LLT ArgTy;
1614
1615 std::tie(InputPtrReg, RC, ArgTy) =
1616 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1617
1618 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1619 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1620 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1621 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1622
1623 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1624}
1625
1626SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1627 const SDLoc &SL) const {
1628 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1629 FIRST_IMPLICIT);
1630 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1631}
1632
1633SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1634 const SDLoc &SL, SDValue Val,
1635 bool Signed,
1636 const ISD::InputArg *Arg) const {
1637 // First, if it is a widened vector, narrow it.
1638 if (VT.isVector() &&
1639 VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1640 EVT NarrowedVT =
1641 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1642 VT.getVectorNumElements());
1643 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1644 DAG.getConstant(0, SL, MVT::i32));
1645 }
1646
1647 // Then convert the vector elements or scalar value.
1648 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1649 VT.bitsLT(MemVT)) {
1650 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1651 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1652 }
1653
1654 if (MemVT.isFloatingPoint())
1655 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1656 else if (Signed)
1657 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1658 else
1659 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1660
1661 return Val;
1662}
1663
1664SDValue SITargetLowering::lowerKernargMemParameter(
1665 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1666 uint64_t Offset, Align Alignment, bool Signed,
1667 const ISD::InputArg *Arg) const {
1668 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1669
1670 // Try to avoid using an extload by loading earlier than the argument address,
1671 // and extracting the relevant bits. The load should hopefully be merged with
1672 // the previous argument.
1673 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1674 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1675 int64_t AlignDownOffset = alignDown(Offset, 4);
1676 int64_t OffsetDiff = Offset - AlignDownOffset;
1677
1678 EVT IntVT = MemVT.changeTypeToInteger();
1679
1680 // TODO: If we passed in the base kernel offset we could have a better
1681 // alignment than 4, but we don't really need it.
1682 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1683 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1684 MachineMemOperand::MODereferenceable |
1685 MachineMemOperand::MOInvariant);
1686
1687 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1688 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1689
1690 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1691 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1692 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1693
1694
1695 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1696 }
1697
1698 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1699 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1700 MachineMemOperand::MODereferenceable |
1701 MachineMemOperand::MOInvariant);
1702
1703 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1704 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1705}
1706
1707SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1708 const SDLoc &SL, SDValue Chain,
1709 const ISD::InputArg &Arg) const {
1710 MachineFunction &MF = DAG.getMachineFunction();
1711 MachineFrameInfo &MFI = MF.getFrameInfo();
1712
1713 if (Arg.Flags.isByVal()) {
1714 unsigned Size = Arg.Flags.getByValSize();
1715 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1716 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1717 }
1718
1719 unsigned ArgOffset = VA.getLocMemOffset();
1720 unsigned ArgSize = VA.getValVT().getStoreSize();
1721
1722 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1723
1724 // Create load nodes to retrieve arguments from the stack.
1725 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1726 SDValue ArgValue;
1727
1728 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1729 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1730 MVT MemVT = VA.getValVT();
1731
1732 switch (VA.getLocInfo()) {
1733 default:
1734 break;
1735 case CCValAssign::BCvt:
1736 MemVT = VA.getLocVT();
1737 break;
1738 case CCValAssign::SExt:
1739 ExtType = ISD::SEXTLOAD;
1740 break;
1741 case CCValAssign::ZExt:
1742 ExtType = ISD::ZEXTLOAD;
1743 break;
1744 case CCValAssign::AExt:
1745 ExtType = ISD::EXTLOAD;
1746 break;
1747 }
1748
1749 ArgValue = DAG.getExtLoad(
1750 ExtType, SL, VA.getLocVT(), Chain, FIN,
1751 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1752 MemVT);
1753 return ArgValue;
1754}
1755
1756SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1757 const SIMachineFunctionInfo &MFI,
1758 EVT VT,
1759 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1760 const ArgDescriptor *Reg;
1761 const TargetRegisterClass *RC;
1762 LLT Ty;
1763
1764 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1765 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1766}
1767
1768static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1769 CallingConv::ID CallConv,
1770 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1771 FunctionType *FType,
1772 SIMachineFunctionInfo *Info) {
1773 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1774 const ISD::InputArg *Arg = &Ins[I];
1775
1776 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "vector type argument should have been split"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1777, __PRETTY_FUNCTION__))
1777 "vector type argument should have been split")(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "vector type argument should have been split"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1777, __PRETTY_FUNCTION__))
;
1778
1779 // First check if it's a PS input addr.
1780 if (CallConv == CallingConv::AMDGPU_PS &&
1781 !Arg->Flags.isInReg() && PSInputNum <= 15) {
1782 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1783
1784 // Inconveniently only the first part of the split is marked as isSplit,
1785 // so skip to the end. We only want to increment PSInputNum once for the
1786 // entire split argument.
1787 if (Arg->Flags.isSplit()) {
1788 while (!Arg->Flags.isSplitEnd()) {
1789 assert((!Arg->VT.isVector() ||(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "unexpected vector split in ps argument type"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1791, __PRETTY_FUNCTION__))
1790 Arg->VT.getScalarSizeInBits() == 16) &&(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "unexpected vector split in ps argument type"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1791, __PRETTY_FUNCTION__))
1791 "unexpected vector split in ps argument type")(((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits()
== 16) && "unexpected vector split in ps argument type"
) ? static_cast<void> (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1791, __PRETTY_FUNCTION__))
;
1792 if (!SkipArg)
1793 Splits.push_back(*Arg);
1794 Arg = &Ins[++I];
1795 }
1796 }
1797
1798 if (SkipArg) {
1799 // We can safely skip PS inputs.
1800 Skipped.set(Arg->getOrigArgIndex());
1801 ++PSInputNum;
1802 continue;
1803 }
1804
1805 Info->markPSInputAllocated(PSInputNum);
1806 if (Arg->Used)
1807 Info->markPSInputEnabled(PSInputNum);
1808
1809 ++PSInputNum;
1810 }
1811
1812 Splits.push_back(*Arg);
1813 }
1814}
1815
1816// Allocate special inputs passed in VGPRs.
1817void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1818 MachineFunction &MF,
1819 const SIRegisterInfo &TRI,
1820 SIMachineFunctionInfo &Info) const {
1821 const LLT S32 = LLT::scalar(32);
1822 MachineRegisterInfo &MRI = MF.getRegInfo();
1823
1824 if (Info.hasWorkItemIDX()) {
1825 Register Reg = AMDGPU::VGPR0;
1826 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1827
1828 CCInfo.AllocateReg(Reg);
1829 unsigned Mask = (Subtarget->hasPackedTID() &&
1830 Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1831 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1832 }
1833
1834 if (Info.hasWorkItemIDY()) {
1835 assert(Info.hasWorkItemIDX())((Info.hasWorkItemIDX()) ? static_cast<void> (0) : __assert_fail
("Info.hasWorkItemIDX()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1835, __PRETTY_FUNCTION__))
;
1836 if (Subtarget->hasPackedTID()) {
1837 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1838 0x3ff << 10));
1839 } else {
1840 unsigned Reg = AMDGPU::VGPR1;
1841 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1842
1843 CCInfo.AllocateReg(Reg);
1844 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1845 }
1846 }
1847
1848 if (Info.hasWorkItemIDZ()) {
1849 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY())((Info.hasWorkItemIDX() && Info.hasWorkItemIDY()) ? static_cast
<void> (0) : __assert_fail ("Info.hasWorkItemIDX() && Info.hasWorkItemIDY()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1849, __PRETTY_FUNCTION__))
;
1850 if (Subtarget->hasPackedTID()) {
1851 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1852 0x3ff << 20));
1853 } else {
1854 unsigned Reg = AMDGPU::VGPR2;
1855 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1856
1857 CCInfo.AllocateReg(Reg);
1858 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1859 }
1860 }
1861}
1862
1863// Try to allocate a VGPR at the end of the argument list, or if no argument
1864// VGPRs are left allocating a stack slot.
1865// If \p Mask is is given it indicates bitfield position in the register.
1866// If \p Arg is given use it with new ]p Mask instead of allocating new.
1867static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1868 ArgDescriptor Arg = ArgDescriptor()) {
1869 if (Arg.isSet())
1870 return ArgDescriptor::createArg(Arg, Mask);
1871
1872 ArrayRef<MCPhysReg> ArgVGPRs
1873 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1874 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1875 if (RegIdx == ArgVGPRs.size()) {
1876 // Spill to stack required.
1877 int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1878
1879 return ArgDescriptor::createStack(Offset, Mask);
1880 }
1881
1882 unsigned Reg = ArgVGPRs[RegIdx];
1883 Reg = CCInfo.AllocateReg(Reg);
1884 assert(Reg != AMDGPU::NoRegister)((Reg != AMDGPU::NoRegister) ? static_cast<void> (0) : __assert_fail
("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1884, __PRETTY_FUNCTION__))
;
1885
1886 MachineFunction &MF = CCInfo.getMachineFunction();
1887 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1888 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1889 return ArgDescriptor::createRegister(Reg, Mask);
1890}
1891
1892static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1893 const TargetRegisterClass *RC,
1894 unsigned NumArgRegs) {
1895 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1896 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1897 if (RegIdx == ArgSGPRs.size())
1898 report_fatal_error("ran out of SGPRs for arguments");
1899
1900 unsigned Reg = ArgSGPRs[RegIdx];
1901 Reg = CCInfo.AllocateReg(Reg);
1902 assert(Reg != AMDGPU::NoRegister)((Reg != AMDGPU::NoRegister) ? static_cast<void> (0) : __assert_fail
("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1902, __PRETTY_FUNCTION__))
;
1903
1904 MachineFunction &MF = CCInfo.getMachineFunction();
1905 MF.addLiveIn(Reg, RC);
1906 return ArgDescriptor::createRegister(Reg);
1907}
1908
1909// If this has a fixed position, we still should allocate the register in the
1910// CCInfo state. Technically we could get away with this for values passed
1911// outside of the normal argument range.
1912static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1913 const TargetRegisterClass *RC,
1914 MCRegister Reg) {
1915 Reg = CCInfo.AllocateReg(Reg);
1916 assert(Reg != AMDGPU::NoRegister)((Reg != AMDGPU::NoRegister) ? static_cast<void> (0) : __assert_fail
("Reg != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1916, __PRETTY_FUNCTION__))
;
1917 MachineFunction &MF = CCInfo.getMachineFunction();
1918 MF.addLiveIn(Reg, RC);
1919}
1920
1921static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1922 if (Arg) {
1923 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1924 Arg.getRegister());
1925 } else
1926 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1927}
1928
1929static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1930 if (Arg) {
1931 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1932 Arg.getRegister());
1933 } else
1934 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1935}
1936
1937/// Allocate implicit function VGPR arguments at the end of allocated user
1938/// arguments.
1939void SITargetLowering::allocateSpecialInputVGPRs(
1940 CCState &CCInfo, MachineFunction &MF,
1941 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1942 const unsigned Mask = 0x3ff;
1943 ArgDescriptor Arg;
1944
1945 if (Info.hasWorkItemIDX()) {
1946 Arg = allocateVGPR32Input(CCInfo, Mask);
1947 Info.setWorkItemIDX(Arg);
1948 }
1949
1950 if (Info.hasWorkItemIDY()) {
1951 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1952 Info.setWorkItemIDY(Arg);
1953 }
1954
1955 if (Info.hasWorkItemIDZ())
1956 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1957}
1958
1959/// Allocate implicit function VGPR arguments in fixed registers.
1960void SITargetLowering::allocateSpecialInputVGPRsFixed(
1961 CCState &CCInfo, MachineFunction &MF,
1962 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1963 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1964 if (!Reg)
1965 report_fatal_error("failed to allocated VGPR for implicit arguments");
1966
1967 const unsigned Mask = 0x3ff;
1968 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1969 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1970 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1971}
1972
1973void SITargetLowering::allocateSpecialInputSGPRs(
1974 CCState &CCInfo,
1975 MachineFunction &MF,
1976 const SIRegisterInfo &TRI,
1977 SIMachineFunctionInfo &Info) const {
1978 auto &ArgInfo = Info.getArgInfo();
1979
1980 // TODO: Unify handling with private memory pointers.
1981
1982 if (Info.hasDispatchPtr())
1983 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
1984
1985 if (Info.hasQueuePtr())
1986 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
1987
1988 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1989 // constant offset from the kernarg segment.
1990 if (Info.hasImplicitArgPtr())
1991 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
1992
1993 if (Info.hasDispatchID())
1994 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
1995
1996 // flat_scratch_init is not applicable for non-kernel functions.
1997
1998 if (Info.hasWorkGroupIDX())
1999 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2000
2001 if (Info.hasWorkGroupIDY())
2002 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2003
2004 if (Info.hasWorkGroupIDZ())
2005 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2006}
2007
2008// Allocate special inputs passed in user SGPRs.
2009void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2010 MachineFunction &MF,
2011 const SIRegisterInfo &TRI,
2012 SIMachineFunctionInfo &Info) const {
2013 if (Info.hasImplicitBufferPtr()) {
2014 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2015 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2016 CCInfo.AllocateReg(ImplicitBufferPtrReg);
2017 }
2018
2019 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2020 if (Info.hasPrivateSegmentBuffer()) {
2021 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2022 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2023 CCInfo.AllocateReg(PrivateSegmentBufferReg);
2024 }
2025
2026 if (Info.hasDispatchPtr()) {
2027 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2028 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2029 CCInfo.AllocateReg(DispatchPtrReg);
2030 }
2031
2032 if (Info.hasQueuePtr()) {
2033 Register QueuePtrReg = Info.addQueuePtr(TRI);
2034 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2035 CCInfo.AllocateReg(QueuePtrReg);
2036 }
2037
2038 if (Info.hasKernargSegmentPtr()) {
2039 MachineRegisterInfo &MRI = MF.getRegInfo();
2040 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2041 CCInfo.AllocateReg(InputPtrReg);
2042
2043 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2044 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2045 }
2046
2047 if (Info.hasDispatchID()) {
2048 Register DispatchIDReg = Info.addDispatchID(TRI);
2049 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2050 CCInfo.AllocateReg(DispatchIDReg);
2051 }
2052
2053 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2054 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2055 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2056 CCInfo.AllocateReg(FlatScratchInitReg);
2057 }
2058
2059 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2060 // these from the dispatch pointer.
2061}
2062
2063// Allocate special input registers that are initialized per-wave.
2064void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2065 MachineFunction &MF,
2066 SIMachineFunctionInfo &Info,
2067 CallingConv::ID CallConv,
2068 bool IsShader) const {
2069 if (Info.hasWorkGroupIDX()) {
2070 Register Reg = Info.addWorkGroupIDX();
2071 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2072 CCInfo.AllocateReg(Reg);
2073 }
2074
2075 if (Info.hasWorkGroupIDY()) {
2076 Register Reg = Info.addWorkGroupIDY();
2077 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2078 CCInfo.AllocateReg(Reg);
2079 }
2080
2081 if (Info.hasWorkGroupIDZ()) {
2082 Register Reg = Info.addWorkGroupIDZ();
2083 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2084 CCInfo.AllocateReg(Reg);
2085 }
2086
2087 if (Info.hasWorkGroupInfo()) {
2088 Register Reg = Info.addWorkGroupInfo();
2089 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2090 CCInfo.AllocateReg(Reg);
2091 }
2092
2093 if (Info.hasPrivateSegmentWaveByteOffset()) {
2094 // Scratch wave offset passed in system SGPR.
2095 unsigned PrivateSegmentWaveByteOffsetReg;
2096
2097 if (IsShader) {
2098 PrivateSegmentWaveByteOffsetReg =
2099 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2100
2101 // This is true if the scratch wave byte offset doesn't have a fixed
2102 // location.
2103 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2104 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2105 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2106 }
2107 } else
2108 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2109
2110 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2111 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2112 }
2113}
2114
2115static void reservePrivateMemoryRegs(const TargetMachine &TM,
2116 MachineFunction &MF,
2117 const SIRegisterInfo &TRI,
2118 SIMachineFunctionInfo &Info) {
2119 // Now that we've figured out where the scratch register inputs are, see if
2120 // should reserve the arguments and use them directly.
2121 MachineFrameInfo &MFI = MF.getFrameInfo();
2122 bool HasStackObjects = MFI.hasStackObjects();
2123 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2124
2125 // Record that we know we have non-spill stack objects so we don't need to
2126 // check all stack objects later.
2127 if (HasStackObjects)
2128 Info.setHasNonSpillStackObjects(true);
2129
2130 // Everything live out of a block is spilled with fast regalloc, so it's
2131 // almost certain that spilling will be required.
2132 if (TM.getOptLevel() == CodeGenOpt::None)
2133 HasStackObjects = true;
2134
2135 // For now assume stack access is needed in any callee functions, so we need
2136 // the scratch registers to pass in.
2137 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2138
2139 if (!ST.enableFlatScratch()) {
2140 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2141 // If we have stack objects, we unquestionably need the private buffer
2142 // resource. For the Code Object V2 ABI, this will be the first 4 user
2143 // SGPR inputs. We can reserve those and use them directly.
2144
2145 Register PrivateSegmentBufferReg =
2146 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2147 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2148 } else {
2149 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2150 // We tentatively reserve the last registers (skipping the last registers
2151 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2152 // we'll replace these with the ones immediately after those which were
2153 // really allocated. In the prologue copies will be inserted from the
2154 // argument to these reserved registers.
2155
2156 // Without HSA, relocations are used for the scratch pointer and the
2157 // buffer resource setup is always inserted in the prologue. Scratch wave
2158 // offset is still in an input SGPR.
2159 Info.setScratchRSrcReg(ReservedBufferReg);
2160 }
2161 }
2162
2163 MachineRegisterInfo &MRI = MF.getRegInfo();
2164
2165 // For entry functions we have to set up the stack pointer if we use it,
2166 // whereas non-entry functions get this "for free". This means there is no
2167 // intrinsic advantage to using S32 over S34 in cases where we do not have
2168 // calls but do need a frame pointer (i.e. if we are requested to have one
2169 // because frame pointer elimination is disabled). To keep things simple we
2170 // only ever use S32 as the call ABI stack pointer, and so using it does not
2171 // imply we need a separate frame pointer.
2172 //
2173 // Try to use s32 as the SP, but move it if it would interfere with input
2174 // arguments. This won't work with calls though.
2175 //
2176 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2177 // registers.
2178 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2179 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2180 } else {
2181 assert(AMDGPU::isShader(MF.getFunction().getCallingConv()))((AMDGPU::isShader(MF.getFunction().getCallingConv())) ? static_cast
<void> (0) : __assert_fail ("AMDGPU::isShader(MF.getFunction().getCallingConv())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2181, __PRETTY_FUNCTION__))
;
2182
2183 if (MFI.hasCalls())
2184 report_fatal_error("call in graphics shader with too many input SGPRs");
2185
2186 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2187 if (!MRI.isLiveIn(Reg)) {
2188 Info.setStackPtrOffsetReg(Reg);
2189 break;
2190 }
2191 }
2192
2193 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2194 report_fatal_error("failed to find register for SP");
2195 }
2196
2197 // hasFP should be accurate for entry functions even before the frame is
2198 // finalized, because it does not rely on the known stack size, only
2199 // properties like whether variable sized objects are present.
2200 if (ST.getFrameLowering()->hasFP(MF)) {
2201 Info.setFrameOffsetReg(AMDGPU::SGPR33);
2202 }
2203}
2204
2205bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2206 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2207 return !Info->isEntryFunction();
2208}
2209
2210void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2211
2212}
2213
2214void SITargetLowering::insertCopiesSplitCSR(
2215 MachineBasicBlock *Entry,
2216 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2217 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2218
2219 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2220 if (!IStart)
2221 return;
2222
2223 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2224 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2225 MachineBasicBlock::iterator MBBI = Entry->begin();
2226 for (const MCPhysReg *I = IStart; *I; ++I) {
2227 const TargetRegisterClass *RC = nullptr;
2228 if (AMDGPU::SReg_64RegClass.contains(*I))
2229 RC = &AMDGPU::SGPR_64RegClass;
2230 else if (AMDGPU::SReg_32RegClass.contains(*I))
2231 RC = &AMDGPU::SGPR_32RegClass;
2232 else
2233 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2233)
;
2234
2235 Register NewVR = MRI->createVirtualRegister(RC);
2236 // Create copy from CSR to a virtual register.
2237 Entry->addLiveIn(*I);
2238 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2239 .addReg(*I);
2240
2241 // Insert the copy-back instructions right before the terminator.
2242 for (auto *Exit : Exits)
2243 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2244 TII->get(TargetOpcode::COPY), *I)
2245 .addReg(NewVR);
2246 }
2247}
2248
2249SDValue SITargetLowering::LowerFormalArguments(
2250 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2251 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2252 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2253 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2254
2255 MachineFunction &MF = DAG.getMachineFunction();
2256 const Function &Fn = MF.getFunction();
2257 FunctionType *FType = MF.getFunction().getFunctionType();
2258 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2259
2260 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2261 DiagnosticInfoUnsupported NoGraphicsHSA(
2262 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2263 DAG.getContext()->diagnose(NoGraphicsHSA);
2264 return DAG.getEntryNode();
2265 }
2266
2267 Info->allocateModuleLDSGlobal(Fn.getParent());
2268
2269 SmallVector<ISD::InputArg, 16> Splits;
2270 SmallVector<CCValAssign, 16> ArgLocs;
2271 BitVector Skipped(Ins.size());
2272 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2273 *DAG.getContext());
2274
2275 bool IsGraphics = AMDGPU::isGraphics(CallConv);
2276 bool IsKernel = AMDGPU::isKernel(CallConv);
2277 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2278
2279 if (IsGraphics) {
2280 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && (!Info->hasFlatScratchInit() || Subtarget->
enableFlatScratch()) && !Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
() && !Info->hasWorkGroupInfo() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? static_cast<void> (0) : __assert_fail
("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2285, __PRETTY_FUNCTION__))
2281 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && (!Info->hasFlatScratchInit() || Subtarget->
enableFlatScratch()) && !Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
() && !Info->hasWorkGroupInfo() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? static_cast<void> (0) : __assert_fail
("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2285, __PRETTY_FUNCTION__))
2282 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && (!Info->hasFlatScratchInit() || Subtarget->
enableFlatScratch()) && !Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
() && !Info->hasWorkGroupInfo() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? static_cast<void> (0) : __assert_fail
("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2285, __PRETTY_FUNCTION__))
2283 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && (!Info->hasFlatScratchInit() || Subtarget->
enableFlatScratch()) && !Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
() && !Info->hasWorkGroupInfo() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? static_cast<void> (0) : __assert_fail
("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2285, __PRETTY_FUNCTION__))
2284 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && (!Info->hasFlatScratchInit() || Subtarget->
enableFlatScratch()) && !Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
() && !Info->hasWorkGroupInfo() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? static_cast<void> (0) : __assert_fail
("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2285, __PRETTY_FUNCTION__))
2285 !Info->hasWorkItemIDZ())((!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr
() && (!Info->hasFlatScratchInit() || Subtarget->
enableFlatScratch()) && !Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
() && !Info->hasWorkGroupInfo() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? static_cast<void> (0) : __assert_fail
("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2285, __PRETTY_FUNCTION__))
;
2286 }
2287
2288 if (CallConv == CallingConv::AMDGPU_PS) {
2289 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2290
2291 // At least one interpolation mode must be enabled or else the GPU will
2292 // hang.
2293 //
2294 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2295 // set PSInputAddr, the user wants to enable some bits after the compilation
2296 // based on run-time states. Since we can't know what the final PSInputEna
2297 // will look like, so we shouldn't do anything here and the user should take
2298 // responsibility for the correct programming.
2299 //
2300 // Otherwise, the following restrictions apply:
2301 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2302 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2303 // enabled too.
2304 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2305 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2306 CCInfo.AllocateReg(AMDGPU::VGPR0);
2307 CCInfo.AllocateReg(AMDGPU::VGPR1);
2308 Info->markPSInputAllocated(0);
2309 Info->markPSInputEnabled(0);
2310 }
2311 if (Subtarget->isAmdPalOS()) {
2312 // For isAmdPalOS, the user does not enable some bits after compilation
2313 // based on run-time states; the register values being generated here are
2314 // the final ones set in hardware. Therefore we need to apply the
2315 // workaround to PSInputAddr and PSInputEnable together. (The case where
2316 // a bit is set in PSInputAddr but not PSInputEnable is where the
2317 // frontend set up an input arg for a particular interpolation mode, but
2318 // nothing uses that input arg. Really we should have an earlier pass
2319 // that removes such an arg.)
2320 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2321 if ((PsInputBits & 0x7F) == 0 ||
2322 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2323 Info->markPSInputEnabled(
2324 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2325 }
2326 } else if (IsKernel) {
2327 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX())((Info->hasWorkGroupIDX() && Info->hasWorkItemIDX
()) ? static_cast<void> (0) : __assert_fail ("Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2327, __PRETTY_FUNCTION__))
;
2328 } else {
2329 Splits.append(Ins.begin(), Ins.end());
2330 }
2331
2332 if (IsEntryFunc) {
2333 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2334 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2335 } else {
2336 // For the fixed ABI, pass workitem IDs in the last argument register.
2337 if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2338 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2339 }
2340
2341 if (IsKernel) {
2342 analyzeFormalArgumentsCompute(CCInfo, Ins);
2343 } else {
2344 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2345 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2346 }
2347
2348 SmallVector<SDValue, 16> Chains;
2349
2350 // FIXME: This is the minimum kernel argument alignment. We should improve
2351 // this to the maximum alignment of the arguments.
2352 //
2353 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2354 // kern arg offset.
2355 const Align KernelArgBaseAlign = Align(16);
2356
2357 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2358 const ISD::InputArg &Arg = Ins[i];
2359 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2360 InVals.push_back(DAG.getUNDEF(Arg.VT));
2361 continue;
2362 }
2363
2364 CCValAssign &VA = ArgLocs[ArgIdx++];
2365 MVT VT = VA.getLocVT();
2366
2367 if (IsEntryFunc && VA.isMemLoc()) {
2368 VT = Ins[i].VT;
2369 EVT MemVT = VA.getLocVT();
2370
2371 const uint64_t Offset = VA.getLocMemOffset();
2372 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2373
2374 if (Arg.Flags.isByRef()) {
2375 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2376
2377 const GCNTargetMachine &TM =
2378 static_cast<const GCNTargetMachine &>(getTargetMachine());
2379 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2380 Arg.Flags.getPointerAddrSpace())) {
2381 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2382 Arg.Flags.getPointerAddrSpace());
2383 }
2384
2385 InVals.push_back(Ptr);
2386 continue;
2387 }
2388
2389 SDValue Arg = lowerKernargMemParameter(
2390 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2391 Chains.push_back(Arg.getValue(1));
2392
2393 auto *ParamTy =
2394 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2395 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2396 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2397 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2398 // On SI local pointers are just offsets into LDS, so they are always
2399 // less than 16-bits. On CI and newer they could potentially be
2400 // real pointers, so we can't guarantee their size.
2401 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2402 DAG.getValueType(MVT::i16));
2403 }
2404
2405 InVals.push_back(Arg);
2406 continue;
2407 } else if (!IsEntryFunc && VA.isMemLoc()) {
2408 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2409 InVals.push_back(Val);
2410 if (!Arg.Flags.isByVal())
2411 Chains.push_back(Val.getValue(1));
2412 continue;
2413 }
2414
2415 assert(VA.isRegLoc() && "Parameter must be in a register!")((VA.isRegLoc() && "Parameter must be in a register!"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Parameter must be in a register!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2415, __PRETTY_FUNCTION__))
;
2416
2417 Register Reg = VA.getLocReg();
2418 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2419 EVT ValVT = VA.getValVT();
2420
2421 Reg = MF.addLiveIn(Reg, RC);
2422 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2423
2424 if (Arg.Flags.isSRet()) {
2425 // The return object should be reasonably addressable.
2426
2427 // FIXME: This helps when the return is a real sret. If it is a
2428 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2429 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2430 unsigned NumBits
2431 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2432 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2433 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2434 }
2435
2436 // If this is an 8 or 16-bit value, it is really passed promoted
2437 // to 32 bits. Insert an assert[sz]ext to capture this, then
2438 // truncate to the right size.
2439 switch (VA.getLocInfo()) {
2440 case CCValAssign::Full:
2441 break;
2442 case CCValAssign::BCvt:
2443 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2444 break;
2445 case CCValAssign::SExt:
2446 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2447 DAG.getValueType(ValVT));
2448 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2449 break;
2450 case CCValAssign::ZExt:
2451 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2452 DAG.getValueType(ValVT));
2453 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2454 break;
2455 case CCValAssign::AExt:
2456 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2457 break;
2458 default:
2459 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2459)
;
2460 }
2461
2462 InVals.push_back(Val);
2463 }
2464
2465 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2466 // Special inputs come after user arguments.
2467 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2468 }
2469
2470 // Start adding system SGPRs.
2471 if (IsEntryFunc) {
2472 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2473 } else {
2474 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2475 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2476 }
2477
2478 auto &ArgUsageInfo =
2479 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2480 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2481
2482 unsigned StackArgSize = CCInfo.getNextStackOffset();
2483 Info->setBytesInStackArgArea(StackArgSize);
2484
2485 return Chains.empty() ? Chain :
2486 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2487}
2488
2489// TODO: If return values can't fit in registers, we should return as many as
2490// possible in registers before passing on stack.
2491bool SITargetLowering::CanLowerReturn(
2492 CallingConv::ID CallConv,
2493 MachineFunction &MF, bool IsVarArg,
2494 const SmallVectorImpl<ISD::OutputArg> &Outs,
2495 LLVMContext &Context) const {
2496 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2497 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2498 // for shaders. Vector types should be explicitly handled by CC.
2499 if (AMDGPU::isEntryFunctionCC(CallConv))
2500 return true;
2501
2502 SmallVector<CCValAssign, 16> RVLocs;
2503 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2504 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2505}
2506
2507SDValue
2508SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2509 bool isVarArg,
2510 const SmallVectorImpl<ISD::OutputArg> &Outs,
2511 const SmallVectorImpl<SDValue> &OutVals,
2512 const SDLoc &DL, SelectionDAG &DAG) const {
2513 MachineFunction &MF = DAG.getMachineFunction();
2514 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2515
2516 if (AMDGPU::isKernel(CallConv)) {
2517 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2518 OutVals, DL, DAG);
2519 }
2520
2521 bool IsShader = AMDGPU::isShader(CallConv);
2522
2523 Info->setIfReturnsVoid(Outs.empty());
2524 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2525
2526 // CCValAssign - represent the assignment of the return value to a location.
2527 SmallVector<CCValAssign, 48> RVLocs;
2528 SmallVector<ISD::OutputArg, 48> Splits;
2529
2530 // CCState - Info about the registers and stack slots.
2531 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2532 *DAG.getContext());
2533
2534 // Analyze outgoing return values.
2535 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2536
2537 SDValue Flag;
2538 SmallVector<SDValue, 48> RetOps;
2539 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2540
2541 // Add return address for callable functions.
2542 if (!Info->isEntryFunction()) {
2543 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2544 SDValue ReturnAddrReg = CreateLiveInRegister(
2545 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2546
2547 SDValue ReturnAddrVirtualReg = DAG.getRegister(
2548 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2549 MVT::i64);
2550 Chain =
2551 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2552 Flag = Chain.getValue(1);
2553 RetOps.push_back(ReturnAddrVirtualReg);
2554 }
2555
2556 // Copy the result values into the output registers.
2557 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2558 ++I, ++RealRVLocIdx) {
2559 CCValAssign &VA = RVLocs[I];
2560 assert(VA.isRegLoc() && "Can only return in registers!")((VA.isRegLoc() && "Can only return in registers!") ?
static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2560, __PRETTY_FUNCTION__))
;
2561 // TODO: Partially return in registers if return values don't fit.
2562 SDValue Arg = OutVals[RealRVLocIdx];
2563
2564 // Copied from other backends.
2565 switch (VA.getLocInfo()) {
2566 case CCValAssign::Full:
2567 break;
2568 case CCValAssign::BCvt:
2569 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2570 break;
2571 case CCValAssign::SExt:
2572 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2573 break;
2574 case CCValAssign::ZExt:
2575 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2576 break;
2577 case CCValAssign::AExt:
2578 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2579 break;
2580 default:
2581 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2581)
;
2582 }
2583
2584 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2585 Flag = Chain.getValue(1);
2586 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2587 }
2588
2589 // FIXME: Does sret work properly?
2590 if (!Info->isEntryFunction()) {
2591 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2592 const MCPhysReg *I =
2593 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2594 if (I) {
2595 for (; *I; ++I) {
2596 if (AMDGPU::SReg_64RegClass.contains(*I))
2597 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2598 else if (AMDGPU::SReg_32RegClass.contains(*I))
2599 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2600 else
2601 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2601)
;
2602 }
2603 }
2604 }
2605
2606 // Update chain and glue.
2607 RetOps[0] = Chain;
2608 if (Flag.getNode())
2609 RetOps.push_back(Flag);
2610
2611 unsigned Opc = AMDGPUISD::ENDPGM;
2612 if (!IsWaveEnd)
2613 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2614 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2615}
2616
2617SDValue SITargetLowering::LowerCallResult(
2618 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2619 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2620 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2621 SDValue ThisVal) const {
2622 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2623
2624 // Assign locations to each value returned by this call.
2625 SmallVector<CCValAssign, 16> RVLocs;
2626 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2627 *DAG.getContext());
2628 CCInfo.AnalyzeCallResult(Ins, RetCC);
2629
2630 // Copy all of the result registers out of their specified physreg.
2631 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2632 CCValAssign VA = RVLocs[i];
2633 SDValue Val;
2634
2635 if (VA.isRegLoc()) {
2636 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2637 Chain = Val.getValue(1);
2638 InFlag = Val.getValue(2);
2639 } else if (VA.isMemLoc()) {
2640 report_fatal_error("TODO: return values in memory");
2641 } else
2642 llvm_unreachable("unknown argument location type")::llvm::llvm_unreachable_internal("unknown argument location type"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2642)
;
2643
2644 switch (VA.getLocInfo()) {
2645 case CCValAssign::Full:
2646 break;
2647 case CCValAssign::BCvt:
2648 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2649 break;
2650 case CCValAssign::ZExt:
2651 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2652 DAG.getValueType(VA.getValVT()));
2653 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2654 break;
2655 case CCValAssign::SExt:
2656 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2657 DAG.getValueType(VA.getValVT()));
2658 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2659 break;
2660 case CCValAssign::AExt:
2661 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2662 break;
2663 default:
2664 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2664)
;
2665 }
2666
2667 InVals.push_back(Val);
2668 }
2669
2670 return Chain;
2671}
2672
2673// Add code to pass special inputs required depending on used features separate
2674// from the explicit user arguments present in the IR.
2675void SITargetLowering::passSpecialInputs(
2676 CallLoweringInfo &CLI,
2677 CCState &CCInfo,
2678 const SIMachineFunctionInfo &Info,
2679 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2680 SmallVectorImpl<SDValue> &MemOpChains,
2681 SDValue Chain) const {
2682 // If we don't have a call site, this was a call inserted by
2683 // legalization. These can never use special inputs.
2684 if (!CLI.CB)
2685 return;
2686
2687 SelectionDAG &DAG = CLI.DAG;
2688 const SDLoc &DL = CLI.DL;
2689
2690 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2691 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2692
2693 const AMDGPUFunctionArgInfo *CalleeArgInfo
2694 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2695 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2696 auto &ArgUsageInfo =
2697 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2698 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2699 }
2700
2701 // TODO: Unify with private memory register handling. This is complicated by
2702 // the fact that at least in kernels, the input argument is not necessarily
2703 // in the same location as the input.
2704 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2705 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2706 AMDGPUFunctionArgInfo::QUEUE_PTR,
2707 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2708 AMDGPUFunctionArgInfo::DISPATCH_ID,
2709 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2710 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2711 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2712 };
2713
2714 for (auto InputID : InputRegs) {
2715 const ArgDescriptor *OutgoingArg;
2716 const TargetRegisterClass *ArgRC;
2717 LLT ArgTy;
2718
2719 std::tie(OutgoingArg, ArgRC, ArgTy) =
2720 CalleeArgInfo->getPreloadedValue(InputID);
2721 if (!OutgoingArg)
2722 continue;
2723
2724 const ArgDescriptor *IncomingArg;
2725 const TargetRegisterClass *IncomingArgRC;
2726 LLT Ty;
2727 std::tie(IncomingArg, IncomingArgRC, Ty) =
2728 CallerArgInfo.getPreloadedValue(InputID);
2729 assert(IncomingArgRC == ArgRC)((IncomingArgRC == ArgRC) ? static_cast<void> (0) : __assert_fail
("IncomingArgRC == ArgRC", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2729, __PRETTY_FUNCTION__))
;
2730
2731 // All special arguments are ints for now.
2732 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2733 SDValue InputReg;
2734
2735 if (IncomingArg) {
2736 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2737 } else {
2738 // The implicit arg ptr is special because it doesn't have a corresponding
2739 // input for kernels, and is computed from the kernarg segment pointer.
2740 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR)((InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) ? static_cast
<void> (0) : __assert_fail ("InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2740, __PRETTY_FUNCTION__))
;
2741 InputReg = getImplicitArgPtr(DAG, DL);
2742 }
2743
2744 if (OutgoingArg->isRegister()) {
2745 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2746 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2747 report_fatal_error("failed to allocate implicit input argument");
2748 } else {
2749 unsigned SpecialArgOffset =
2750 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2751 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2752 SpecialArgOffset);
2753 MemOpChains.push_back(ArgStore);
2754 }
2755 }
2756
2757 // Pack workitem IDs into a single register or pass it as is if already
2758 // packed.
2759 const ArgDescriptor *OutgoingArg;
2760 const TargetRegisterClass *ArgRC;
2761 LLT Ty;
2762
2763 std::tie(OutgoingArg, ArgRC, Ty) =
2764 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2765 if (!OutgoingArg)
2766 std::tie(OutgoingArg, ArgRC, Ty) =
2767 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2768 if (!OutgoingArg)
2769 std::tie(OutgoingArg, ArgRC, Ty) =
2770 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2771 if (!OutgoingArg)
2772 return;
2773
2774 const ArgDescriptor *IncomingArgX = std::get<0>(
2775 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2776 const ArgDescriptor *IncomingArgY = std::get<0>(
2777 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2778 const ArgDescriptor *IncomingArgZ = std::get<0>(
2779 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2780
2781 SDValue InputReg;
2782 SDLoc SL;
2783
2784 // If incoming ids are not packed we need to pack them.
2785 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2786 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2787
2788 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2789 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2790 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2791 DAG.getShiftAmountConstant(10, MVT::i32, SL));
2792 InputReg = InputReg.getNode() ?
2793 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2794 }
2795
2796 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2797 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2798 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2799 DAG.getShiftAmountConstant(20, MVT::i32, SL));
2800 InputReg = InputReg.getNode() ?
2801 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2802 }
2803
2804 if (!InputReg.getNode()) {
2805 // Workitem ids are already packed, any of present incoming arguments
2806 // will carry all required fields.
2807 ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2808 IncomingArgX ? *IncomingArgX :
2809 IncomingArgY ? *IncomingArgY :
2810 *IncomingArgZ, ~0u);
2811 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2812 }
2813
2814 if (OutgoingArg->isRegister()) {
2815 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2816 CCInfo.AllocateReg(OutgoingArg->getRegister());
2817 } else {
2818 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2819 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2820 SpecialArgOffset);
2821 MemOpChains.push_back(ArgStore);
2822 }
2823}
2824
2825static bool canGuaranteeTCO(CallingConv::ID CC) {
2826 return CC == CallingConv::Fast;
2827}
2828
2829/// Return true if we might ever do TCO for calls with this calling convention.
2830static bool mayTailCallThisCC(CallingConv::ID CC) {
2831 switch (CC) {
2832 case CallingConv::C:
2833 case CallingConv::AMDGPU_Gfx:
2834 return true;
2835 default:
2836 return canGuaranteeTCO(CC);
2837 }
2838}
2839
2840bool SITargetLowering::isEligibleForTailCallOptimization(
2841 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2842 const SmallVectorImpl<ISD::OutputArg> &Outs,
2843 const SmallVectorImpl<SDValue> &OutVals,
2844 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2845 if (!mayTailCallThisCC(CalleeCC))
2846 return false;
2847
2848 MachineFunction &MF = DAG.getMachineFunction();
2849 const Function &CallerF = MF.getFunction();
2850 CallingConv::ID CallerCC = CallerF.getCallingConv();
2851 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2852 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2853
2854 // Kernels aren't callable, and don't have a live in return address so it
2855 // doesn't make sense to do a tail call with entry functions.
2856 if (!CallerPreserved)
2857 return false;
2858
2859 bool CCMatch = CallerCC == CalleeCC;
2860
2861 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2862 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2863 return true;
2864 return false;
2865 }
2866
2867 // TODO: Can we handle var args?
2868 if (IsVarArg)
2869 return false;
2870
2871 for (const Argument &Arg : CallerF.args()) {
2872 if (Arg.hasByValAttr())
2873 return false;
2874 }
2875
2876 LLVMContext &Ctx = *DAG.getContext();
2877
2878 // Check that the call results are passed in the same way.
2879 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2880 CCAssignFnForCall(CalleeCC, IsVarArg),
2881 CCAssignFnForCall(CallerCC, IsVarArg)))
2882 return false;
2883
2884 // The callee has to preserve all registers the caller needs to preserve.
2885 if (!CCMatch) {
2886 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2887 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2888 return false;
2889 }
2890
2891 // Nothing more to check if the callee is taking no arguments.
2892 if (Outs.empty())
2893 return true;
2894
2895 SmallVector<CCValAssign, 16> ArgLocs;
2896 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2897
2898 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2899
2900 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2901 // If the stack arguments for this call do not fit into our own save area then
2902 // the call cannot be made tail.
2903 // TODO: Is this really necessary?
2904 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2905 return false;
2906
2907 const MachineRegisterInfo &MRI = MF.getRegInfo();
2908 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2909}
2910
2911bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2912 if (!CI->isTailCall())
2913 return false;
2914
2915 const Function *ParentFn = CI->getParent()->getParent();
2916 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2917 return false;
2918 return true;
2919}
2920
2921// The wave scratch offset register is used as the global base pointer.
2922SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2923 SmallVectorImpl<SDValue> &InVals) const {
2924 SelectionDAG &DAG = CLI.DAG;
2925 const SDLoc &DL = CLI.DL;
2926 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2927 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2928 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2929 SDValue Chain = CLI.Chain;
2930 SDValue Callee = CLI.Callee;
2931 bool &IsTailCall = CLI.IsTailCall;
2932 CallingConv::ID CallConv = CLI.CallConv;
2933 bool IsVarArg = CLI.IsVarArg;
2934 bool IsSibCall = false;
2935 bool IsThisReturn = false;
2936 MachineFunction &MF = DAG.getMachineFunction();
2937
2938 if (Callee.isUndef() || isNullConstant(Callee)) {
2939 if (!CLI.IsTailCall) {
2940 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2941 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2942 }
2943
2944 return Chain;
2945 }
2946
2947 if (IsVarArg) {
2948 return lowerUnhandledCall(CLI, InVals,
2949 "unsupported call to variadic function ");
2950 }
2951
2952 if (!CLI.CB)
2953 report_fatal_error("unsupported libcall legalization");
2954
2955 if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2956 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2957 return lowerUnhandledCall(CLI, InVals,
2958 "unsupported indirect call to function ");
2959 }
2960
2961 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2962 return lowerUnhandledCall(CLI, InVals,
2963 "unsupported required tail call to function ");
2964 }
2965
2966 if (AMDGPU::isShader(CallConv)) {
2967 // Note the issue is with the CC of the called function, not of the call
2968 // itself.
2969 return lowerUnhandledCall(CLI, InVals,
2970 "unsupported call to a shader function ");
2971 }
2972
2973 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2974 CallConv != CallingConv::AMDGPU_Gfx) {
2975 // Only allow calls with specific calling conventions.
2976 return lowerUnhandledCall(CLI, InVals,
2977 "unsupported calling convention for call from "
2978 "graphics shader of function ");
2979 }
2980
2981 if (IsTailCall) {
2982 IsTailCall = isEligibleForTailCallOptimization(
2983 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2984 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2985 report_fatal_error("failed to perform tail call elimination on a call "
2986 "site marked musttail");
2987 }
2988
2989 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2990
2991 // A sibling call is one where we're under the usual C ABI and not planning
2992 // to change that but can still do a tail call:
2993 if (!TailCallOpt && IsTailCall)
2994 IsSibCall = true;
2995
2996 if (IsTailCall)
2997 ++NumTailCalls;
2998 }
2999
3000 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3001 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3002 SmallVector<SDValue, 8> MemOpChains;
3003
3004 // Analyze operands of the call, assigning locations to each operand.
3005 SmallVector<CCValAssign, 16> ArgLocs;
3006 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3007 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3008
3009 if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3010 CallConv != CallingConv::AMDGPU_Gfx) {
3011 // With a fixed ABI, allocate fixed registers before user arguments.
3012 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3013 }
3014
3015 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3016
3017 // Get a count of how many bytes are to be pushed on the stack.
3018 unsigned NumBytes = CCInfo.getNextStackOffset();
3019
3020 if (IsSibCall) {
3021 // Since we're not changing the ABI to make this a tail call, the memory
3022 // operands are already available in the caller's incoming argument space.
3023 NumBytes = 0;
3024 }
3025
3026 // FPDiff is the byte offset of the call's argument area from the callee's.
3027 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3028 // by this amount for a tail call. In a sibling call it must be 0 because the
3029 // caller will deallocate the entire stack and the callee still expects its
3030 // arguments to begin at SP+0. Completely unused for non-tail calls.
3031 int32_t FPDiff = 0;
3032 MachineFrameInfo &MFI = MF.getFrameInfo();
3033
3034 // Adjust the stack pointer for the new arguments...
3035 // These operations are automatically eliminated by the prolog/epilog pass
3036 if (!IsSibCall) {
3037 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3038
3039 if (!Subtarget->enableFlatScratch()) {
3040 SmallVector<SDValue, 4> CopyFromChains;
3041
3042 // In the HSA case, this should be an identity copy.
3043 SDValue ScratchRSrcReg
3044 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3045 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3046 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3047 Chain = DAG.getTokenFactor(DL, CopyFromChains);
3048 }
3049 }
3050
3051 MVT PtrVT = MVT::i32;
3052
3053 // Walk the register/memloc assignments, inserting copies/loads.
3054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3055 CCValAssign &VA = ArgLocs[i];
3056 SDValue Arg = OutVals[i];
3057
3058 // Promote the value if needed.
3059 switch (VA.getLocInfo()) {
3060 case CCValAssign::Full:
3061 break;
3062 case CCValAssign::BCvt:
3063 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3064 break;
3065 case CCValAssign::ZExt:
3066 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3067 break;
3068 case CCValAssign::SExt:
3069 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3070 break;
3071 case CCValAssign::AExt:
3072 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3073 break;
3074 case CCValAssign::FPExt:
3075 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3076 break;
3077 default:
3078 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3078)
;
3079 }
3080
3081 if (VA.isRegLoc()) {
3082 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3083 } else {
3084 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3084, __PRETTY_FUNCTION__))
;
3085
3086 SDValue DstAddr;
3087 MachinePointerInfo DstInfo;
3088
3089 unsigned LocMemOffset = VA.getLocMemOffset();
3090 int32_t Offset = LocMemOffset;
3091
3092 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3093 MaybeAlign Alignment;
3094
3095 if (IsTailCall) {
3096 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3097 unsigned OpSize = Flags.isByVal() ?
3098 Flags.getByValSize() : VA.getValVT().getStoreSize();
3099
3100 // FIXME: We can have better than the minimum byval required alignment.
3101 Alignment =
3102 Flags.isByVal()
3103 ? Flags.getNonZeroByValAlign()
3104 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3105
3106 Offset = Offset + FPDiff;
3107 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3108
3109 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3110 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3111
3112 // Make sure any stack arguments overlapping with where we're storing
3113 // are loaded before this eventual operation. Otherwise they'll be
3114 // clobbered.
3115
3116 // FIXME: Why is this really necessary? This seems to just result in a
3117 // lot of code to copy the stack and write them back to the same
3118 // locations, which are supposed to be immutable?
3119 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3120 } else {
3121 DstAddr = PtrOff;
3122 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3123 Alignment =
3124 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3125 }
3126
3127 if (Outs[i].Flags.isByVal()) {
3128 SDValue SizeNode =
3129 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3130 SDValue Cpy =
3131 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3132 Outs[i].Flags.getNonZeroByValAlign(),
3133 /*isVol = */ false, /*AlwaysInline = */ true,
3134 /*isTailCall = */ false, DstInfo,
3135 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3136
3137 MemOpChains.push_back(Cpy);
3138 } else {
3139 SDValue Store =
3140 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3141 MemOpChains.push_back(Store);
3142 }
3143 }
3144 }
3145
3146 if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3147 CallConv != CallingConv::AMDGPU_Gfx) {
3148 // Copy special input registers after user input arguments.
3149 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3150 }
3151
3152 if (!MemOpChains.empty())
3153 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3154
3155 // Build a sequence of copy-to-reg nodes chained together with token chain
3156 // and flag operands which copy the outgoing args into the appropriate regs.
3157 SDValue InFlag;
3158 for (auto &RegToPass : RegsToPass) {
3159 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3160 RegToPass.second, InFlag);
3161 InFlag = Chain.getValue(1);
3162 }
3163
3164
3165 SDValue PhysReturnAddrReg;
3166 if (IsTailCall) {
3167 // Since the return is being combined with the call, we need to pass on the
3168 // return address.
3169
3170 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3171 SDValue ReturnAddrReg = CreateLiveInRegister(
3172 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3173
3174 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3175 MVT::i64);
3176 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3177 InFlag = Chain.getValue(1);
3178 }
3179
3180 // We don't usually want to end the call-sequence here because we would tidy
3181 // the frame up *after* the call, however in the ABI-changing tail-call case
3182 // we've carefully laid out the parameters so that when sp is reset they'll be
3183 // in the correct location.
3184 if (IsTailCall && !IsSibCall) {
3185 Chain = DAG.getCALLSEQ_END(Chain,
3186 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3187 DAG.getTargetConstant(0, DL, MVT::i32),
3188 InFlag, DL);
3189 InFlag = Chain.getValue(1);
3190 }
3191
3192 std::vector<SDValue> Ops;
3193 Ops.push_back(Chain);
3194 Ops.push_back(Callee);
3195 // Add a redundant copy of the callee global which will not be legalized, as
3196 // we need direct access to the callee later.
3197 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3198 const GlobalValue *GV = GSD->getGlobal();
3199 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3200 } else {
3201 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3202 }
3203
3204 if (IsTailCall) {
3205 // Each tail call may have to adjust the stack by a different amount, so
3206 // this information must travel along with the operation for eventual
3207 // consumption by emitEpilogue.
3208 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3209
3210 Ops.push_back(PhysReturnAddrReg);
3211 }
3212
3213 // Add argument registers to the end of the list so that they are known live
3214 // into the call.
3215 for (auto &RegToPass : RegsToPass) {
3216 Ops.push_back(DAG.getRegister(RegToPass.first,
3217 RegToPass.second.getValueType()));
3218 }
3219
3220 // Add a register mask operand representing the call-preserved registers.
3221
3222 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3223 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3224 assert(Mask && "Missing call preserved mask for calling convention")((Mask && "Missing call preserved mask for calling convention"
) ? static_cast<void> (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3224, __PRETTY_FUNCTION__))
;
3225 Ops.push_back(DAG.getRegisterMask(Mask));
3226
3227 if (InFlag.getNode())
3228 Ops.push_back(InFlag);
3229
3230 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3231
3232 // If we're doing a tall call, use a TC_RETURN here rather than an
3233 // actual call instruction.
3234 if (IsTailCall) {
3235 MFI.setHasTailCall();
3236 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3237 }
3238
3239 // Returns a chain and a flag for retval copy to use.
3240 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3241 Chain = Call.getValue(0);
3242 InFlag = Call.getValue(1);
3243
3244 uint64_t CalleePopBytes = NumBytes;
3245 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3246 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3247 InFlag, DL);
3248 if (!Ins.empty())
3249 InFlag = Chain.getValue(1);
3250
3251 // Handle result values, copying them out of physregs into vregs that we
3252 // return.
3253 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3254 InVals, IsThisReturn,
3255 IsThisReturn ? OutVals[0] : SDValue());
3256}
3257
3258// This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3259// except for applying the wave size scale to the increment amount.
3260SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3261 SDValue Op, SelectionDAG &DAG) const {
3262 const MachineFunction &MF = DAG.getMachineFunction();
3263 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3264
3265 SDLoc dl(Op);
3266 EVT VT = Op.getValueType();
3267 SDValue Tmp1 = Op;
3268 SDValue Tmp2 = Op.getValue(1);
3269 SDValue Tmp3 = Op.getOperand(2);
3270 SDValue Chain = Tmp1.getOperand(0);
3271
3272 Register SPReg = Info->getStackPtrOffsetReg();
3273
3274 // Chain the dynamic stack allocation so that it doesn't modify the stack
3275 // pointer when other instructions are using the stack.
3276 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3277
3278 SDValue Size = Tmp2.getOperand(1);
3279 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3280 Chain = SP.getValue(1);
3281 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3282 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3283 const TargetFrameLowering *TFL = ST.getFrameLowering();
3284 unsigned Opc =
3285 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3286 ISD::ADD : ISD::SUB;
3287
3288 SDValue ScaledSize = DAG.getNode(
3289 ISD::SHL, dl, VT, Size,
3290 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3291
3292 Align StackAlign = TFL->getStackAlign();
3293 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3294 if (Alignment && *Alignment > StackAlign) {
3295 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3296 DAG.getConstant(-(uint64_t)Alignment->value()
3297 << ST.getWavefrontSizeLog2(),
3298 dl, VT));
3299 }
3300
3301 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
3302 Tmp2 = DAG.getCALLSEQ_END(
3303 Chain, DAG.getIntPtrConstant(0, dl, true),
3304 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3305
3306 return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3307}
3308
3309SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3310 SelectionDAG &DAG) const {
3311 // We only handle constant sizes here to allow non-entry block, static sized
3312 // allocas. A truly dynamic value is more difficult to support because we
3313 // don't know if the size value is uniform or not. If the size isn't uniform,
3314 // we would need to do a wave reduction to get the maximum size to know how
3315 // much to increment the uniform stack pointer.
3316 SDValue Size = Op.getOperand(1);
3317 if (isa<ConstantSDNode>(Size))
3318 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3319
3320 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3321}
3322
3323Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3324 const MachineFunction &MF) const {
3325 Register Reg = StringSwitch<Register>(RegName)
3326 .Case("m0", AMDGPU::M0)
3327 .Case("exec", AMDGPU::EXEC)
3328 .Case("exec_lo", AMDGPU::EXEC_LO)
3329 .Case("exec_hi", AMDGPU::EXEC_HI)
3330 .Case("flat_scratch", AMDGPU::FLAT_SCR)
3331 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3332 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3333 .Default(Register());
3334
3335 if (Reg == AMDGPU::NoRegister) {
3336 report_fatal_error(Twine("invalid register name \""
3337 + StringRef(RegName) + "\"."));
3338
3339 }
3340
3341 if (!Subtarget->hasFlatScrRegister() &&
3342 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3343 report_fatal_error(Twine("invalid register \""
3344 + StringRef(RegName) + "\" for subtarget."));
3345 }
3346
3347 switch (Reg) {
3348 case AMDGPU::M0:
3349 case AMDGPU::EXEC_LO:
3350 case AMDGPU::EXEC_HI:
3351 case AMDGPU::FLAT_SCR_LO:
3352 case AMDGPU::FLAT_SCR_HI:
3353 if (VT.getSizeInBits() == 32)
3354 return Reg;
3355 break;
3356 case AMDGPU::EXEC:
3357 case AMDGPU::FLAT_SCR:
3358 if (VT.getSizeInBits() == 64)
3359 return Reg;
3360 break;
3361 default:
3362 llvm_unreachable("missing register type checking")::llvm::llvm_unreachable_internal("missing register type checking"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3362)
;
3363 }
3364
3365 report_fatal_error(Twine("invalid type for register \""
3366 + StringRef(RegName) + "\"."));
3367}
3368
3369// If kill is not the last instruction, split the block so kill is always a
3370// proper terminator.
3371MachineBasicBlock *
3372SITargetLowering::splitKillBlock(MachineInstr &MI,
3373 MachineBasicBlock *BB) const {
3374 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3375 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3376 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3377 return SplitBB;
3378}
3379
3380// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3381// \p MI will be the only instruction in the loop body block. Otherwise, it will
3382// be the first instruction in the remainder block.
3383//
3384/// \returns { LoopBody, Remainder }
3385static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3386splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3387 MachineFunction *MF = MBB.getParent();
3388 MachineBasicBlock::iterator I(&MI);
3389
3390 // To insert the loop we need to split the block. Move everything after this
3391 // point to a new block, and insert a new empty block between the two.
3392 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3393 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3394 MachineFunction::iterator MBBI(MBB);
3395 ++MBBI;
3396
3397 MF->insert(MBBI, LoopBB);
3398 MF->insert(MBBI, RemainderBB);
3399
3400 LoopBB->addSuccessor(LoopBB);
3401 LoopBB->addSuccessor(RemainderBB);
3402
3403 // Move the rest of the block into a new block.
3404 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3405
3406 if (InstInLoop) {
3407 auto Next = std::next(I);
3408
3409 // Move instruction to loop body.
3410 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3411
3412 // Move the rest of the block.
3413 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3414 } else {
3415 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3416 }
3417
3418 MBB.addSuccessor(LoopBB);
3419
3420 return std::make_pair(LoopBB, RemainderBB);
3421}
3422
3423/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3424void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3425 MachineBasicBlock *MBB = MI.getParent();
3426 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3427 auto I = MI.getIterator();
3428 auto E = std::next(I);
3429
3430 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3431 .addImm(0);
3432
3433 MIBundleBuilder Bundler(*MBB, I, E);
3434 finalizeBundle(*MBB, Bundler.begin());
3435}
3436
3437MachineBasicBlock *
3438SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3439 MachineBasicBlock *BB) const {
3440 const DebugLoc &DL = MI.getDebugLoc();
3441
3442 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3443
3444 MachineBasicBlock *LoopBB;
3445 MachineBasicBlock *RemainderBB;
3446 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3447
3448 // Apparently kill flags are only valid if the def is in the same block?
3449 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3450 Src->setIsKill(false);
3451
3452 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3453
3454 MachineBasicBlock::iterator I = LoopBB->end();
3455
3456 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3457 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3458
3459 // Clear TRAP_STS.MEM_VIOL
3460 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3461 .addImm(0)
3462 .addImm(EncodedReg);
3463
3464 bundleInstWithWaitcnt(MI);
3465
3466 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3467
3468 // Load and check TRAP_STS.MEM_VIOL
3469 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3470 .addImm(EncodedReg);
3471
3472 // FIXME: Do we need to use an isel pseudo that may clobber scc?
3473 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3474 .addReg(Reg, RegState::Kill)
3475 .addImm(0);
3476 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3477 .addMBB(LoopBB);
3478
3479 return RemainderBB;
3480}
3481
3482// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3483// wavefront. If the value is uniform and just happens to be in a VGPR, this
3484// will only do one iteration. In the worst case, this will loop 64 times.
3485//
3486// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3487static MachineBasicBlock::iterator
3488emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3489 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3490 const DebugLoc &DL, const MachineOperand &Idx,
3491 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3492 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3493 Register &SGPRIdxReg) {
3494
3495 MachineFunction *MF = OrigBB.getParent();
3496 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3497 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3498 MachineBasicBlock::iterator I = LoopBB.begin();
3499
3500 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3501 Register PhiExec = MRI.createVirtualRegister(BoolRC);
3502 Register NewExec = MRI.createVirtualRegister(BoolRC);
3503 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3504 Register CondReg = MRI.createVirtualRegister(BoolRC);
3505
3506 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3507 .addReg(InitReg)
3508 .addMBB(&OrigBB)
3509 .addReg(ResultReg)
3510 .addMBB(&LoopBB);
3511
3512 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3513 .addReg(InitSaveExecReg)
3514 .addMBB(&OrigBB)
3515 .addReg(NewExec)
3516 .addMBB(&LoopBB);
3517
3518 // Read the next variant <- also loop target.
3519 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3520 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3521
3522 // Compare the just read M0 value to all possible Idx values.
3523 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3524 .addReg(CurrentIdxReg)
3525 .addReg(Idx.getReg(), 0, Idx.getSubReg());
3526
3527 // Update EXEC, save the original EXEC value to VCC.
3528 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3529 : AMDGPU::S_AND_SAVEEXEC_B64),
3530 NewExec)
3531 .addReg(CondReg, RegState::Kill);
3532
3533 MRI.setSimpleHint(NewExec, CondReg);
3534
3535 if (UseGPRIdxMode) {
3536 if (Offset == 0) {
3537 SGPRIdxReg = CurrentIdxReg;
3538 } else {
3539 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3540 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3541 .addReg(CurrentIdxReg, RegState::Kill)
3542 .addImm(Offset);
3543 }
3544 } else {
3545 // Move index from VCC into M0
3546 if (Offset == 0) {
3547 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3548 .addReg(CurrentIdxReg, RegState::Kill);
3549 } else {
3550 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3551 .addReg(CurrentIdxReg, RegState::Kill)
3552 .addImm(Offset);
3553 }
3554 }
3555
3556 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3557 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3558 MachineInstr *InsertPt =
3559 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3560 : AMDGPU::S_XOR_B64_term), Exec)
3561 .addReg(Exec)
3562 .addReg(NewExec);
3563
3564 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3565 // s_cbranch_scc0?
3566
3567 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3568 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3569 .addMBB(&LoopBB);
3570
3571 return InsertPt->getIterator();
3572}
3573
3574// This has slightly sub-optimal regalloc when the source vector is killed by
3575// the read. The register allocator does not understand that the kill is
3576// per-workitem, so is kept alive for the whole loop so we end up not re-using a
3577// subregister from it, using 1 more VGPR than necessary. This was saved when
3578// this was expanded after register allocation.
3579static MachineBasicBlock::iterator
3580loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3581 unsigned InitResultReg, unsigned PhiReg, int Offset,
3582 bool UseGPRIdxMode, Register &SGPRIdxReg) {
3583 MachineFunction *MF = MBB.getParent();
3584 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3585 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3586 MachineRegisterInfo &MRI = MF->getRegInfo();
3587 const DebugLoc &DL = MI.getDebugLoc();
3588 MachineBasicBlock::iterator I(&MI);
3589
3590 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3591 Register DstReg = MI.getOperand(0).getReg();
3592 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3593 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3594 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3595 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3596
3597 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3598
3599 // Save the EXEC mask
3600 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3601 .addReg(Exec);
3602
3603 MachineBasicBlock *LoopBB;
3604 MachineBasicBlock *RemainderBB;
3605 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3606
3607 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3608
3609 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3610 InitResultReg, DstReg, PhiReg, TmpExec,
3611 Offset, UseGPRIdxMode, SGPRIdxReg);
3612
3613 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3614 MachineFunction::iterator MBBI(LoopBB);
3615 ++MBBI;
3616 MF->insert(MBBI, LandingPad);
3617 LoopBB->removeSuccessor(RemainderBB);
3618 LandingPad->addSuccessor(RemainderBB);
3619 LoopBB->addSuccessor(LandingPad);
3620 MachineBasicBlock::iterator First = LandingPad->begin();
3621 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3622 .addReg(SaveExec);
3623
3624 return InsPt;
3625}
3626
3627// Returns subreg index, offset
3628static std::pair<unsigned, int>
3629computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3630 const TargetRegisterClass *SuperRC,
3631 unsigned VecReg,
3632 int Offset) {
3633 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3634
3635 // Skip out of bounds offsets, or else we would end up using an undefined
3636 // register.
3637 if (Offset >= NumElts || Offset < 0)
3638 return std::make_pair(AMDGPU::sub0, Offset);
3639
3640 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3641}
3642
3643static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3644 MachineRegisterInfo &MRI, MachineInstr &MI,
3645 int Offset) {
3646 MachineBasicBlock *MBB = MI.getParent();
3647 const DebugLoc &DL = MI.getDebugLoc();
3648 MachineBasicBlock::iterator I(&MI);
3649
3650 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3651
3652 assert(Idx->getReg() != AMDGPU::NoRegister)((Idx->getReg() != AMDGPU::NoRegister) ? static_cast<void
> (0) : __assert_fail ("Idx->getReg() != AMDGPU::NoRegister"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3652, __PRETTY_FUNCTION__))
;
3653
3654 if (Offset == 0) {
3655 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3656 } else {
3657 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3658 .add(*Idx)
3659 .addImm(Offset);
3660 }
3661}
3662
3663static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3664 MachineRegisterInfo &MRI, MachineInstr &MI,
3665 int Offset) {
3666 MachineBasicBlock *MBB = MI.getParent();
3667 const DebugLoc &DL = MI.getDebugLoc();
3668 MachineBasicBlock::iterator I(&MI);
3669
3670 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3671
3672 if (Offset == 0)
3673 return Idx->getReg();
3674
3675 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3676 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3677 .add(*Idx)
3678 .addImm(Offset);
3679 return Tmp;
3680}
3681
3682static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3683 MachineBasicBlock &MBB,
3684 const GCNSubtarget &ST) {
3685 const SIInstrInfo *TII = ST.getInstrInfo();
3686 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3687 MachineFunction *MF = MBB.getParent();
3688 MachineRegisterInfo &MRI = MF->getRegInfo();
3689
3690 Register Dst = MI.getOperand(0).getReg();
3691 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3692 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3693 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3694
3695 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3696 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3697
3698 unsigned SubReg;
3699 std::tie(SubReg, Offset)
3700 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3701
3702 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3703
3704 // Check for a SGPR index.
3705 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3706 MachineBasicBlock::iterator I(&MI);
3707 const DebugLoc &DL = MI.getDebugLoc();
3708
3709 if (UseGPRIdxMode) {
3710 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3711 // to avoid interfering with other uses, so probably requires a new
3712 // optimization pass.
3713 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3714
3715 const MCInstrDesc &GPRIDXDesc =
3716 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3717 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3718 .addReg(SrcReg)
3719 .addReg(Idx)
3720 .addImm(SubReg);
3721 } else {
3722 setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3723
3724 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3725 .addReg(SrcReg, 0, SubReg)
3726 .addReg(SrcReg, RegState::Implicit);
3727 }
3728
3729 MI.eraseFromParent();
3730
3731 return &MBB;
3732 }
3733
3734 // Control flow needs to be inserted if indexing with a VGPR.
3735 const DebugLoc &DL = MI.getDebugLoc();
3736 MachineBasicBlock::iterator I(&MI);
3737
3738 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3739 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3740
3741 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3742
3743 Register SGPRIdxReg;
3744 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3745 UseGPRIdxMode, SGPRIdxReg);
3746
3747 MachineBasicBlock *LoopBB = InsPt->getParent();
3748
3749 if (UseGPRIdxMode) {
3750 const MCInstrDesc &GPRIDXDesc =
3751 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3752
3753 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3754 .addReg(SrcReg)
3755 .addReg(SGPRIdxReg)
3756 .addImm(SubReg);
3757 } else {
3758 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3759 .addReg(SrcReg, 0, SubReg)
3760 .addReg(SrcReg, RegState::Implicit);
3761 }
3762
3763 MI.eraseFromParent();
3764
3765 return LoopBB;
3766}
3767
3768static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3769 MachineBasicBlock &MBB,
3770 const GCNSubtarget &ST) {
3771 const SIInstrInfo *TII = ST.getInstrInfo();
3772 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3773 MachineFunction *MF = MBB.getParent();
3774 MachineRegisterInfo &MRI = MF->getRegInfo();
3775
3776 Register Dst = MI.getOperand(0).getReg();
3777 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3778 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3779 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3780 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3781 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3782 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3783
3784 // This can be an immediate, but will be folded later.
3785 assert(Val->getReg())((Val->getReg()) ? static_cast<void> (0) : __assert_fail
("Val->getReg()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3785, __PRETTY_FUNCTION__))
;
3786
3787 unsigned SubReg;
3788 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3789 SrcVec->getReg(),
3790 Offset);
3791 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3792
3793 if (Idx->getReg() == AMDGPU::NoRegister) {
3794 MachineBasicBlock::iterator I(&MI);
3795 const DebugLoc &DL = MI.getDebugLoc();
3796
3797 assert(Offset == 0)((Offset == 0) ? static_cast<void> (0) : __assert_fail (
"Offset == 0", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3797, __PRETTY_FUNCTION__))
;
3798
3799 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3800 .add(*SrcVec)
3801 .add(*Val)
3802 .addImm(SubReg);
3803
3804 MI.eraseFromParent();
3805 return &MBB;
3806 }
3807
3808 // Check for a SGPR index.
3809 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3810 MachineBasicBlock::iterator I(&MI);
3811 const DebugLoc &DL = MI.getDebugLoc();
3812
3813 if (UseGPRIdxMode) {
3814 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3815
3816 const MCInstrDesc &GPRIDXDesc =
3817 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3818 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3819 .addReg(SrcVec->getReg())
3820 .add(*Val)
3821 .addReg(Idx)
3822 .addImm(SubReg);
3823 } else {
3824 setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3825
3826 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3827 TRI.getRegSizeInBits(*VecRC), 32, false);
3828 BuildMI(MBB, I, DL, MovRelDesc, Dst)
3829 .addReg(SrcVec->getReg())
3830 .add(*Val)
3831 .addImm(SubReg);
3832 }
3833 MI.eraseFromParent();
3834 return &MBB;
3835 }
3836
3837 // Control flow needs to be inserted if indexing with a VGPR.
3838 if (Val->isReg())
3839 MRI.clearKillFlags(Val->getReg());
3840
3841 const DebugLoc &DL = MI.getDebugLoc();
3842
3843 Register PhiReg = MRI.createVirtualRegister(VecRC);
3844
3845 Register SGPRIdxReg;
3846 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3847 UseGPRIdxMode, SGPRIdxReg);
3848 MachineBasicBlock *LoopBB = InsPt->getParent();
3849
3850 if (UseGPRIdxMode) {
3851 const MCInstrDesc &GPRIDXDesc =
3852 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3853
3854 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3855 .addReg(PhiReg)
3856 .add(*Val)
3857 .addReg(SGPRIdxReg)
3858 .addImm(AMDGPU::sub0);
3859 } else {
3860 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3861 TRI.getRegSizeInBits(*VecRC), 32, false);
3862 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3863 .addReg(PhiReg)
3864 .add(*Val)
3865 .addImm(AMDGPU::sub0);
3866 }
3867
3868 MI.eraseFromParent();
3869 return LoopBB;
3870}
3871
3872MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3873 MachineInstr &MI, MachineBasicBlock *BB) const {
3874
3875 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3876 MachineFunction *MF = BB->getParent();
3877 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3878
3879 switch (MI.getOpcode()) {
3880 case AMDGPU::S_UADDO_PSEUDO:
3881 case AMDGPU::S_USUBO_PSEUDO: {
3882 const DebugLoc &DL = MI.getDebugLoc();
3883 MachineOperand &Dest0 = MI.getOperand(0);
3884 MachineOperand &Dest1 = MI.getOperand(1);
3885 MachineOperand &Src0 = MI.getOperand(2);
3886 MachineOperand &Src1 = MI.getOperand(3);
3887
3888 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3889 ? AMDGPU::S_ADD_I32
3890 : AMDGPU::S_SUB_I32;
3891 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3892
3893 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3894 .addImm(1)
3895 .addImm(0);
3896
3897 MI.eraseFromParent();
3898 return BB;
3899 }
3900 case AMDGPU::S_ADD_U64_PSEUDO:
3901 case AMDGPU::S_SUB_U64_PSEUDO: {
3902 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3903 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3904 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3905 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3906 const DebugLoc &DL = MI.getDebugLoc();
3907
3908 MachineOperand &Dest = MI.getOperand(0);
3909 MachineOperand &Src0 = MI.getOperand(1);
3910 MachineOperand &Src1 = MI.getOperand(2);
3911
3912 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3913 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3914
3915 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3916 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3917 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3918 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3919
3920 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3921 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3922 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3923 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3924
3925 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3926
3927 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3928 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3929 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3930 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3931 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3932 .addReg(DestSub0)
3933 .addImm(AMDGPU::sub0)
3934 .addReg(DestSub1)
3935 .addImm(AMDGPU::sub1);
3936 MI.eraseFromParent();
3937 return BB;
3938 }
3939 case AMDGPU::V_ADD_U64_PSEUDO:
3940 case AMDGPU::V_SUB_U64_PSEUDO: {
3941 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3942 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3943 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3944 const DebugLoc &DL = MI.getDebugLoc();
3945
3946 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3947
3948 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3949
3950 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3951 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3952
3953 Register CarryReg = MRI.createVirtualRegister(CarryRC);
3954 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3955
3956 MachineOperand &Dest = MI.getOperand(0);
3957 MachineOperand &Src0 = MI.getOperand(1);
3958 MachineOperand &Src1 = MI.getOperand(2);
3959
3960 const TargetRegisterClass *Src0RC = Src0.isReg()
3961 ? MRI.getRegClass(Src0.getReg())
3962 : &AMDGPU::VReg_64RegClass;
3963 const TargetRegisterClass *Src1RC = Src1.isReg()
3964 ? MRI.getRegClass(Src1.getReg())
3965 : &AMDGPU::VReg_64RegClass;
3966
3967 const TargetRegisterClass *Src0SubRC =
3968 TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3969 const TargetRegisterClass *Src1SubRC =
3970 TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3971
3972 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3973 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3974 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3975 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3976
3977 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3978 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3979 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3980 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3981
3982 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3983 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3984 .addReg(CarryReg, RegState::Define)
3985 .add(SrcReg0Sub0)
3986 .add(SrcReg1Sub0)
3987 .addImm(0); // clamp bit
3988
3989 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3990 MachineInstr *HiHalf =
3991 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3992 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3993 .add(SrcReg0Sub1)
3994 .add(SrcReg1Sub1)
3995 .addReg(CarryReg, RegState::Kill)
3996 .addImm(0); // clamp bit
3997
3998 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3999 .addReg(DestSub0)
4000 .addImm(AMDGPU::sub0)
4001 .addReg(DestSub1)
4002 .addImm(AMDGPU::sub1);
4003 TII->legalizeOperands(*LoHalf);
4004 TII->legalizeOperands(*HiHalf);
4005 MI.eraseFromParent();
4006 return BB;
4007 }
4008 case AMDGPU::S_ADD_CO_PSEUDO:
4009 case AMDGPU::S_SUB_CO_PSEUDO: {
4010 // This pseudo has a chance to be selected
4011 // only from uniform add/subcarry node. All the VGPR operands
4012 // therefore assumed to be splat vectors.
4013 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4014 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4015 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4016 MachineBasicBlock::iterator MII = MI;
4017 const DebugLoc &DL = MI.getDebugLoc();
4018 MachineOperand &Dest = MI.getOperand(0);
4019 MachineOperand &CarryDest = MI.getOperand(1);
4020 MachineOperand &Src0 = MI.getOperand(2);
4021 MachineOperand &Src1 = MI.getOperand(3);
4022 MachineOperand &Src2 = MI.getOperand(4);
4023 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4024 ? AMDGPU::S_ADDC_U32
4025 : AMDGPU::S_SUBB_U32;
4026 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4027 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4028 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4029 .addReg(Src0.getReg());
4030 Src0.setReg(RegOp0);
4031 }
4032 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4033 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4034 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4035 .addReg(Src1.getReg());
4036 Src1.setReg(RegOp1);
4037 }
4038 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4039 if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4040 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4041 .addReg(Src2.getReg());
4042 Src2.setReg(RegOp2);
4043 }
4044
4045 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4046 if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4047 if (ST.hasScalarCompareEq64()) {
4048 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4049 .addReg(Src2.getReg())
4050 .addImm(0);
4051 } else {
4052 const TargetRegisterClass *SubRC =
4053 TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4054 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4055 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4056 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4057 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4058 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4059
4060 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4061 .add(Src2Sub0)
4062 .add(Src2Sub1);
4063
4064 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4065 .addReg(Src2_32, RegState::Kill)
4066 .addImm(0);
4067 }
4068 } else {
4069 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4070 .addReg(Src2.getReg())
4071 .addImm(0);
4072 }
4073
4074 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4075
4076 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4077 .addReg(AMDGPU::SCC);
4078 MI.eraseFromParent();
4079 return BB;
4080 }
4081 case AMDGPU::SI_INIT_M0: {
4082 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4083 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4084 .add(MI.getOperand(0));
4085 MI.eraseFromParent();
4086 return BB;
4087 }
4088 case AMDGPU::GET_GROUPSTATICSIZE: {
4089 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||((getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA
|| getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL
) ? static_cast<void> (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4090, __PRETTY_FUNCTION__))
4090 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)((getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA
|| getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL
) ? static_cast<void> (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4090, __PRETTY_FUNCTION__))
;
4091 DebugLoc DL = MI.getDebugLoc();
4092 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4093 .add(MI.getOperand(0))
4094 .addImm(MFI->getLDSSize());
4095 MI.eraseFromParent();
4096 return BB;
4097 }
4098 case AMDGPU::SI_INDIRECT_SRC_V1:
4099 case AMDGPU::SI_INDIRECT_SRC_V2:
4100 case AMDGPU::SI_INDIRECT_SRC_V4:
4101 case AMDGPU::SI_INDIRECT_SRC_V8:
4102 case AMDGPU::SI_INDIRECT_SRC_V16:
4103 case AMDGPU::SI_INDIRECT_SRC_V32:
4104 return emitIndirectSrc(MI, *BB, *getSubtarget());
4105 case AMDGPU::SI_INDIRECT_DST_V1:
4106 case AMDGPU::SI_INDIRECT_DST_V2:
4107 case AMDGPU::SI_INDIRECT_DST_V4:
4108 case AMDGPU::SI_INDIRECT_DST_V8:
4109 case AMDGPU::SI_INDIRECT_DST_V16:
4110 case AMDGPU::SI_INDIRECT_DST_V32:
4111 return emitIndirectDst(MI, *BB, *getSubtarget());
4112 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4113 case AMDGPU::SI_KILL_I1_PSEUDO:
4114 return splitKillBlock(MI, BB);
4115 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4116 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4117 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4118 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4119
4120 Register Dst = MI.getOperand(0).getReg();
4121 Register Src0 = MI.getOperand(1).getReg();
4122 Register Src1 = MI.getOperand(2).getReg();
4123 const DebugLoc &DL = MI.getDebugLoc();
4124 Register SrcCond = MI.getOperand(3).getReg();
4125
4126 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4127 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4128 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4129 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4130
4131 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4132 .addReg(SrcCond);
4133 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4134 .addImm(0)
4135 .addReg(Src0, 0, AMDGPU::sub0)
4136 .addImm(0)
4137 .addReg(Src1, 0, AMDGPU::sub0)
4138 .addReg(SrcCondCopy);
4139 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4140 .addImm(0)
4141 .addReg(Src0, 0, AMDGPU::sub1)
4142 .addImm(0)
4143 .addReg(Src1, 0, AMDGPU::sub1)
4144 .addReg(SrcCondCopy);
4145
4146 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4147 .addReg(DstLo)
4148 .addImm(AMDGPU::sub0)
4149 .addReg(DstHi)
4150 .addImm(AMDGPU::sub1);
4151 MI.eraseFromParent();
4152 return BB;
4153 }
4154 case AMDGPU::SI_BR_UNDEF: {
4155 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4156 const DebugLoc &DL = MI.getDebugLoc();
4157 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4158 .add(MI.getOperand(0));
4159 Br->getOperand(1).setIsUndef(true); // read undef SCC
4160 MI.eraseFromParent();
4161 return BB;
4162 }
4163 case AMDGPU::ADJCALLSTACKUP:
4164 case AMDGPU::ADJCALLSTACKDOWN: {
4165 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4166 MachineInstrBuilder MIB(*MF, &MI);
4167 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4168 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4169 return BB;
4170 }
4171 case AMDGPU::SI_CALL_ISEL: {
4172 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4173 const DebugLoc &DL = MI.getDebugLoc();
4174
4175 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4176
4177 MachineInstrBuilder MIB;
4178 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4179
4180 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4181 MIB.add(MI.getOperand(I));
4182
4183 MIB.cloneMemRefs(MI);
4184 MI.eraseFromParent();
4185 return BB;
4186 }
4187 case AMDGPU::V_ADD_CO_U32_e32:
4188 case AMDGPU::V_SUB_CO_U32_e32:
4189 case AMDGPU::V_SUBREV_CO_U32_e32: {
4190 // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4191 const DebugLoc &DL = MI.getDebugLoc();
4192 unsigned Opc = MI.getOpcode();
4193
4194 bool NeedClampOperand = false;
4195 if (TII->pseudoToMCOpcode(Opc) == -1) {
4196 Opc = AMDGPU::getVOPe64(Opc);
4197 NeedClampOperand = true;
4198 }
4199
4200 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4201 if (TII->isVOP3(*I)) {
4202 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4203 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4204 I.addReg(TRI->getVCC(), RegState::Define);
4205 }
4206 I.add(MI.getOperand(1))
4207 .add(MI.getOperand(2));
4208 if (NeedClampOperand)
4209 I.addImm(0); // clamp bit for e64 encoding
4210
4211 TII->legalizeOperands(*I);
4212
4213 MI.eraseFromParent();
4214 return BB;
4215 }
4216 case AMDGPU::DS_GWS_INIT:
4217 case AMDGPU::DS_GWS_SEMA_V:
4218 case AMDGPU::DS_GWS_SEMA_BR:
4219 case AMDGPU::DS_GWS_SEMA_P:
4220 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4221 case AMDGPU::DS_GWS_BARRIER:
4222 // A s_waitcnt 0 is required to be the instruction immediately following.
4223 if (getSubtarget()->hasGWSAutoReplay()) {
4224 bundleInstWithWaitcnt(MI);
4225 return BB;
4226 }
4227
4228 return emitGWSMemViolTestLoop(MI, BB);
4229 case AMDGPU::S_SETREG_B32: {
4230 // Try to optimize cases that only set the denormal mode or rounding mode.
4231 //
4232 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4233 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4234 // instead.
4235 //
4236 // FIXME: This could be predicates on the immediate, but tablegen doesn't
4237 // allow you to have a no side effect instruction in the output of a
4238 // sideeffecting pattern.
4239 unsigned ID, Offset, Width;
4240 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4241 if (ID != AMDGPU::Hwreg::ID_MODE)
4242 return BB;
4243
4244 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4245 const unsigned SetMask = WidthMask << Offset;
4246
4247 if (getSubtarget()->hasDenormModeInst()) {
4248 unsigned SetDenormOp = 0;
4249 unsigned SetRoundOp = 0;
4250
4251 // The dedicated instructions can only set the whole denorm or round mode
4252 // at once, not a subset of bits in either.
4253 if (SetMask ==
4254 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4255 // If this fully sets both the round and denorm mode, emit the two
4256 // dedicated instructions for these.
4257 SetRoundOp = AMDGPU::S_ROUND_MODE;
4258 SetDenormOp = AMDGPU::S_DENORM_MODE;
4259 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4260 SetRoundOp = AMDGPU::S_ROUND_MODE;
4261 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4262 SetDenormOp = AMDGPU::S_DENORM_MODE;
4263 }
4264
4265 if (SetRoundOp || SetDenormOp) {
4266 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4267 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4268 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4269 unsigned ImmVal = Def->getOperand(1).getImm();
4270 if (SetRoundOp) {
4271 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4272 .addImm(ImmVal & 0xf);
4273
4274 // If we also have the denorm mode, get just the denorm mode bits.
4275 ImmVal >>= 4;
4276 }
4277
4278 if (SetDenormOp) {
4279 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4280 .addImm(ImmVal & 0xf);
4281 }
4282
4283 MI.eraseFromParent();
4284 return BB;
4285 }
4286 }
4287 }
4288
4289 // If only FP bits are touched, used the no side effects pseudo.
4290 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4291 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4292 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4293
4294 return BB;
4295 }
4296 default:
4297 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4298 }
4299}
4300
4301bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4302 return isTypeLegal(VT.getScalarType());
4303}
4304
4305bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4306 // This currently forces unfolding various combinations of fsub into fma with
4307 // free fneg'd operands. As long as we have fast FMA (controlled by
4308 // isFMAFasterThanFMulAndFAdd), we should perform these.
4309
4310 // When fma is quarter rate, for f64 where add / sub are at best half rate,
4311 // most of these combines appear to be cycle neutral but save on instruction
4312 // count / code size.
4313 return true;
4314}
4315
4316EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4317 EVT VT) const {
4318 if (!VT.isVector()) {
4319 return MVT::i1;
4320 }
4321 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4322}
4323
4324MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4325 // TODO: Should i16 be used always if legal? For now it would force VALU
4326 // shifts.
4327 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4328}
4329
4330LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4331 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4332 ? Ty.changeElementSize(16)
4333 : Ty.changeElementSize(32);
4334}
4335
4336// Answering this is somewhat tricky and depends on the specific device which
4337// have different rates for fma or all f64 operations.
4338//
4339// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4340// regardless of which device (although the number of cycles differs between
4341// devices), so it is always profitable for f64.
4342//
4343// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4344// only on full rate devices. Normally, we should prefer selecting v_mad_f32
4345// which we can always do even without fused FP ops since it returns the same
4346// result as the separate operations and since it is always full
4347// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4348// however does not support denormals, so we do report fma as faster if we have
4349// a fast fma device and require denormals.
4350//
4351bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4352 EVT VT) const {
4353 VT = VT.getScalarType();
4354
4355 switch (VT.getSimpleVT().SimpleTy) {
4356 case MVT::f32: {
4357 // If mad is not available this depends only on if f32 fma is full rate.
4358 if (!Subtarget->hasMadMacF32Insts())
4359 return Subtarget->hasFastFMAF32();
4360
4361 // Otherwise f32 mad is always full rate and returns the same result as
4362 // the separate operations so should be preferred over fma.
4363 // However does not support denomals.
4364 if (hasFP32Denormals(MF))
4365 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4366
4367 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4368 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4369 }
4370 case MVT::f64:
4371 return true;
4372 case MVT::f16:
4373 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4374 default:
4375 break;
4376 }
4377
4378 return false;
4379}
4380
4381bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4382 const SDNode *N) const {
4383 // TODO: Check future ftz flag
4384 // v_mad_f32/v_mac_f32 do not support denormals.
4385 EVT VT = N->getValueType(0);
4386 if (VT == MVT::f32)
4387 return Subtarget->hasMadMacF32Insts() &&
4388 !hasFP32Denormals(DAG.getMachineFunction());
4389 if (VT == MVT::f16) {
4390 return Subtarget->hasMadF16() &&
4391 !hasFP64FP16Denormals(DAG.getMachineFunction());
4392 }
4393
4394 return false;
4395}
4396
4397//===----------------------------------------------------------------------===//
4398// Custom DAG Lowering Operations
4399//===----------------------------------------------------------------------===//
4400
4401// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4402// wider vector type is legal.
4403SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4404 SelectionDAG &DAG) const {
4405 unsigned Opc = Op.getOpcode();
4406 EVT VT = Op.getValueType();
4407 assert(VT == MVT::v4f16 || VT == MVT::v4i16)((VT == MVT::v4f16 || VT == MVT::v4i16) ? static_cast<void
> (0) : __assert_fail ("VT == MVT::v4f16 || VT == MVT::v4i16"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4407, __PRETTY_FUNCTION__))
;
4408
4409 SDValue Lo, Hi;
4410 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4411
4412 SDLoc SL(Op);
4413 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4414 Op->getFlags());
4415 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4416 Op->getFlags());
4417
4418 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4419}
4420
4421// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4422// wider vector type is legal.
4423SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4424 SelectionDAG &DAG) const {
4425 unsigned Opc = Op.getOpcode();
4426 EVT VT = Op.getValueType();
4427 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||((VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32) ?
static_cast<void> (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4428, __PRETTY_FUNCTION__))
4428 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32)((VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32) ?
static_cast<void> (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4428, __PRETTY_FUNCTION__))
;
4429
4430 SDValue Lo0, Hi0;
4431 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4432 SDValue Lo1, Hi1;
4433 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4434
4435 SDLoc SL(Op);
4436
4437 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4438 Op->getFlags());
4439 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4440 Op->getFlags());
4441
4442 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4443}
4444
4445SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4446 SelectionDAG &DAG) const {
4447 unsigned Opc = Op.getOpcode();
4448 EVT VT = Op.getValueType();
4449 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||((VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32) ?
static_cast<void> (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4450, __PRETTY_FUNCTION__))
4450 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32)((VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32) ?
static_cast<void> (0) : __assert_fail ("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4450, __PRETTY_FUNCTION__))
;
4451
4452 SDValue Lo0, Hi0;
4453 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4454 SDValue Lo1, Hi1;
4455 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4456 SDValue Lo2, Hi2;
4457 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4458
4459 SDLoc SL(Op);
4460
4461 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4462 Op->getFlags());
4463 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4464 Op->getFlags());
4465
4466 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4467}
4468
4469
4470SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4471 switch (Op.getOpcode()) {
4472 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4473 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4474 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4475 case ISD::LOAD: {
4476 SDValue Result = LowerLOAD(Op, DAG);
4477 assert((!Result.getNode() ||(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4479, __PRETTY_FUNCTION__))
4478 Result.getNode()->getNumValues() == 2) &&(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4479, __PRETTY_FUNCTION__))
4479 "Load should return a value and a chain")(((!Result.getNode() || Result.getNode()->getNumValues() ==
2) && "Load should return a value and a chain") ? static_cast
<void> (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4479, __PRETTY_FUNCTION__))
;
4480 return Result;
4481 }
4482
4483 case ISD::FSIN:
4484 case ISD::FCOS:
4485 return LowerTrig(Op, DAG);
4486 case ISD::SELECT: return LowerSELECT(Op, DAG);
4487 case ISD::FDIV: return LowerFDIV(Op, DAG);
4488 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4489 case ISD::STORE: return LowerSTORE(Op, DAG);
4490 case ISD::GlobalAddress: {
4491 MachineFunction &MF = DAG.getMachineFunction();
4492 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4493 return LowerGlobalAddress(MFI, Op, DAG);
4494 }
4495 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4496 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4497 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4498 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4499 case ISD::INSERT_SUBVECTOR:
4500 return lowerINSERT_SUBVECTOR(Op, DAG);
4501 case ISD::INSERT_VECTOR_ELT:
4502 return lowerINSERT_VECTOR_ELT(Op, DAG);
4503 case ISD::EXTRACT_VECTOR_ELT:
4504 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4505 case ISD::VECTOR_SHUFFLE:
4506 return lowerVECTOR_SHUFFLE(Op, DAG);
4507 case ISD::BUILD_VECTOR:
4508 return lowerBUILD_VECTOR(Op, DAG);
4509 case ISD::FP_ROUND:
4510 return lowerFP_ROUND(Op, DAG);
4511 case ISD::TRAP:
4512 return lowerTRAP(Op, DAG);
4513 case ISD::DEBUGTRAP:
4514 return lowerDEBUGTRAP(Op, DAG);
4515 case ISD::FABS:
4516 case ISD::FNEG:
4517 case ISD::FCANONICALIZE:
4518 case ISD::BSWAP:
4519 return splitUnaryVectorOp(Op, DAG);
4520 case ISD::FMINNUM:
4521 case ISD::FMAXNUM:
4522 return lowerFMINNUM_FMAXNUM(Op, DAG);
4523 case ISD::FMA:
4524 return splitTernaryVectorOp(Op, DAG);
4525 case ISD::SHL:
4526 case ISD::SRA:
4527 case ISD::SRL:
4528 case ISD::ADD:
4529 case ISD::SUB:
4530 case ISD::MUL:
4531 case ISD::SMIN:
4532 case ISD::SMAX:
4533 case ISD::UMIN:
4534 case ISD::UMAX:
4535 case ISD::FADD:
4536 case ISD::FMUL:
4537 case ISD::FMINNUM_IEEE:
4538 case ISD::FMAXNUM_IEEE:
4539 case ISD::UADDSAT:
4540 case ISD::USUBSAT:
4541 case ISD::SADDSAT:
4542 case ISD::SSUBSAT:
4543 return splitBinaryVectorOp(Op, DAG);
4544 case ISD::SMULO:
4545 case ISD::UMULO:
4546 return lowerXMULO(Op, DAG);
4547 case ISD::DYNAMIC_STACKALLOC:
4548 return LowerDYNAMIC_STACKALLOC(Op, DAG);
4549 }
4550 return SDValue();
4551}
4552
4553// Used for D16: Casts the result of an instruction into the right vector,
4554// packs values if loads return unpacked values.
4555static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4556 const SDLoc &DL,
4557 SelectionDAG &DAG, bool Unpacked) {
4558 if (!LoadVT.isVector())
4559 return Result;
4560
4561 // Cast back to the original packed type or to a larger type that is a
4562 // multiple of 32 bit for D16. Widening the return type is a required for
4563 // legalization.
4564 EVT FittingLoadVT = LoadVT;
4565 if ((LoadVT.getVectorNumElements() % 2) == 1) {
4566 FittingLoadVT =
4567 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4568 LoadVT.getVectorNumElements() + 1);
4569 }
4570
4571 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4572 // Truncate to v2i16/v4i16.
4573 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4574
4575 // Workaround legalizer not scalarizing truncate after vector op
4576 // legalization but not creating intermediate vector trunc.
4577 SmallVector<SDValue, 4> Elts;
4578 DAG.ExtractVectorElements(Result, Elts);
4579 for (SDValue &Elt : Elts)
4580 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4581
4582 // Pad illegal v1i16/v3fi6 to v4i16
4583 if ((LoadVT.getVectorNumElements() % 2) == 1)
4584 Elts.push_back(DAG.getUNDEF(MVT::i16));
4585
4586 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4587
4588 // Bitcast to original type (v2f16/v4f16).
4589 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4590 }
4591
4592 // Cast back to the original packed type.
4593 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4594}
4595
4596SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4597 MemSDNode *M,
4598 SelectionDAG &DAG,
4599 ArrayRef<SDValue> Ops,
4600 bool IsIntrinsic) const {
4601 SDLoc DL(M);
4602
4603 bool Unpacked = Subtarget->hasUnpackedD16VMem();
4604 EVT LoadVT = M->getValueType(0);
4605
4606 EVT EquivLoadVT = LoadVT;
4607 if (LoadVT.isVector()) {
4608 if (Unpacked) {
4609 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4610 LoadVT.getVectorNumElements());
4611 } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4612 // Widen v3f16 to legal type
4613 EquivLoadVT =
4614 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4615 LoadVT.getVectorNumElements() + 1);
4616 }
4617 }
4618
4619 // Change from v4f16/v2f16 to EquivLoadVT.
4620 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4621
4622 SDValue Load
4623 = DAG.getMemIntrinsicNode(
4624 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4625 VTList, Ops, M->getMemoryVT(),
4626 M->getMemOperand());
4627
4628 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4629
4630 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4631}
4632
4633SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4634 SelectionDAG &DAG,
4635 ArrayRef<SDValue> Ops) const {
4636 SDLoc DL(M);
4637 EVT LoadVT = M->getValueType(0);
4638 EVT EltType = LoadVT.getScalarType();
4639 EVT IntVT = LoadVT.changeTypeToInteger();
4640
4641 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4642
4643 unsigned Opc =
4644 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4645
4646 if (IsD16) {
4647 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4648 }
4649
4650 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4651 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4652 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4653
4654 if (isTypeLegal(LoadVT)) {
4655 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4656 M->getMemOperand(), DAG);
4657 }
4658
4659 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4660 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4661 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4662 M->getMemOperand(), DAG);
4663 return DAG.getMergeValues(
4664 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4665 DL);
4666}
4667
4668static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4669 SDNode *N, SelectionDAG &DAG) {
4670 EVT VT = N->getValueType(0);
4671 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4672 unsigned CondCode = CD->getZExtValue();
4673 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4674 return DAG.getUNDEF(VT);
4675
4676 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4677
4678 SDValue LHS = N->getOperand(1);
4679 SDValue RHS = N->getOperand(2);
4680
4681 SDLoc DL(N);
4682
4683 EVT CmpVT = LHS.getValueType();
4684 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4685 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4686 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4687 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4688 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4689 }
4690
4691 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4692
4693 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4694 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4695
4696 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4697 DAG.getCondCode(CCOpcode));
4698 if (VT.bitsEq(CCVT))
4699 return SetCC;
4700 return DAG.getZExtOrTrunc(SetCC, DL, VT);
4701}
4702
4703static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4704 SDNode *N, SelectionDAG &DAG) {
4705 EVT VT = N->getValueType(0);
4706 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4707
4708 unsigned CondCode = CD->getZExtValue();
4709 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4710 return DAG.getUNDEF(VT);
4711
4712 SDValue Src0 = N->getOperand(1);
4713 SDValue Src1 = N->getOperand(2);
4714 EVT CmpVT = Src0.getValueType();
4715 SDLoc SL(N);
4716
4717 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4718 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4719 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4720 }
4721
4722 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4723 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4724 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4725 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4726 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4727 Src1, DAG.getCondCode(CCOpcode));
4728 if (VT.bitsEq(CCVT))
4729 return SetCC;
4730 return DAG.getZExtOrTrunc(SetCC, SL, VT);
4731}
4732
4733static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4734 SelectionDAG &DAG) {
4735 EVT VT = N->getValueType(0);
4736 SDValue Src = N->getOperand(1);
4737 SDLoc SL(N);
4738
4739 if (Src.getOpcode() == ISD::SETCC) {
4740 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4741 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4742 Src.getOperand(1), Src.getOperand(2));
4743 }
4744 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4745 // (ballot 0) -> 0
4746 if (Arg->isNullValue())
4747 return DAG.getConstant(0, SL, VT);
4748
4749 // (ballot 1) -> EXEC/EXEC_LO
4750 if (Arg->isOne()) {
4751 Register Exec;
4752 if (VT.getScalarSizeInBits() == 32)
4753 Exec = AMDGPU::EXEC_LO;
4754 else if (VT.getScalarSizeInBits() == 64)
4755 Exec = AMDGPU::EXEC;
4756 else
4757 return SDValue();
4758
4759 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4760 }
4761 }
4762
4763 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4764 // ISD::SETNE)
4765 return DAG.getNode(
4766 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4767 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4768}
4769
4770void SITargetLowering::ReplaceNodeResults(SDNode *N,
4771 SmallVectorImpl<SDValue> &Results,
4772 SelectionDAG &DAG) const {
4773 switch (N->getOpcode()) {
4774 case ISD::INSERT_VECTOR_ELT: {
4775 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4776 Results.push_back(Res);
4777 return;
4778 }
4779 case ISD::EXTRACT_VECTOR_ELT: {
4780 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4781 Results.push_back(Res);
4782 return;
4783 }
4784 case ISD::INTRINSIC_WO_CHAIN: {
4785 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4786 switch (IID) {
4787 case Intrinsic::amdgcn_cvt_pkrtz: {
4788 SDValue Src0 = N->getOperand(1);
4789 SDValue Src1 = N->getOperand(2);
4790 SDLoc SL(N);
4791 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4792 Src0, Src1);
4793 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4794 return;
4795 }
4796 case Intrinsic::amdgcn_cvt_pknorm_i16:
4797 case Intrinsic::amdgcn_cvt_pknorm_u16:
4798 case Intrinsic::amdgcn_cvt_pk_i16:
4799 case Intrinsic::amdgcn_cvt_pk_u16: {
4800 SDValue Src0 = N->getOperand(1);
4801 SDValue Src1 = N->getOperand(2);
4802 SDLoc SL(N);
4803 unsigned Opcode;
4804
4805 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4806 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4807 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4808 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4809 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4810 Opcode = AMDGPUISD::CVT_PK_I16_I32;
4811 else
4812 Opcode = AMDGPUISD::CVT_PK_U16_U32;
4813
4814 EVT VT = N->getValueType(0);
4815 if (isTypeLegal(VT))
4816 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4817 else {
4818 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4819 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4820 }
4821 return;
4822 }
4823 }
4824 break;
4825 }
4826 case ISD::INTRINSIC_W_CHAIN: {
4827 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4828 if (Res.getOpcode() == ISD::MERGE_VALUES) {
4829 // FIXME: Hacky
4830 for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4831 Results.push_back(Res.getOperand(I));
4832 }
4833 } else {
4834 Results.push_back(Res);
4835 Results.push_back(Res.getValue(1));
4836 }
4837 return;
4838 }
4839
4840 break;
4841 }
4842 case ISD::SELECT: {
4843 SDLoc SL(N);
4844 EVT VT = N->getValueType(0);
4845 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4846 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4847 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4848
4849 EVT SelectVT = NewVT;
4850 if (NewVT.bitsLT(MVT::i32)) {
4851 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4852 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4853 SelectVT = MVT::i32;
4854 }
4855
4856 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4857 N->getOperand(0), LHS, RHS);
4858
4859 if (NewVT != SelectVT)
4860 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4861 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4862 return;
4863 }
4864 case ISD::FNEG: {
4865 if (N->getValueType(0) != MVT::v2f16)
4866 break;
4867
4868 SDLoc SL(N);
4869 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4870
4871 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4872 BC,
4873 DAG.getConstant(0x80008000, SL, MVT::i32));
4874 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4875 return;
4876 }
4877 case ISD::FABS: {
4878 if (N->getValueType(0) != MVT::v2f16)
4879 break;
4880
4881 SDLoc SL(N);
4882 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4883
4884 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4885 BC,
4886 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4887 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4888 return;
4889 }
4890 default:
4891 break;
4892 }
4893}
4894
4895/// Helper function for LowerBRCOND
4896static SDNode *findUser(SDValue Value, unsigned Opcode) {
4897
4898 SDNode *Parent = Value.getNode();
4899 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4900 I != E; ++I) {
4901
4902 if (I.getUse().get() != Value)
4903 continue;
4904
4905 if (I->getOpcode() == Opcode)
4906 return *I;
4907 }
4908 return nullptr;
4909}
4910
4911unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4912 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4913 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4914 case Intrinsic::amdgcn_if:
4915 return AMDGPUISD::IF;
4916 case Intrinsic::amdgcn_else:
4917 return AMDGPUISD::ELSE;
4918 case Intrinsic::amdgcn_loop:
4919 return AMDGPUISD::LOOP;
4920 case Intrinsic::amdgcn_end_cf:
4921 llvm_unreachable("should not occur")::llvm::llvm_unreachable_internal("should not occur", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4921)
;
4922 default:
4923 return 0;
4924 }
4925 }
4926
4927 // break, if_break, else_break are all only used as inputs to loop, not
4928 // directly as branch conditions.
4929 return 0;
4930}
4931
4932bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4933 const Triple &TT = getTargetMachine().getTargetTriple();
4934 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4935 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4936 AMDGPU::shouldEmitConstantsToTextSection(TT);
4937}
4938
4939bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4940 // FIXME: Either avoid relying on address space here or change the default
4941 // address space for functions to avoid the explicit check.
4942 return (GV->getValueType()->isFunctionTy() ||
4943 !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4944 !shouldEmitFixup(GV) &&
4945 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4946}
4947
4948bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4949 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4950}
4951
4952bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4953 if (!GV->hasExternalLinkage())
4954 return true;
4955
4956 const auto OS = getTargetMachine().getTargetTriple().getOS();
4957 return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4958}
4959
4960/// This transforms the control flow intrinsics to get the branch destination as
4961/// last parameter, also switches branch target with BR if the need arise
4962SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4963 SelectionDAG &DAG) const {
4964 SDLoc DL(BRCOND);
4965
4966 SDNode *Intr = BRCOND.getOperand(1).getNode();
4967 SDValue Target = BRCOND.getOperand(2);
4968 SDNode *BR = nullptr;
4969 SDNode *SetCC = nullptr;
4970
4971 if (Intr->getOpcode() == ISD::SETCC) {
4972 // As long as we negate the condition everything is fine
4973 SetCC = Intr;
4974 Intr = SetCC->getOperand(0).getNode();
4975
4976 } else {
4977 // Get the target from BR if we don't negate the condition
4978 BR = findUser(BRCOND, ISD::BR);
4979 assert(BR && "brcond missing unconditional branch user")((BR && "brcond missing unconditional branch user") ?
static_cast<void> (0) : __assert_fail ("BR && \"brcond missing unconditional branch user\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4979, __PRETTY_FUNCTION__))
;
4980 Target = BR->getOperand(1);
4981 }
4982
4983 unsigned CFNode = isCFIntrinsic(Intr);
4984 if (CFNode == 0) {
4985 // This is a uniform branch so we don't need to legalize.
4986 return BRCOND;
4987 }
4988
4989 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4990 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4991
4992 assert(!SetCC ||((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4995, __PRETTY_FUNCTION__))
4993 (SetCC->getConstantOperandVal(1) == 1 &&((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4995, __PRETTY_FUNCTION__))
4994 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4995, __PRETTY_FUNCTION__))
4995 ISD::SETNE))((!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode()
)->get() == ISD::SETNE)) ? static_cast<void> (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 4995, __PRETTY_FUNCTION__))
;
4996
4997 // operands of the new intrinsic call
4998 SmallVector<SDValue, 4> Ops;
4999 if (HaveChain)
5000 Ops.push_back(BRCOND.getOperand(0));
5001
5002 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
5003 Ops.push_back(Target);
5004
5005 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5006
5007 // build the new intrinsic call
5008 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5009
5010 if (!HaveChain) {
5011 SDValue Ops[] = {
5012 SDValue(Result, 0),
5013 BRCOND.getOperand(0)
5014 };
5015
5016 Result = DAG.getMergeValues(Ops, DL).getNode();
5017 }
5018
5019 if (BR) {
5020 // Give the branch instruction our target
5021 SDValue Ops[] = {
5022 BR->getOperand(0),
5023 BRCOND.getOperand(2)
5024 };
5025 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5026 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5027 }
5028
5029 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5030
5031 // Copy the intrinsic results to registers
5032 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5033 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5034 if (!CopyToReg)
5035 continue;
5036
5037 Chain = DAG.getCopyToReg(
5038 Chain, DL,
5039 CopyToReg->getOperand(1),
5040 SDValue(Result, i - 1),
5041 SDValue());
5042
5043 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5044 }
5045
5046 // Remove the old intrinsic from the chain
5047 DAG.ReplaceAllUsesOfValueWith(
5048 SDValue(Intr, Intr->getNumValues() - 1),
5049 Intr->getOperand(0));
5050
5051 return Chain;
5052}
5053
5054SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5055 SelectionDAG &DAG) const {
5056 MVT VT = Op.getSimpleValueType();
5057 SDLoc DL(Op);
5058 // Checking the depth
5059 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5060 return DAG.getConstant(0, DL, VT);
5061
5062 MachineFunction &MF = DAG.getMachineFunction();
5063 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5064 // Check for kernel and shader functions
5065 if (Info->isEntryFunction())
5066 return DAG.getConstant(0, DL, VT);
5067
5068 MachineFrameInfo &MFI = MF.getFrameInfo();
5069 // There is a call to @llvm.returnaddress in this function
5070 MFI.setReturnAddressIsTaken(true);
5071
5072 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5073 // Get the return address reg and mark it as an implicit live-in
5074 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5075
5076 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5077}
5078
5079SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5080 SDValue Op,
5081 const SDLoc &DL,
5082 EVT VT) const {
5083 return Op.getValueType().bitsLE(VT) ?
5084 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5085 DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5086 DAG.getTargetConstant(0, DL, MVT::i32));
5087}
5088
5089SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5090 assert(Op.getValueType() == MVT::f16 &&((Op.getValueType() == MVT::f16 && "Do not know how to custom lower FP_ROUND for non-f16 type"
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5091, __PRETTY_FUNCTION__))
5091 "Do not know how to custom lower FP_ROUND for non-f16 type")((Op.getValueType() == MVT::f16 && "Do not know how to custom lower FP_ROUND for non-f16 type"
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5091, __PRETTY_FUNCTION__))
;
5092
5093 SDValue Src = Op.getOperand(0);
5094 EVT SrcVT = Src.getValueType();
5095 if (SrcVT != MVT::f64)
5096 return Op;
5097
5098 SDLoc DL(Op);
5099
5100 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5101 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5102 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5103}
5104
5105SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5106 SelectionDAG &DAG) const {
5107 EVT VT = Op.getValueType();
5108 const MachineFunction &MF = DAG.getMachineFunction();
5109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5110 bool IsIEEEMode = Info->getMode().IEEE;
5111
5112 // FIXME: Assert during selection that this is only selected for
5113 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5114 // mode functions, but this happens to be OK since it's only done in cases
5115 // where there is known no sNaN.
5116 if (IsIEEEMode)
5117 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5118
5119 if (VT == MVT::v4f16)
5120 return splitBinaryVectorOp(Op, DAG);
5121 return Op;
5122}
5123
5124SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5125 EVT VT = Op.getValueType();
5126 SDLoc SL(Op);
5127 SDValue LHS = Op.getOperand(0);
5128 SDValue RHS = Op.getOperand(1);
5129 bool isSigned = Op.getOpcode() == ISD::SMULO;
5130
5131 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5132 const APInt &C = RHSC->getAPIntValue();
5133 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5134 if (C.isPowerOf2()) {
5135 // smulo(x, signed_min) is same as umulo(x, signed_min).
5136 bool UseArithShift = isSigned && !C.isMinSignedValue();
5137 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5138 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5139 SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5140 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5141 SL, VT, Result, ShiftAmt),
5142 LHS, ISD::SETNE);
5143 return DAG.getMergeValues({ Result, Overflow }, SL);
5144 }
5145 }
5146
5147 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5148 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5149 SL, VT, LHS, RHS);
5150
5151 SDValue Sign = isSigned
5152 ? DAG.getNode(ISD::SRA, SL, VT, Result,
5153 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5154 : DAG.getConstant(0, SL, VT);
5155 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5156
5157 return DAG.getMergeValues({ Result, Overflow }, SL);
5158}
5159
5160SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5161 if (!Subtarget->isTrapHandlerEnabled() ||
5162 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5163 return lowerTrapEndpgm(Op, DAG);
5164
5165 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5166 switch (*HsaAbiVer) {
5167 case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5168 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5169 return lowerTrapHsaQueuePtr(Op, DAG);
5170 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5171 return Subtarget->supportsGetDoorbellID() ?
5172 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5173 }
5174 }
5175
5176 llvm_unreachable("Unknown trap handler")::llvm::llvm_unreachable_internal("Unknown trap handler", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5176)
;
5177}
5178
5179SDValue SITargetLowering::lowerTrapEndpgm(
5180 SDValue Op, SelectionDAG &DAG) const {
5181 SDLoc SL(Op);
5182 SDValue Chain = Op.getOperand(0);
5183 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5184}
5185
5186SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5187 SDValue Op, SelectionDAG &DAG) const {
5188 SDLoc SL(Op);
5189 SDValue Chain = Op.getOperand(0);
5190
5191 MachineFunction &MF = DAG.getMachineFunction();
5192 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5193 Register UserSGPR = Info->getQueuePtrUserSGPR();
5194 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5194, __PRETTY_FUNCTION__))
;
5195 SDValue QueuePtr = CreateLiveInRegister(
5196 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5197 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5198 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5199 QueuePtr, SDValue());
5200
5201 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5202 SDValue Ops[] = {
5203 ToReg,
5204 DAG.getTargetConstant(TrapID, SL, MVT::i16),
5205 SGPR01,
5206 ToReg.getValue(1)
5207 };
5208 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5209}
5210
5211SDValue SITargetLowering::lowerTrapHsa(
5212 SDValue Op, SelectionDAG &DAG) const {
5213 SDLoc SL(Op);
5214 SDValue Chain = Op.getOperand(0);
5215
5216 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5217 SDValue Ops[] = {
5218 Chain,
5219 DAG.getTargetConstant(TrapID, SL, MVT::i16)
5220 };
5221 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5222}
5223
5224SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5225 SDLoc SL(Op);
5226 SDValue Chain = Op.getOperand(0);
5227 MachineFunction &MF = DAG.getMachineFunction();
5228
5229 if (!Subtarget->isTrapHandlerEnabled() ||
5230 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5231 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5232 "debugtrap handler not supported",
5233 Op.getDebugLoc(),
5234 DS_Warning);
5235 LLVMContext &Ctx = MF.getFunction().getContext();
5236 Ctx.diagnose(NoTrap);
5237 return Chain;
5238 }
5239
5240 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5241 SDValue Ops[] = {
5242 Chain,
5243 DAG.getTargetConstant(TrapID, SL, MVT::i16)
5244 };
5245 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5246}
5247
5248SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5249 SelectionDAG &DAG) const {
5250 // FIXME: Use inline constants (src_{shared, private}_base) instead.
5251 if (Subtarget->hasApertureRegs()) {
5252 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5253 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5254 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5255 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5256 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5257 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5258 unsigned Encoding =
5259 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5260 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5261 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5262
5263 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5264 SDValue ApertureReg = SDValue(
5265 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5266 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5267 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5268 }
5269
5270 MachineFunction &MF = DAG.getMachineFunction();
5271 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5272 Register UserSGPR = Info->getQueuePtrUserSGPR();
5273 assert(UserSGPR != AMDGPU::NoRegister)((UserSGPR != AMDGPU::NoRegister) ? static_cast<void> (
0) : __assert_fail ("UserSGPR != AMDGPU::NoRegister", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5273, __PRETTY_FUNCTION__))
;
5274
5275 SDValue QueuePtr = CreateLiveInRegister(
5276 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5277
5278 // Offset into amd_queue_t for group_segment_aperture_base_hi /
5279 // private_segment_aperture_base_hi.
5280 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5281
5282 SDValue Ptr =
5283 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5284
5285 // TODO: Use custom target PseudoSourceValue.
5286 // TODO: We should use the value from the IR intrinsic call, but it might not
5287 // be available and how do we get it?
5288 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5289 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5290 commonAlignment(Align(64), StructOffset),
5291 MachineMemOperand::MODereferenceable |
5292 MachineMemOperand::MOInvariant);
5293}
5294
5295SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5296 SelectionDAG &DAG) const {
5297 SDLoc SL(Op);
5298 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5299
5300 SDValue Src = ASC->getOperand(0);
5301 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5302
5303 const AMDGPUTargetMachine &TM =
5304 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5305
5306 // flat -> local/private
5307 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5308 unsigned DestAS = ASC->getDestAddressSpace();
5309
5310 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5311 DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5312 unsigned NullVal = TM.getNullPointerValue(DestAS);
5313 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5314 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5315 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5316
5317 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5318 NonNull, Ptr, SegmentNullPtr);
5319 }
5320 }
5321
5322 // local/private -> flat
5323 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5324 unsigned SrcAS = ASC->getSrcAddressSpace();
5325
5326 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5327 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5328 unsigned NullVal = TM.getNullPointerValue(SrcAS);
5329 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5330
5331 SDValue NonNull
5332 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5333
5334 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5335 SDValue CvtPtr
5336 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5337
5338 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5339 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5340 FlatNullPtr);
5341 }
5342 }
5343
5344 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5345 Src.getValueType() == MVT::i64)
5346 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5347
5348 // global <-> flat are no-ops and never emitted.
5349
5350 const MachineFunction &MF = DAG.getMachineFunction();
5351 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5352 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5353 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5354
5355 return DAG.getUNDEF(ASC->getValueType(0));
5356}
5357
5358// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5359// the small vector and inserting them into the big vector. That is better than
5360// the default expansion of doing it via a stack slot. Even though the use of
5361// the stack slot would be optimized away afterwards, the stack slot itself
5362// remains.
5363SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5364 SelectionDAG &DAG) const {
5365 SDValue Vec = Op.getOperand(0);
5366 SDValue Ins = Op.getOperand(1);
5367 SDValue Idx = Op.getOperand(2);
5368 EVT VecVT = Vec.getValueType();
5369 EVT InsVT = Ins.getValueType();
5370 EVT EltVT = VecVT.getVectorElementType();
5371 unsigned InsNumElts = InsVT.getVectorNumElements();
5372 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5373 SDLoc SL(Op);
5374
5375 for (unsigned I = 0; I != InsNumElts; ++I) {
5376 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5377 DAG.getConstant(I, SL, MVT::i32));
5378 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5379 DAG.getConstant(IdxVal + I, SL, MVT::i32));
5380 }
5381 return Vec;
5382}
5383
5384SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5385 SelectionDAG &DAG) const {
5386 SDValue Vec = Op.getOperand(0);
5387 SDValue InsVal = Op.getOperand(1);
5388 SDValue Idx = Op.getOperand(2);
5389 EVT VecVT = Vec.getValueType();
5390 EVT EltVT = VecVT.getVectorElementType();
5391 unsigned VecSize = VecVT.getSizeInBits();
5392 unsigned EltSize = EltVT.getSizeInBits();
5393
5394
5395 assert(VecSize <= 64)((VecSize <= 64) ? static_cast<void> (0) : __assert_fail
("VecSize <= 64", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5395, __PRETTY_FUNCTION__))
;
5396
5397 unsigned NumElts = VecVT.getVectorNumElements();
5398 SDLoc SL(Op);
5399 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5400
5401 if (NumElts == 4 && EltSize == 16 && KIdx) {
5402 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5403
5404 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5405 DAG.getConstant(0, SL, MVT::i32));
5406 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5407 DAG.getConstant(1, SL, MVT::i32));
5408
5409 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5410 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5411
5412 unsigned Idx = KIdx->getZExtValue();
5413 bool InsertLo = Idx < 2;
5414 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5415 InsertLo ? LoVec : HiVec,
5416 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5417 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5418
5419 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5420
5421 SDValue Concat = InsertLo ?
5422 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5423 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5424
5425 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5426 }
5427
5428 if (isa<ConstantSDNode>(Idx))
5429 return SDValue();
5430
5431 MVT IntVT = MVT::getIntegerVT(VecSize);
5432
5433 // Avoid stack access for dynamic indexing.
5434 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5435
5436 // Create a congruent vector with the target value in each element so that
5437 // the required element can be masked and ORed into the target vector.
5438 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5439 DAG.getSplatBuildVector(VecVT, SL, InsVal));
5440
5441 assert(isPowerOf2_32(EltSize))((isPowerOf2_32(EltSize)) ? static_cast<void> (0) : __assert_fail
("isPowerOf2_32(EltSize)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5441, __PRETTY_FUNCTION__))
;
5442 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5443
5444 // Convert vector index to bit-index.
5445 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5446
5447 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5448 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5449 DAG.getConstant(0xffff, SL, IntVT),
5450 ScaledIdx);
5451
5452 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5453 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5454 DAG.getNOT(SL, BFM, IntVT), BCVec);
5455
5456 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5457 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5458}
5459
5460SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5461 SelectionDAG &DAG) const {
5462 SDLoc SL(Op);
5463
5464 EVT ResultVT = Op.getValueType();
5465 SDValue Vec = Op.getOperand(0);
5466 SDValue Idx = Op.getOperand(1);
5467 EVT VecVT = Vec.getValueType();
5468 unsigned VecSize = VecVT.getSizeInBits();
5469 EVT EltVT = VecVT.getVectorElementType();
5470 assert(VecSize <= 64)((VecSize <= 64) ? static_cast<void> (0) : __assert_fail
("VecSize <= 64", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5470, __PRETTY_FUNCTION__))
;
5471
5472 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5473
5474 // Make sure we do any optimizations that will make it easier to fold
5475 // source modifiers before obscuring it with bit operations.
5476
5477 // XXX - Why doesn't this get called when vector_shuffle is expanded?
5478 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5479 return Combined;
5480
5481 unsigned EltSize = EltVT.getSizeInBits();
5482 assert(isPowerOf2_32(EltSize))((isPowerOf2_32(EltSize)) ? static_cast<void> (0) : __assert_fail
("isPowerOf2_32(EltSize)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5482, __PRETTY_FUNCTION__))
;
5483
5484 MVT IntVT = MVT::getIntegerVT(VecSize);
5485 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5486
5487 // Convert vector index to bit-index (* EltSize)
5488 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5489
5490 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5491 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5492
5493 if (ResultVT == MVT::f16) {
5494 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5495 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5496 }
5497
5498 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5499}
5500
5501static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5502 assert(Elt % 2 == 0)((Elt % 2 == 0) ? static_cast<void> (0) : __assert_fail
("Elt % 2 == 0", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5502, __PRETTY_FUNCTION__))
;
5503 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5504}
5505
5506SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5507 SelectionDAG &DAG) const {
5508 SDLoc SL(Op);
5509 EVT ResultVT = Op.getValueType();
5510 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5511
5512 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5513 EVT EltVT = PackVT.getVectorElementType();
5514 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5515
5516 // vector_shuffle <0,1,6,7> lhs, rhs
5517 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5518 //
5519 // vector_shuffle <6,7,2,3> lhs, rhs
5520 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5521 //
5522 // vector_shuffle <6,7,0,1> lhs, rhs
5523 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5524
5525 // Avoid scalarizing when both halves are reading from consecutive elements.
5526 SmallVector<SDValue, 4> Pieces;
5527 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5528 if (elementPairIsContiguous(SVN->getMask(), I)) {
5529 const int Idx = SVN->getMaskElt(I);
5530 int VecIdx = Idx < SrcNumElts ? 0 : 1;
5531 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5532 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5533 PackVT, SVN->getOperand(VecIdx),
5534 DAG.getConstant(EltIdx, SL, MVT::i32));
5535 Pieces.push_back(SubVec);
5536 } else {
5537 const int Idx0 = SVN->getMaskElt(I);
5538 const int Idx1 = SVN->getMaskElt(I + 1);
5539 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5540 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5541 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5542 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5543
5544 SDValue Vec0 = SVN->getOperand(VecIdx0);
5545 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5546 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5547
5548 SDValue Vec1 = SVN->getOperand(VecIdx1);
5549 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5550 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5551 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5552 }
5553 }
5554
5555 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5556}
5557
5558SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5559 SelectionDAG &DAG) const {
5560 SDLoc SL(Op);
5561 EVT VT = Op.getValueType();
5562
5563 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5564 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5565
5566 // Turn into pair of packed build_vectors.
5567 // TODO: Special case for constants that can be materialized with s_mov_b64.
5568 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5569 { Op.getOperand(0), Op.getOperand(1) });
5570 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5571 { Op.getOperand(2), Op.getOperand(3) });
5572
5573 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5574 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5575
5576 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5577 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5578 }
5579
5580 assert(VT == MVT::v2f16 || VT == MVT::v2i16)((VT == MVT::v2f16 || VT == MVT::v2i16) ? static_cast<void
> (0) : __assert_fail ("VT == MVT::v2f16 || VT == MVT::v2i16"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5580, __PRETTY_FUNCTION__))
;
5581 assert(!Subtarget->hasVOP3PInsts() && "this should be legal")((!Subtarget->hasVOP3PInsts() && "this should be legal"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget->hasVOP3PInsts() && \"this should be legal\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5581, __PRETTY_FUNCTION__))
;
5582
5583 SDValue Lo = Op.getOperand(0);
5584 SDValue Hi = Op.getOperand(1);
5585
5586 // Avoid adding defined bits with the zero_extend.
5587 if (Hi.isUndef()) {
5588 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5589 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5590 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5591 }
5592
5593 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5594 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5595
5596 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5597 DAG.getConstant(16, SL, MVT::i32));
5598 if (Lo.isUndef())
5599 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5600
5601 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5602 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5603
5604 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5605 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5606}
5607
5608bool
5609SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5610 // We can fold offsets for anything that doesn't require a GOT relocation.
5611 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5612 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5613 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5614 !shouldEmitGOTReloc(GA->getGlobal());
5615}
5616
5617static SDValue
5618buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5619 const SDLoc &DL, int64_t Offset, EVT PtrVT,
5620 unsigned GAFlags = SIInstrInfo::MO_NONE) {
5621 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!")((isInt<32>(Offset + 4) && "32-bit offset is expected!"
) ? static_cast<void> (0) : __assert_fail ("isInt<32>(Offset + 4) && \"32-bit offset is expected!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5621, __PRETTY_FUNCTION__))
;
5622 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5623 // lowered to the following code sequence:
5624 //
5625 // For constant address space:
5626 // s_getpc_b64 s[0:1]
5627 // s_add_u32 s0, s0, $symbol
5628 // s_addc_u32 s1, s1, 0
5629 //
5630 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5631 // a fixup or relocation is emitted to replace $symbol with a literal
5632 // constant, which is a pc-relative offset from the encoding of the $symbol
5633 // operand to the global variable.
5634 //
5635 // For global address space:
5636 // s_getpc_b64 s[0:1]
5637 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5638 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5639 //
5640 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
5641 // fixups or relocations are emitted to replace $symbol@*@lo and
5642 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5643 // which is a 64-bit pc-relative offset from the encoding of the $symbol
5644 // operand to the global variable.
5645 //
5646 // What we want here is an offset from the value returned by s_getpc
5647 // (which is the address of the s_add_u32 instruction) to the global
5648 // variable, but since the encoding of $symbol starts 4 bytes after the start
5649 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5650 // small. This requires us to add 4 to the global variable offset in order to
5651 // compute the correct address. Similarly for the s_addc_u32 instruction, the
5652 // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5653 // instruction.
5654 SDValue PtrLo =
5655 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5656 SDValue PtrHi;
5657 if (GAFlags == SIInstrInfo::MO_NONE) {
5658 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5659 } else {
5660 PtrHi =
5661 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5662 }
5663 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5664}
5665
5666SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5667 SDValue Op,
5668 SelectionDAG &DAG) const {
5669 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5670 SDLoc DL(GSD);
5671 EVT PtrVT = Op.getValueType();
5672
5673 const GlobalValue *GV = GSD->getGlobal();
5674 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5675 shouldUseLDSConstAddress(GV)) ||
5676 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5677 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5678 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5679 GV->hasExternalLinkage()) {
5680 Type *Ty = GV->getValueType();
5681 // HIP uses an unsized array `extern __shared__ T s[]` or similar
5682 // zero-sized type in other languages to declare the dynamic shared
5683 // memory which size is not known at the compile time. They will be
5684 // allocated by the runtime and placed directly after the static
5685 // allocated ones. They all share the same offset.
5686 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5687 assert(PtrVT == MVT::i32 && "32-bit pointer is expected.")((PtrVT == MVT::i32 && "32-bit pointer is expected.")
? static_cast<void> (0) : __assert_fail ("PtrVT == MVT::i32 && \"32-bit pointer is expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5687, __PRETTY_FUNCTION__))
;
5688 // Adjust alignment for that dynamic shared memory array.
5689 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5690 return SDValue(
5691 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5692 }
5693 }
5694 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5695 }
5696
5697 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5698 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5699 SIInstrInfo::MO_ABS32_LO);
5700 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5701 }
5702
5703 if (shouldEmitFixup(GV))
5704 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5705 else if (shouldEmitPCReloc(GV))
5706 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5707 SIInstrInfo::MO_REL32);
5708
5709 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5710 SIInstrInfo::MO_GOTPCREL32);
5711
5712 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5713 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5714 const DataLayout &DataLayout = DAG.getDataLayout();
5715 Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5716 MachinePointerInfo PtrInfo
5717 = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5718
5719 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5720 MachineMemOperand::MODereferenceable |
5721 MachineMemOperand::MOInvariant);
5722}
5723
5724SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5725 const SDLoc &DL, SDValue V) const {
5726 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5727 // the destination register.
5728 //
5729 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5730 // so we will end up with redundant moves to m0.
5731 //
5732 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5733
5734 // A Null SDValue creates a glue result.
5735 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5736 V, Chain);
5737 return SDValue(M0, 0);
5738}
5739
5740SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5741 SDValue Op,
5742 MVT VT,
5743 unsigned Offset) const {
5744 SDLoc SL(Op);
5745 SDValue Param = lowerKernargMemParameter(
5746 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5747 // The local size values will have the hi 16-bits as zero.
5748 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5749 DAG.getValueType(VT));
5750}
5751
5752static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5753 EVT VT) {
5754 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5755 "non-hsa intrinsic with hsa target",
5756 DL.getDebugLoc());
5757 DAG.getContext()->diagnose(BadIntrin);
5758 return DAG.getUNDEF(VT);
5759}
5760
5761static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5762 EVT VT) {
5763 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5764 "intrinsic not supported on subtarget",
5765 DL.getDebugLoc());
5766 DAG.getContext()->diagnose(BadIntrin);
5767 return DAG.getUNDEF(VT);
5768}
5769
5770static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5771 ArrayRef<SDValue> Elts) {
5772 assert(!Elts.empty())((!Elts.empty()) ? static_cast<void> (0) : __assert_fail
("!Elts.empty()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5772, __PRETTY_FUNCTION__))
;
5773 MVT Type;
5774 unsigned NumElts;
5775
5776 if (Elts.size() == 1) {
5777 Type = MVT::f32;
5778 NumElts = 1;
5779 } else if (Elts.size() == 2) {
5780 Type = MVT::v2f32;
5781 NumElts = 2;
5782 } else if (Elts.size() == 3) {
5783 Type = MVT::v3f32;
5784 NumElts = 3;
5785 } else if (Elts.size() <= 4) {
5786 Type = MVT::v4f32;
5787 NumElts = 4;
5788 } else if (Elts.size() <= 8) {
5789 Type = MVT::v8f32;
5790 NumElts = 8;
5791 } else {
5792 assert(Elts.size() <= 16)((Elts.size() <= 16) ? static_cast<void> (0) : __assert_fail
("Elts.size() <= 16", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5792, __PRETTY_FUNCTION__))
;
5793 Type = MVT::v16f32;
5794 NumElts = 16;
5795 }
5796
5797 SmallVector<SDValue, 16> VecElts(NumElts);
5798 for (unsigned i = 0; i < Elts.size(); ++i) {
5799 SDValue Elt = Elts[i];
5800 if (Elt.getValueType() != MVT::f32)
5801 Elt = DAG.getBitcast(MVT::f32, Elt);
5802 VecElts[i] = Elt;
5803 }
5804 for (unsigned i = Elts.size(); i < NumElts; ++i)
5805 VecElts[i] = DAG.getUNDEF(MVT::f32);
5806
5807 if (NumElts == 1)
5808 return VecElts[0];
5809 return DAG.getBuildVector(Type, DL, VecElts);
5810}
5811
5812static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5813 SDValue Src, int ExtraElts) {
5814 EVT SrcVT = Src.getValueType();
5815
5816 SmallVector<SDValue, 8> Elts;
5817
5818 if (SrcVT.isVector())
5819 DAG.ExtractVectorElements(Src, Elts);
5820 else
5821 Elts.push_back(Src);
5822
5823 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5824 while (ExtraElts--)
5825 Elts.push_back(Undef);
5826
5827 return DAG.getBuildVector(CastVT, DL, Elts);
5828}
5829
5830// Re-construct the required return value for a image load intrinsic.
5831// This is more complicated due to the optional use TexFailCtrl which means the required
5832// return type is an aggregate
5833static SDValue constructRetValue(SelectionDAG &DAG,
5834 MachineSDNode *Result,
5835 ArrayRef<EVT> ResultTypes,
5836 bool IsTexFail, bool Unpacked, bool IsD16,
5837 int DMaskPop, int NumVDataDwords,
5838 const SDLoc &DL) {
5839 // Determine the required return type. This is the same regardless of IsTexFail flag
5840 EVT ReqRetVT = ResultTypes[0];
5841 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5842 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5843 ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5844
5845 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5846 DMaskPop : (DMaskPop + 1) / 2;
5847
5848 MVT DataDwordVT = NumDataDwords == 1 ?
5849 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5850
5851 MVT MaskPopVT = MaskPopDwords == 1 ?
5852 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5853
5854 SDValue Data(Result, 0);
5855 SDValue TexFail;
5856
5857 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5858 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5859 if (MaskPopVT.isVector()) {
5860 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5861 SDValue(Result, 0), ZeroIdx);
5862 } else {
5863 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5864 SDValue(Result, 0), ZeroIdx);
5865 }
5866 }
5867
5868 if (DataDwordVT.isVector())
5869 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5870 NumDataDwords - MaskPopDwords);
5871
5872 if (IsD16)
5873 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5874
5875 EVT LegalReqRetVT = ReqRetVT;
5876 if (!ReqRetVT.isVector()) {
5877 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5878 } else {
5879 // We need to widen the return vector to a legal type
5880 if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5881 ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5882 LegalReqRetVT =
5883 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5884 ReqRetVT.getVectorNumElements() + 1);
5885 }
5886 }
5887 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5888
5889 if (IsTexFail) {
5890 TexFail =
5891 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5892 DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5893
5894 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5895 }
5896
5897 if (Result->getNumValues() == 1)
5898 return Data;
5899
5900 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5901}
5902
5903static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5904 SDValue *LWE, bool &IsTexFail) {
5905 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5906
5907 uint64_t Value = TexFailCtrlConst->getZExtValue();
5908 if (Value) {
5909 IsTexFail = true;
5910 }
5911
5912 SDLoc DL(TexFailCtrlConst);
5913 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5914 Value &= ~(uint64_t)0x1;
5915 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5916 Value &= ~(uint64_t)0x2;
5917
5918 return Value == 0;
5919}
5920
5921static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5922 MVT PackVectorVT,
5923 SmallVectorImpl<SDValue> &PackedAddrs,
5924 unsigned DimIdx, unsigned EndIdx,
5925 unsigned NumGradients) {
5926 SDLoc DL(Op);
5927 for (unsigned I = DimIdx; I < EndIdx; I++) {
5928 SDValue Addr = Op.getOperand(I);
5929
5930 // Gradients are packed with undef for each coordinate.
5931 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5932 // 1D: undef,dx/dh; undef,dx/dv
5933 // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5934 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5935 if (((I + 1) >= EndIdx) ||
5936 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5937 I == DimIdx + NumGradients - 1))) {
5938 if (Addr.getValueType() != MVT::i16)
5939 Addr = DAG.getBitcast(MVT::i16, Addr);
5940 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5941 } else {
5942 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5943 I++;
5944 }
5945 Addr = DAG.getBitcast(MVT::f32, Addr);
5946 PackedAddrs.push_back(Addr);
5947 }
5948}
5949
5950SDValue SITargetLowering::lowerImage(SDValue Op,
5951 const AMDGPU::ImageDimIntrinsicInfo *Intr,
5952 SelectionDAG &DAG, bool WithChain) const {
5953 SDLoc DL(Op);
5954 MachineFunction &MF = DAG.getMachineFunction();
5955 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5956 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5957 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5958 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5959 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5960 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5961 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5962 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5963 unsigned IntrOpcode = Intr->BaseOpcode;
5964 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5965
5966 SmallVector<EVT, 3> ResultTypes(Op->values());
5967 SmallVector<EVT, 3> OrigResultTypes(Op->values());
5968 bool IsD16 = false;
5969 bool IsG16 = false;
5970 bool IsA16 = false;
5971 SDValue VData;
5972 int NumVDataDwords;
5973 bool AdjustRetType = false;
5974
5975 // Offset of intrinsic arguments
5976 const unsigned ArgOffset = WithChain ? 2 : 1;
5977
5978 unsigned DMask;
5979 unsigned DMaskLanes = 0;
5980
5981 if (BaseOpcode->Atomic) {
5982 VData = Op.getOperand(2);
5983
5984 bool Is64Bit = VData.getValueType() == MVT::i64;
5985 if (BaseOpcode->AtomicX2) {
5986 SDValue VData2 = Op.getOperand(3);
5987 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5988 {VData, VData2});
5989 if (Is64Bit)
5990 VData = DAG.getBitcast(MVT::v4i32, VData);
5991
5992 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5993 DMask = Is64Bit ? 0xf : 0x3;
5994 NumVDataDwords = Is64Bit ? 4 : 2;
5995 } else {
5996 DMask = Is64Bit ? 0x3 : 0x1;
5997 NumVDataDwords = Is64Bit ? 2 : 1;
5998 }
5999 } else {
6000 auto *DMaskConst =
6001 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6002 DMask = DMaskConst->getZExtValue();
6003 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6004
6005 if (BaseOpcode->Store) {
6006 VData = Op.getOperand(2);
6007
6008 MVT StoreVT = VData.getSimpleValueType();
6009 if (StoreVT.getScalarType() == MVT::f16) {
6010 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6011 return Op; // D16 is unsupported for this instruction
6012
6013 IsD16 = true;
6014 VData = handleD16VData(VData, DAG, true);
6015 }
6016
6017 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6018 } else {
6019 // Work out the num dwords based on the dmask popcount and underlying type
6020 // and whether packing is supported.
6021 MVT LoadVT = ResultTypes[0].getSimpleVT();
6022 if (LoadVT.getScalarType() == MVT::f16) {
6023 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6024 return Op; // D16 is unsupported for this instruction
6025
6026 IsD16 = true;
6027 }
6028
6029 // Confirm that the return type is large enough for the dmask specified
6030 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6031 (!LoadVT.isVector() && DMaskLanes > 1))
6032 return Op;
6033
6034 // The sq block of gfx8 and gfx9 do not estimate register use correctly
6035 // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6036 // instructions.
6037 if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6038 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6039 NumVDataDwords = (DMaskLanes + 1) / 2;
6040 else
6041 NumVDataDwords = DMaskLanes;
6042
6043 AdjustRetType = true;
6044 }
6045 }
6046
6047 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6048 SmallVector<SDValue, 4> VAddrs;
6049
6050 // Optimize _L to _LZ when _L is zero
6051 if (LZMappingInfo) {
6052 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6053 Op.getOperand(ArgOffset + Intr->LodIndex))) {
6054 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6055 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
6056 VAddrEnd--; // remove 'lod'
6057 }
6058 }
6059 }
6060
6061 // Optimize _mip away, when 'lod' is zero
6062 if (MIPMappingInfo) {
6063 if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6064 Op.getOperand(ArgOffset + Intr->MipIndex))) {
6065 if (ConstantLod->isNullValue()) {
6066 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip
6067 VAddrEnd--; // remove 'mip'
6068 }
6069 }
6070 }
6071
6072 // Push back extra arguments.
6073 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6074 VAddrs.push_back(Op.getOperand(ArgOffset + I));
6075
6076 // Check for 16 bit addresses or derivatives and pack if true.
6077 MVT VAddrVT =
6078 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6079 MVT VAddrScalarVT = VAddrVT.getScalarType();
6080 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6081 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6082
6083 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6084 VAddrScalarVT = VAddrVT.getScalarType();
6085 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6086 if (IsA16 || IsG16) {
6087 if (IsA16) {
6088 if (!ST->hasA16()) {
6089 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit addresses\n"; } } while (false)
6090 "support 16 bit addresses\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit addresses\n"; } } while (false)
;
6091 return Op;
6092 }
6093 if (!IsG16) {
6094 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"need 16 bit derivatives but got 32 bit derivatives\n"; } } while
(false)
6095 dbgs() << "Failed to lower image intrinsic: 16 bit addresses "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"need 16 bit derivatives but got 32 bit derivatives\n"; } } while
(false)
6096 "need 16 bit derivatives but got 32 bit derivatives\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"need 16 bit derivatives but got 32 bit derivatives\n"; } } while
(false)
;
6097 return Op;
6098 }
6099 } else if (!ST->hasG16()) {
6100 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit derivatives\n"; } } while (false)
6101 "support 16 bit derivatives\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit derivatives\n"; } } while (false)
;
6102 return Op;
6103 }
6104
6105 if (BaseOpcode->Gradients && !IsA16) {
6106 if (!ST->hasG16()) {
6107 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit derivatives\n"; } } while (false)
6108 "support 16 bit derivatives\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: Target does not "
"support 16 bit derivatives\n"; } } while (false)
;
6109 return Op;
6110 }
6111 // Activate g16
6112 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6113 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6114 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6115 }
6116
6117 // Don't compress addresses for G16
6118 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6119 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6120 ArgOffset + Intr->GradientStart, PackEndIdx,
6121 Intr->NumGradients);
6122
6123 if (!IsA16) {
6124 // Add uncompressed address
6125 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6126 VAddrs.push_back(Op.getOperand(I));
6127 }
6128 } else {
6129 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6130 VAddrs.push_back(Op.getOperand(I));
6131 }
6132
6133 // If the register allocator cannot place the address registers contiguously
6134 // without introducing moves, then using the non-sequential address encoding
6135 // is always preferable, since it saves VALU instructions and is usually a
6136 // wash in terms of code size or even better.
6137 //
6138 // However, we currently have no way of hinting to the register allocator that
6139 // MIMG addresses should be placed contiguously when it is possible to do so,
6140 // so force non-NSA for the common 2-address case as a heuristic.
6141 //
6142 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6143 // allocation when possible.
6144 bool UseNSA =
6145 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6146 SDValue VAddr;
6147 if (!UseNSA)
6148 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6149
6150 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6151 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6152 SDValue Unorm;
6153 if (!BaseOpcode->Sampler) {
6154 Unorm = True;
6155 } else {
6156 auto UnormConst =
6157 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6158
6159 Unorm = UnormConst->getZExtValue() ? True : False;
6160 }
6161
6162 SDValue TFE;
6163 SDValue LWE;
6164 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6165 bool IsTexFail = false;
6166 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6167 return Op;
6168
6169 if (IsTexFail) {
6170 if (!DMaskLanes) {
6171 // Expecting to get an error flag since TFC is on - and dmask is 0
6172 // Force dmask to be at least 1 otherwise the instruction will fail
6173 DMask = 0x1;
6174 DMaskLanes = 1;
6175 NumVDataDwords = 1;
6176 }
6177 NumVDataDwords += 1;
6178 AdjustRetType = true;
6179 }
6180
6181 // Has something earlier tagged that the return type needs adjusting
6182 // This happens if the instruction is a load or has set TexFailCtrl flags
6183 if (AdjustRetType) {
6184 // NumVDataDwords reflects the true number of dwords required in the return type
6185 if (DMaskLanes == 0 && !BaseOpcode->Store) {
6186 // This is a no-op load. This can be eliminated
6187 SDValue Undef = DAG.getUNDEF(Op.getValueType());
6188 if (isa<MemSDNode>(Op))
6189 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6190 return Undef;
6191 }
6192
6193 EVT NewVT = NumVDataDwords > 1 ?
6194 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6195 : MVT::i32;
6196
6197 ResultTypes[0] = NewVT;
6198 if (ResultTypes.size() == 3) {
6199 // Original result was aggregate type used for TexFailCtrl results
6200 // The actual instruction returns as a vector type which has now been
6201 // created. Remove the aggregate result.
6202 ResultTypes.erase(&ResultTypes[1]);
6203 }
6204 }
6205
6206 unsigned CPol = cast<ConstantSDNode>(
6207 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6208 if (BaseOpcode->Atomic)
6209 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6210 if (CPol & ~AMDGPU::CPol::ALL)
6211 return Op;
6212
6213 SmallVector<SDValue, 26> Ops;
6214 if (BaseOpcode->Store || BaseOpcode->Atomic)
6215 Ops.push_back(VData); // vdata
6216 if (UseNSA)
6217 append_range(Ops, VAddrs);
6218 else
6219 Ops.push_back(VAddr);
6220 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6221 if (BaseOpcode->Sampler)
6222 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6223 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6224 if (IsGFX10Plus)
6225 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6226 Ops.push_back(Unorm);
6227 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6228 Ops.push_back(IsA16 && // r128, a16 for gfx9
6229 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6230 if (IsGFX10Plus)
6231 Ops.push_back(IsA16 ? True : False);
6232 if (!Subtarget->hasGFX90AInsts()) {
6233 Ops.push_back(TFE); //tfe
6234 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6235 report_fatal_error("TFE is not supported on this GPU");
6236 }
6237 Ops.push_back(LWE); // lwe
6238 if (!IsGFX10Plus)
6239 Ops.push_back(DimInfo->DA ? True : False);
6240 if (BaseOpcode->HasD16)
6241 Ops.push_back(IsD16 ? True : False);
6242 if (isa<MemSDNode>(Op))
6243 Ops.push_back(Op.getOperand(0)); // chain
6244
6245 int NumVAddrDwords =
6246 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6247 int Opcode = -1;
6248
6249 if (IsGFX10Plus) {
6250 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6251 UseNSA ? AMDGPU::MIMGEncGfx10NSA
6252 : AMDGPU::MIMGEncGfx10Default,
6253 NumVDataDwords, NumVAddrDwords);
6254 } else {
6255 if (Subtarget->hasGFX90AInsts()) {
6256 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6257 NumVDataDwords, NumVAddrDwords);
6258 if (Opcode == -1)
6259 report_fatal_error(
6260 "requested image instruction is not supported on this GPU");
6261 }
6262 if (Opcode == -1 &&
6263 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6264 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6265 NumVDataDwords, NumVAddrDwords);
6266 if (Opcode == -1)
6267 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6268 NumVDataDwords, NumVAddrDwords);
6269 }
6270 assert(Opcode != -1)((Opcode != -1) ? static_cast<void> (0) : __assert_fail
("Opcode != -1", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6270, __PRETTY_FUNCTION__))
;
6271