Bug Summary

File:build/source/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 11998, 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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SIISelLowering.cpp -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 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Target/AMDGPU -I /build/source/llvm/lib/Target/AMDGPU -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility=hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2023-05-10-133810-16478-1 -x c++ /build/source/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/FloatingPointMode.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/OptimizationRemarkEmitter.h"
23#include "llvm/Analysis/UniformityAnalysis.h"
24#include "llvm/BinaryFormat/ELF.h"
25#include "llvm/CodeGen/Analysis.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
28#include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineLoopInfo.h"
32#include "llvm/IR/DiagnosticInfo.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/IntrinsicsAMDGPU.h"
36#include "llvm/IR/IntrinsicsR600.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/KnownBits.h"
39#include "llvm/Support/ModRef.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE"si-lower" "si-lower"
44
45STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"si-lower", "NumTailCalls"
, "Number of tail calls"}
;
46
47static cl::opt<bool> DisableLoopAlignment(
48 "amdgpu-disable-loop-alignment",
49 cl::desc("Do not align and prefetch loops"),
50 cl::init(false));
51
52static cl::opt<bool> UseDivergentRegisterIndexing(
53 "amdgpu-use-divergent-register-indexing",
54 cl::Hidden,
55 cl::desc("Use indirect register addressing for divergent indexes"),
56 cl::init(false));
57
58static bool hasFP32Denormals(const MachineFunction &MF) {
59 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
60 return Info->getMode().allFP32Denormals();
61}
62
63static bool hasFP64FP16Denormals(const MachineFunction &MF) {
64 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
65 return Info->getMode().allFP64FP16Denormals();
66}
67
68static unsigned findFirstFreeSGPR(CCState &CCInfo) {
69 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
70 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
71 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
72 return AMDGPU::SGPR0 + Reg;
73 }
74 }
75 llvm_unreachable("Cannot allocate sgpr")::llvm::llvm_unreachable_internal("Cannot allocate sgpr", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 75)
;
76}
77
78SITargetLowering::SITargetLowering(const TargetMachine &TM,
79 const GCNSubtarget &STI)
80 : AMDGPUTargetLowering(TM, STI),
81 Subtarget(&STI) {
82 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
83 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
84
85 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
86 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
87
88 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
89
90 const SIRegisterInfo *TRI = STI.getRegisterInfo();
91 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
92
93 addRegisterClass(MVT::f64, V64RegClass);
94 addRegisterClass(MVT::v2f32, V64RegClass);
95
96 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
97 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
98
99 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
100 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
101
102 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
103 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
104
105 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
106 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
107
108 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
109 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
110
111 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
112 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
113
114 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
115 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
116
117 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
118 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
119
120 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
121 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
122
123 addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
124 addRegisterClass(MVT::v9f32, TRI->getVGPRClassForBitWidth(288));
125
126 addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
127 addRegisterClass(MVT::v10f32, TRI->getVGPRClassForBitWidth(320));
128
129 addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
130 addRegisterClass(MVT::v11f32, TRI->getVGPRClassForBitWidth(352));
131
132 addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
133 addRegisterClass(MVT::v12f32, TRI->getVGPRClassForBitWidth(384));
134
135 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
136 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
137
138 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
139 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
140
141 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
142 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
143
144 if (Subtarget->has16BitInsts()) {
145 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
146 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
147
148 // Unless there are also VOP3P operations, not operations are really legal.
149 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
150 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
151 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
152 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
153 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
154 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
155 addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
156 addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
157 }
158
159 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
160 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
161
162 computeRegisterProperties(Subtarget->getRegisterInfo());
163
164 // The boolean content concept here is too inflexible. Compares only ever
165 // really produce a 1-bit result. Any copy/extend from these will turn into a
166 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
167 // it's what most targets use.
168 setBooleanContents(ZeroOrOneBooleanContent);
169 setBooleanVectorContents(ZeroOrOneBooleanContent);
170
171 // We need to custom lower vector stores from local memory
172 setOperationAction(ISD::LOAD,
173 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
174 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
175 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
176 MVT::i1, MVT::v32i32},
177 Custom);
178
179 setOperationAction(ISD::STORE,
180 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
181 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
182 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
183 MVT::i1, MVT::v32i32},
184 Custom);
185
186 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
187 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
188 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
189 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
190 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
191 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
192 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
193 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
194 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
195 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
196 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
197 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
198 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
199 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
200 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
201 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
202
203 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
204 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
205 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
206 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
207 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
208 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
209 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
210
211 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
212
213 setOperationAction(ISD::SELECT, MVT::i1, Promote);
214 setOperationAction(ISD::SELECT, MVT::i64, Custom);
215 setOperationAction(ISD::SELECT, MVT::f64, Promote);
216 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
217
218 setOperationAction(ISD::SELECT_CC,
219 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
220
221 setOperationAction(ISD::SETCC, MVT::i1, Promote);
222 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
224
225 setOperationAction(ISD::TRUNCATE,
226 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
227 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
228 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32},
229 Expand);
230 setOperationAction(ISD::FP_ROUND,
231 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
232 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v9f32,
233 MVT::v10f32, MVT::v11f32, MVT::v12f32, MVT::v16f32},
234 Expand);
235
236 setOperationAction(ISD::SIGN_EXTEND_INREG,
237 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
238 MVT::v3i16, MVT::v4i16, MVT::Other},
239 Custom);
240
241 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
242 setOperationAction(ISD::BR_CC,
243 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
244
245 setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal);
246
247 setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY}, MVT::i32, Legal);
248
249 setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64,
250 Expand);
251
252#if 0
253 setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY}, MVT::i64, Legal);
254#endif
255
256 // We only support LOAD/STORE and vector manipulation ops for vectors
257 // with > 4 elements.
258 for (MVT VT :
259 {MVT::v8i32, MVT::v8f32, MVT::v9i32, MVT::v9f32, MVT::v10i32,
260 MVT::v10f32, MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32,
261 MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64, MVT::v4i16,
262 MVT::v4f16, MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
263 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, MVT::v8i16,
264 MVT::v8f16, MVT::v16i16, MVT::v16f16, MVT::v16i64, MVT::v16f64,
265 MVT::v32i32, MVT::v32f32}) {
266 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
267 switch (Op) {
268 case ISD::LOAD:
269 case ISD::STORE:
270 case ISD::BUILD_VECTOR:
271 case ISD::BITCAST:
272 case ISD::UNDEF:
273 case ISD::EXTRACT_VECTOR_ELT:
274 case ISD::INSERT_VECTOR_ELT:
275 case ISD::EXTRACT_SUBVECTOR:
276 case ISD::SCALAR_TO_VECTOR:
277 case ISD::IS_FPCLASS:
278 break;
279 case ISD::INSERT_SUBVECTOR:
280 case ISD::CONCAT_VECTORS:
281 setOperationAction(Op, VT, Custom);
282 break;
283 default:
284 setOperationAction(Op, VT, Expand);
285 break;
286 }
287 }
288 }
289
290 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
291
292 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
293 // is expanded to avoid having two separate loops in case the index is a VGPR.
294
295 // Most operations are naturally 32-bit vector operations. We only support
296 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
297 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
298 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
299 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
300
301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
302 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
303
304 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
305 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
306
307 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
308 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
309 }
310
311 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
312 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
313 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
314
315 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
316 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
317
318 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
319 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
320
321 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
322 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
323 }
324
325 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
326 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
327 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
328
329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
330 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
331
332 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
333 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
334
335 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
336 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
337 }
338
339 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
340 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
341 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
342
343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
344 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
345
346 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
347 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
348
349 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
350 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
351 }
352
353 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
354 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
355 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
356
357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
358 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
359
360 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
361 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
362
363 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
364 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
365 }
366
367 setOperationAction(ISD::VECTOR_SHUFFLE,
368 {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
369 Expand);
370
371 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom);
372
373 // Avoid stack access for these.
374 // TODO: Generalize to more vector types.
375 setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT},
376 {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
377 MVT::v4i16, MVT::v4f16},
378 Custom);
379
380 // Deal with vec3 vector operations when widened to vec4.
381 setOperationAction(ISD::INSERT_SUBVECTOR,
382 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
383
384 // Deal with vec5/6/7 vector operations when widened to vec8.
385 setOperationAction(ISD::INSERT_SUBVECTOR,
386 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
387 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32,
388 MVT::v9i32, MVT::v9f32, MVT::v10i32, MVT::v10f32,
389 MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32},
390 Custom);
391
392 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
393 // and output demarshalling
394 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
395
396 // We can't return success/failure, only the old value,
397 // let LLVM add the comparison
398 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64},
399 Expand);
400
401 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
402
403 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
404
405 // FIXME: This should be narrowed to i32, but that only happens if i64 is
406 // illegal.
407 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
408 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
409
410 // On SI this is s_memtime and s_memrealtime on VI.
411 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
412 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom);
413
414 if (Subtarget->has16BitInsts()) {
415 setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote);
416 setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom);
417 }
418
419 if (Subtarget->hasMadMacF32Insts())
420 setOperationAction(ISD::FMAD, MVT::f32, Legal);
421
422 if (!Subtarget->hasBFI())
423 // fcopysign can be done in a single instruction with BFI.
424 setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
425
426 if (!Subtarget->hasBCNT(32))
427 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
428
429 if (!Subtarget->hasBCNT(64))
430 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
431
432 if (Subtarget->hasFFBH())
433 setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom);
434
435 if (Subtarget->hasFFBL())
436 setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom);
437
438 // We only really have 32-bit BFE instructions (and 16-bit on VI).
439 //
440 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
441 // effort to match them now. We want this to be false for i64 cases when the
442 // extraction isn't restricted to the upper or lower half. Ideally we would
443 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
444 // span the midpoint are probably relatively rare, so don't worry about them
445 // for now.
446 if (Subtarget->hasBFE())
447 setHasExtractBitsInsn(true);
448
449 // Clamp modifier on add/sub
450 if (Subtarget->hasIntClamp())
451 setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal);
452
453 if (Subtarget->hasAddNoCarry())
454 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
455 Legal);
456
457 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
458 Custom);
459
460 // These are really only legal for ieee_mode functions. We should be avoiding
461 // them for functions that don't have ieee_mode enabled, so just say they are
462 // legal.
463 setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
464 {MVT::f32, MVT::f64}, Legal);
465
466 if (Subtarget->haveRoundOpsF64())
467 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal);
468 else
469 setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR},
470 MVT::f64, Custom);
471
472 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
473
474 setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom);
475 setOperationAction(ISD::FDIV, MVT::f64, Custom);
476
477 setOperationAction(ISD::BF16_TO_FP, {MVT::i16, MVT::f32, MVT::f64}, Expand);
478 setOperationAction(ISD::FP_TO_BF16, {MVT::i16, MVT::f32, MVT::f64}, Expand);
479
480 if (Subtarget->has16BitInsts()) {
481 setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN,
482 ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT},
483 MVT::i16, Legal);
484
485 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
486
487 setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC},
488 MVT::i16, Expand);
489
490 setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM,
491 ISD::UREM, ISD::BITREVERSE, ISD::CTTZ,
492 ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF,
493 ISD::CTPOP},
494 MVT::i16, Promote);
495
496 setOperationAction(ISD::LOAD, MVT::i16, Custom);
497
498 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
499
500 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
501 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
502 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
503 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
504
505 setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom);
506
507 // F16 - Constant Actions.
508 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
509
510 // F16 - Load/Store Actions.
511 setOperationAction(ISD::LOAD, MVT::f16, Promote);
512 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
513 setOperationAction(ISD::STORE, MVT::f16, Promote);
514 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
515
516 // F16 - VOP1 Actions.
517 setOperationAction(
518 {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND},
519 MVT::f16, Custom);
520
521 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
522
523 setOperationAction(
524 {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP},
525 MVT::f16, Promote);
526
527 // F16 - VOP2 Actions.
528 setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand);
529
530 setOperationAction(ISD::FDIV, MVT::f16, Custom);
531
532 // F16 - VOP3 Actions.
533 setOperationAction(ISD::FMA, MVT::f16, Legal);
534 if (STI.hasMadF16())
535 setOperationAction(ISD::FMAD, MVT::f16, Legal);
536
537 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
538 MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
539 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
540 switch (Op) {
541 case ISD::LOAD:
542 case ISD::STORE:
543 case ISD::BUILD_VECTOR:
544 case ISD::BITCAST:
545 case ISD::UNDEF:
546 case ISD::EXTRACT_VECTOR_ELT:
547 case ISD::INSERT_VECTOR_ELT:
548 case ISD::INSERT_SUBVECTOR:
549 case ISD::EXTRACT_SUBVECTOR:
550 case ISD::SCALAR_TO_VECTOR:
551 case ISD::IS_FPCLASS:
552 break;
553 case ISD::CONCAT_VECTORS:
554 setOperationAction(Op, VT, Custom);
555 break;
556 default:
557 setOperationAction(Op, VT, Expand);
558 break;
559 }
560 }
561 }
562
563 // v_perm_b32 can handle either of these.
564 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
565 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
566
567 // XXX - Do these do anything? Vector constants turn into build_vector.
568 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
569
570 setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal);
571
572 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
573 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
574 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
575 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
576
577 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
578 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
579 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
580 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
581
582 setOperationAction(ISD::AND, MVT::v2i16, Promote);
583 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
584 setOperationAction(ISD::OR, MVT::v2i16, Promote);
585 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
586 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
587 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
588
589 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
590 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
591 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
592 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
593
594 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
595 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
596 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
597 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
598
599 setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
600 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
601 setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
602 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
603
604 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
605 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
606 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
607 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
608
609 setOperationAction(ISD::STORE, MVT::v8i16, Promote);
610 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
611 setOperationAction(ISD::STORE, MVT::v8f16, Promote);
612 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
613
614 setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
615 AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
616 setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
617 AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
618
619 setOperationAction(ISD::STORE, MVT::v16i16, Promote);
620 AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
621 setOperationAction(ISD::STORE, MVT::v16f16, Promote);
622 AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
623
624 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
625 MVT::v2i32, Expand);
626 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
627
628 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
629 MVT::v4i32, Expand);
630
631 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
632 MVT::v8i32, Expand);
633
634 if (!Subtarget->hasVOP3PInsts())
635 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom);
636
637 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
638 // This isn't really legal, but this avoids the legalizer unrolling it (and
639 // allows matching fneg (fabs x) patterns)
640 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
641
642 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom);
643 setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal);
644
645 setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
646 {MVT::v4f16, MVT::v8f16, MVT::v16f16}, Custom);
647
648 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM},
649 {MVT::v4f16, MVT::v8f16, MVT::v16f16}, Expand);
650
651 for (MVT Vec16 : {MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
652 setOperationAction(
653 {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR},
654 Vec16, Custom);
655 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
656 }
657 }
658
659 if (Subtarget->hasVOP3PInsts()) {
660 setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL,
661 ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
662 ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT},
663 MVT::v2i16, Legal);
664
665 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE,
666 ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE},
667 MVT::v2f16, Legal);
668
669 setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16},
670 Custom);
671
672 setOperationAction(ISD::VECTOR_SHUFFLE,
673 {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16,
674 MVT::v16f16, MVT::v16i16},
675 Custom);
676
677 for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16})
678 // Split vector operations.
679 setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB,
680 ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
681 ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT,
682 ISD::SSUBSAT},
683 VT, Custom);
684
685 for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16})
686 // Split vector operations.
687 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE},
688 VT, Custom);
689
690 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
691 Custom);
692
693 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
694 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom);
695
696 if (Subtarget->hasPackedFP32Ops()) {
697 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG},
698 MVT::v2f32, Legal);
699 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA},
700 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
701 Custom);
702 }
703 }
704
705 setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom);
706
707 if (Subtarget->has16BitInsts()) {
708 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
709 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
710 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
711 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
712 } else {
713 // Legalization hack.
714 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
715
716 setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom);
717 }
718
719 setOperationAction(ISD::SELECT,
720 {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
721 MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16},
722 Custom);
723
724 setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom);
725
726 if (Subtarget->hasMad64_32())
727 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
728
729 setOperationAction(ISD::INTRINSIC_WO_CHAIN,
730 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
731 MVT::v2i16, MVT::v2f16},
732 Custom);
733
734 setOperationAction(ISD::INTRINSIC_W_CHAIN,
735 {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
736 MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
737 MVT::i16, MVT::i8},
738 Custom);
739
740 setOperationAction(ISD::INTRINSIC_VOID,
741 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
742 MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
743 MVT::i8},
744 Custom);
745
746 setTargetDAGCombine({ISD::ADD,
747 ISD::UADDO_CARRY,
748 ISD::SUB,
749 ISD::USUBO_CARRY,
750 ISD::FADD,
751 ISD::FSUB,
752 ISD::FMINNUM,
753 ISD::FMAXNUM,
754 ISD::FMINNUM_IEEE,
755 ISD::FMAXNUM_IEEE,
756 ISD::FMA,
757 ISD::SMIN,
758 ISD::SMAX,
759 ISD::UMIN,
760 ISD::UMAX,
761 ISD::SETCC,
762 ISD::AND,
763 ISD::OR,
764 ISD::XOR,
765 ISD::SINT_TO_FP,
766 ISD::UINT_TO_FP,
767 ISD::FCANONICALIZE,
768 ISD::SCALAR_TO_VECTOR,
769 ISD::ZERO_EXTEND,
770 ISD::SIGN_EXTEND_INREG,
771 ISD::EXTRACT_VECTOR_ELT,
772 ISD::INSERT_VECTOR_ELT,
773 ISD::FCOPYSIGN});
774
775 // All memory operations. Some folding on the pointer operand is done to help
776 // matching the constant offsets in the addressing modes.
777 setTargetDAGCombine({ISD::LOAD,
778 ISD::STORE,
779 ISD::ATOMIC_LOAD,
780 ISD::ATOMIC_STORE,
781 ISD::ATOMIC_CMP_SWAP,
782 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
783 ISD::ATOMIC_SWAP,
784 ISD::ATOMIC_LOAD_ADD,
785 ISD::ATOMIC_LOAD_SUB,
786 ISD::ATOMIC_LOAD_AND,
787 ISD::ATOMIC_LOAD_OR,
788 ISD::ATOMIC_LOAD_XOR,
789 ISD::ATOMIC_LOAD_NAND,
790 ISD::ATOMIC_LOAD_MIN,
791 ISD::ATOMIC_LOAD_MAX,
792 ISD::ATOMIC_LOAD_UMIN,
793 ISD::ATOMIC_LOAD_UMAX,
794 ISD::ATOMIC_LOAD_FADD,
795 ISD::ATOMIC_LOAD_UINC_WRAP,
796 ISD::ATOMIC_LOAD_UDEC_WRAP,
797 ISD::INTRINSIC_VOID,
798 ISD::INTRINSIC_W_CHAIN});
799
800 // FIXME: In other contexts we pretend this is a per-function property.
801 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
802
803 setSchedulingPreference(Sched::RegPressure);
804}
805
806const GCNSubtarget *SITargetLowering::getSubtarget() const {
807 return Subtarget;
808}
809
810//===----------------------------------------------------------------------===//
811// TargetLowering queries
812//===----------------------------------------------------------------------===//
813
814// v_mad_mix* support a conversion from f16 to f32.
815//
816// There is only one special case when denormals are enabled we don't currently,
817// where this is OK to use.
818bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
819 EVT DestVT, EVT SrcVT) const {
820 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
821 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
822 DestVT.getScalarType() == MVT::f32 &&
823 SrcVT.getScalarType() == MVT::f16 &&
824 // TODO: This probably only requires no input flushing?
825 !hasFP32Denormals(DAG.getMachineFunction());
826}
827
828bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
829 LLT DestTy, LLT SrcTy) const {
830 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
831 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
832 DestTy.getScalarSizeInBits() == 32 &&
833 SrcTy.getScalarSizeInBits() == 16 &&
834 // TODO: This probably only requires no input flushing?
835 !hasFP32Denormals(*MI.getMF());
836}
837
838bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
839 // SI has some legal vector types, but no legal vector operations. Say no
840 // shuffles are legal in order to prefer scalarizing some vector operations.
841 return false;
842}
843
844MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
845 CallingConv::ID CC,
846 EVT VT) const {
847 if (CC == CallingConv::AMDGPU_KERNEL)
848 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
849
850 if (VT.isVector()) {
851 EVT ScalarVT = VT.getScalarType();
852 unsigned Size = ScalarVT.getSizeInBits();
853 if (Size == 16) {
854 if (Subtarget->has16BitInsts()) {
855 if (VT.isInteger())
856 return MVT::v2i16;
857 return (ScalarVT == MVT::bf16 ? MVT::i32 : MVT::v2f16);
858 }
859 return VT.isInteger() ? MVT::i32 : MVT::f32;
860 }
861
862 if (Size < 16)
863 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
864 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
865 }
866
867 if (VT.getSizeInBits() > 32)
868 return MVT::i32;
869
870 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
871}
872
873unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
874 CallingConv::ID CC,
875 EVT VT) const {
876 if (CC == CallingConv::AMDGPU_KERNEL)
877 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
878
879 if (VT.isVector()) {
880 unsigned NumElts = VT.getVectorNumElements();
881 EVT ScalarVT = VT.getScalarType();
882 unsigned Size = ScalarVT.getSizeInBits();
883
884 // FIXME: Should probably promote 8-bit vectors to i16.
885 if (Size == 16 && Subtarget->has16BitInsts())
886 return (NumElts + 1) / 2;
887
888 if (Size <= 32)
889 return NumElts;
890
891 if (Size > 32)
892 return NumElts * ((Size + 31) / 32);
893 } else if (VT.getSizeInBits() > 32)
894 return (VT.getSizeInBits() + 31) / 32;
895
896 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
897}
898
899unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
900 LLVMContext &Context, CallingConv::ID CC,
901 EVT VT, EVT &IntermediateVT,
902 unsigned &NumIntermediates, MVT &RegisterVT) const {
903 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
904 unsigned NumElts = VT.getVectorNumElements();
905 EVT ScalarVT = VT.getScalarType();
906 unsigned Size = ScalarVT.getSizeInBits();
907 // FIXME: We should fix the ABI to be the same on targets without 16-bit
908 // support, but unless we can properly handle 3-vectors, it will be still be
909 // inconsistent.
910 if (Size == 16 && Subtarget->has16BitInsts()) {
911 if (ScalarVT == MVT::bf16) {
912 RegisterVT = MVT::i32;
913 IntermediateVT = MVT::v2bf16;
914 } else {
915 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
916 IntermediateVT = RegisterVT;
917 }
918 NumIntermediates = (NumElts + 1) / 2;
919 return NumIntermediates;
920 }
921
922 if (Size == 32) {
923 RegisterVT = ScalarVT.getSimpleVT();
924 IntermediateVT = RegisterVT;
925 NumIntermediates = NumElts;
926 return NumIntermediates;
927 }
928
929 if (Size < 16 && Subtarget->has16BitInsts()) {
930 // FIXME: Should probably form v2i16 pieces
931 RegisterVT = MVT::i16;
932 IntermediateVT = ScalarVT;
933 NumIntermediates = NumElts;
934 return NumIntermediates;
935 }
936
937
938 if (Size != 16 && Size <= 32) {
939 RegisterVT = MVT::i32;
940 IntermediateVT = ScalarVT;
941 NumIntermediates = NumElts;
942 return NumIntermediates;
943 }
944
945 if (Size > 32) {
946 RegisterVT = MVT::i32;
947 IntermediateVT = RegisterVT;
948 NumIntermediates = NumElts * ((Size + 31) / 32);
949 return NumIntermediates;
950 }
951 }
952
953 return TargetLowering::getVectorTypeBreakdownForCallingConv(
954 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
955}
956
957static EVT memVTFromLoadIntrData(Type *Ty, unsigned MaxNumLanes) {
958 assert(MaxNumLanes != 0)(static_cast <bool> (MaxNumLanes != 0) ? void (0) : __assert_fail
("MaxNumLanes != 0", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
;
959
960 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
961 unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
962 return EVT::getVectorVT(Ty->getContext(),
963 EVT::getEVT(VT->getElementType()),
964 NumElts);
965 }
966
967 return EVT::getEVT(Ty);
968}
969
970// Peek through TFE struct returns to only use the data size.
971static EVT memVTFromLoadIntrReturn(Type *Ty, unsigned MaxNumLanes) {
972 auto *ST = dyn_cast<StructType>(Ty);
973 if (!ST)
974 return memVTFromLoadIntrData(Ty, MaxNumLanes);
975
976 // TFE intrinsics return an aggregate type.
977 assert(ST->getNumContainedTypes() == 2 &&(static_cast <bool> (ST->getNumContainedTypes() == 2
&& ST->getContainedType(1)->isIntegerTy(32)) ?
void (0) : __assert_fail ("ST->getNumContainedTypes() == 2 && ST->getContainedType(1)->isIntegerTy(32)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 978, __extension__
__PRETTY_FUNCTION__))
978 ST->getContainedType(1)->isIntegerTy(32))(static_cast <bool> (ST->getNumContainedTypes() == 2
&& ST->getContainedType(1)->isIntegerTy(32)) ?
void (0) : __assert_fail ("ST->getNumContainedTypes() == 2 && ST->getContainedType(1)->isIntegerTy(32)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 978, __extension__
__PRETTY_FUNCTION__))
;
979 return memVTFromLoadIntrData(ST->getContainedType(0), MaxNumLanes);
980}
981
982bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
983 const CallInst &CI,
984 MachineFunction &MF,
985 unsigned IntrID) const {
986 Info.flags = MachineMemOperand::MONone;
987 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
988 Info.flags |= MachineMemOperand::MOInvariant;
989
990 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
991 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
992 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
993 (Intrinsic::ID)IntrID);
994 MemoryEffects ME = Attr.getMemoryEffects();
995 if (ME.doesNotAccessMemory())
996 return false;
997
998 // TODO: Should images get their own address space?
999 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1000
1001 if (RsrcIntr->IsImage)
1002 Info.align.reset();
1003
1004 Info.flags |= MachineMemOperand::MODereferenceable;
1005 if (ME.onlyReadsMemory()) {
1006 unsigned MaxNumLanes = 4;
1007
1008 if (RsrcIntr->IsImage) {
1009 const AMDGPU::ImageDimIntrinsicInfo *Intr
1010 = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1011 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1012 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1013
1014 if (!BaseOpcode->Gather4) {
1015 // If this isn't a gather, we may have excess loaded elements in the
1016 // IR type. Check the dmask for the real number of elements loaded.
1017 unsigned DMask
1018 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1019 MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1020 }
1021 }
1022
1023 Info.memVT = memVTFromLoadIntrReturn(CI.getType(), MaxNumLanes);
1024
1025 // FIXME: What does alignment mean for an image?
1026 Info.opc = ISD::INTRINSIC_W_CHAIN;
1027 Info.flags |= MachineMemOperand::MOLoad;
1028 } else if (ME.onlyWritesMemory()) {
1029 Info.opc = ISD::INTRINSIC_VOID;
1030
1031 Type *DataTy = CI.getArgOperand(0)->getType();
1032 if (RsrcIntr->IsImage) {
1033 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1034 unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1035 Info.memVT = memVTFromLoadIntrData(DataTy, DMaskLanes);
1036 } else
1037 Info.memVT = EVT::getEVT(DataTy);
1038
1039 Info.flags |= MachineMemOperand::MOStore;
1040 } else {
1041 // Atomic
1042 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1043 ISD::INTRINSIC_W_CHAIN;
1044 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1045 Info.flags |= MachineMemOperand::MOLoad |
1046 MachineMemOperand::MOStore |
1047 MachineMemOperand::MODereferenceable;
1048
1049 // XXX - Should this be volatile without known ordering?
1050 Info.flags |= MachineMemOperand::MOVolatile;
1051
1052 switch (IntrID) {
1053 default:
1054 break;
1055 case Intrinsic::amdgcn_raw_buffer_load_lds:
1056 case Intrinsic::amdgcn_struct_buffer_load_lds: {
1057 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1058 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1059 return true;
1060 }
1061 }
1062 }
1063 return true;
1064 }
1065
1066 switch (IntrID) {
1067 case Intrinsic::amdgcn_atomic_inc:
1068 case Intrinsic::amdgcn_atomic_dec:
1069 case Intrinsic::amdgcn_ds_ordered_add:
1070 case Intrinsic::amdgcn_ds_ordered_swap:
1071 case Intrinsic::amdgcn_ds_fadd:
1072 case Intrinsic::amdgcn_ds_fmin:
1073 case Intrinsic::amdgcn_ds_fmax: {
1074 Info.opc = ISD::INTRINSIC_W_CHAIN;
1075 Info.memVT = MVT::getVT(CI.getType());
1076 Info.ptrVal = CI.getOperand(0);
1077 Info.align.reset();
1078 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1079
1080 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1081 if (!Vol->isZero())
1082 Info.flags |= MachineMemOperand::MOVolatile;
1083
1084 return true;
1085 }
1086 case Intrinsic::amdgcn_buffer_atomic_fadd: {
1087 Info.opc = ISD::INTRINSIC_W_CHAIN;
1088 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1089 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1090 Info.align.reset();
1091 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1092
1093 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1094 if (!Vol || !Vol->isZero())
1095 Info.flags |= MachineMemOperand::MOVolatile;
1096
1097 return true;
1098 }
1099 case Intrinsic::amdgcn_ds_add_gs_reg_rtn:
1100 case Intrinsic::amdgcn_ds_sub_gs_reg_rtn: {
1101 Info.opc = ISD::INTRINSIC_W_CHAIN;
1102 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1103 Info.ptrVal = nullptr;
1104 Info.fallbackAddressSpace = AMDGPUAS::STREAMOUT_REGISTER;
1105 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1106 return true;
1107 }
1108 case Intrinsic::amdgcn_ds_append:
1109 case Intrinsic::amdgcn_ds_consume: {
1110 Info.opc = ISD::INTRINSIC_W_CHAIN;
1111 Info.memVT = MVT::getVT(CI.getType());
1112 Info.ptrVal = CI.getOperand(0);
1113 Info.align.reset();
1114 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1115
1116 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1117 if (!Vol->isZero())
1118 Info.flags |= MachineMemOperand::MOVolatile;
1119
1120 return true;
1121 }
1122 case Intrinsic::amdgcn_global_atomic_csub: {
1123 Info.opc = ISD::INTRINSIC_W_CHAIN;
1124 Info.memVT = MVT::getVT(CI.getType());
1125 Info.ptrVal = CI.getOperand(0);
1126 Info.align.reset();
1127 Info.flags |= MachineMemOperand::MOLoad |
1128 MachineMemOperand::MOStore |
1129 MachineMemOperand::MOVolatile;
1130 return true;
1131 }
1132 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1133 Info.opc = ISD::INTRINSIC_W_CHAIN;
1134 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1135
1136 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1137 Info.align.reset();
1138 Info.flags |= MachineMemOperand::MOLoad |
1139 MachineMemOperand::MODereferenceable;
1140 return true;
1141 }
1142 case Intrinsic::amdgcn_global_atomic_fadd:
1143 case Intrinsic::amdgcn_global_atomic_fmin:
1144 case Intrinsic::amdgcn_global_atomic_fmax:
1145 case Intrinsic::amdgcn_flat_atomic_fadd:
1146 case Intrinsic::amdgcn_flat_atomic_fmin:
1147 case Intrinsic::amdgcn_flat_atomic_fmax:
1148 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1149 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1150 Info.opc = ISD::INTRINSIC_W_CHAIN;
1151 Info.memVT = MVT::getVT(CI.getType());
1152 Info.ptrVal = CI.getOperand(0);
1153 Info.align.reset();
1154 Info.flags |= MachineMemOperand::MOLoad |
1155 MachineMemOperand::MOStore |
1156 MachineMemOperand::MODereferenceable |
1157 MachineMemOperand::MOVolatile;
1158 return true;
1159 }
1160 case Intrinsic::amdgcn_ds_gws_init:
1161 case Intrinsic::amdgcn_ds_gws_barrier:
1162 case Intrinsic::amdgcn_ds_gws_sema_v:
1163 case Intrinsic::amdgcn_ds_gws_sema_br:
1164 case Intrinsic::amdgcn_ds_gws_sema_p:
1165 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1166 Info.opc = ISD::INTRINSIC_VOID;
1167
1168 const GCNTargetMachine &TM =
1169 static_cast<const GCNTargetMachine &>(getTargetMachine());
1170
1171 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1172 Info.ptrVal = MFI->getGWSPSV(TM);
1173
1174 // This is an abstract access, but we need to specify a type and size.
1175 Info.memVT = MVT::i32;
1176 Info.size = 4;
1177 Info.align = Align(4);
1178
1179 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1180 Info.flags |= MachineMemOperand::MOLoad;
1181 else
1182 Info.flags |= MachineMemOperand::MOStore;
1183 return true;
1184 }
1185 case Intrinsic::amdgcn_global_load_lds: {
1186 Info.opc = ISD::INTRINSIC_VOID;
1187 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1188 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1189 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1190 MachineMemOperand::MOVolatile;
1191 return true;
1192 }
1193 case Intrinsic::amdgcn_ds_bvh_stack_rtn: {
1194 Info.opc = ISD::INTRINSIC_W_CHAIN;
1195
1196 const GCNTargetMachine &TM =
1197 static_cast<const GCNTargetMachine &>(getTargetMachine());
1198
1199 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1200 Info.ptrVal = MFI->getGWSPSV(TM);
1201
1202 // This is an abstract access, but we need to specify a type and size.
1203 Info.memVT = MVT::i32;
1204 Info.size = 4;
1205 Info.align = Align(4);
1206
1207 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1208 return true;
1209 }
1210 default:
1211 return false;
1212 }
1213}
1214
1215bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1216 SmallVectorImpl<Value*> &Ops,
1217 Type *&AccessTy) const {
1218 switch (II->getIntrinsicID()) {
1219 case Intrinsic::amdgcn_atomic_inc:
1220 case Intrinsic::amdgcn_atomic_dec:
1221 case Intrinsic::amdgcn_ds_ordered_add:
1222 case Intrinsic::amdgcn_ds_ordered_swap:
1223 case Intrinsic::amdgcn_ds_append:
1224 case Intrinsic::amdgcn_ds_consume:
1225 case Intrinsic::amdgcn_ds_fadd:
1226 case Intrinsic::amdgcn_ds_fmin:
1227 case Intrinsic::amdgcn_ds_fmax:
1228 case Intrinsic::amdgcn_global_atomic_fadd:
1229 case Intrinsic::amdgcn_flat_atomic_fadd:
1230 case Intrinsic::amdgcn_flat_atomic_fmin:
1231 case Intrinsic::amdgcn_flat_atomic_fmax:
1232 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1233 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1234 case Intrinsic::amdgcn_global_atomic_csub: {
1235 Value *Ptr = II->getArgOperand(0);
1236 AccessTy = II->getType();
1237 Ops.push_back(Ptr);
1238 return true;
1239 }
1240 default:
1241 return false;
1242 }
1243}
1244
1245bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1246 if (!Subtarget->hasFlatInstOffsets()) {
1247 // Flat instructions do not have offsets, and only have the register
1248 // address.
1249 return AM.BaseOffs == 0 && AM.Scale == 0;
1250 }
1251
1252 return AM.Scale == 0 &&
1253 (AM.BaseOffs == 0 ||
1254 Subtarget->getInstrInfo()->isLegalFLATOffset(
1255 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1256}
1257
1258bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1259 if (Subtarget->hasFlatGlobalInsts())
1260 return AM.Scale == 0 &&
1261 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1262 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1263 SIInstrFlags::FlatGlobal));
1264
1265 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1266 // Assume the we will use FLAT for all global memory accesses
1267 // on VI.
1268 // FIXME: This assumption is currently wrong. On VI we still use
1269 // MUBUF instructions for the r + i addressing mode. As currently
1270 // implemented, the MUBUF instructions only work on buffer < 4GB.
1271 // It may be possible to support > 4GB buffers with MUBUF instructions,
1272 // by setting the stride value in the resource descriptor which would
1273 // increase the size limit to (stride * 4GB). However, this is risky,
1274 // because it has never been validated.
1275 return isLegalFlatAddressingMode(AM);
1276 }
1277
1278 return isLegalMUBUFAddressingMode(AM);
1279}
1280
1281bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1282 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1283 // additionally can do r + r + i with addr64. 32-bit has more addressing
1284 // mode options. Depending on the resource constant, it can also do
1285 // (i64 r0) + (i32 r1) * (i14 i).
1286 //
1287 // Private arrays end up using a scratch buffer most of the time, so also
1288 // assume those use MUBUF instructions. Scratch loads / stores are currently
1289 // implemented as mubuf instructions with offen bit set, so slightly
1290 // different than the normal addr64.
1291 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1292 return false;
1293
1294 // FIXME: Since we can split immediate into soffset and immediate offset,
1295 // would it make sense to allow any immediate?
1296
1297 switch (AM.Scale) {
1298 case 0: // r + i or just i, depending on HasBaseReg.
1299 return true;
1300 case 1:
1301 return true; // We have r + r or r + i.
1302 case 2:
1303 if (AM.HasBaseReg) {
1304 // Reject 2 * r + r.
1305 return false;
1306 }
1307
1308 // Allow 2 * r as r + r
1309 // Or 2 * r + i is allowed as r + r + i.
1310 return true;
1311 default: // Don't allow n * r
1312 return false;
1313 }
1314}
1315
1316bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1317 const AddrMode &AM, Type *Ty,
1318 unsigned AS, Instruction *I) const {
1319 // No global is ever allowed as a base.
1320 if (AM.BaseGV)
1321 return false;
1322
1323 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1324 return isLegalGlobalAddressingMode(AM);
1325
1326 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1327 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1328 AS == AMDGPUAS::BUFFER_FAT_POINTER || AS == AMDGPUAS::BUFFER_RESOURCE) {
1329 // If the offset isn't a multiple of 4, it probably isn't going to be
1330 // correctly aligned.
1331 // FIXME: Can we get the real alignment here?
1332 if (AM.BaseOffs % 4 != 0)
1333 return isLegalMUBUFAddressingMode(AM);
1334
1335 // There are no SMRD extloads, so if we have to do a small type access we
1336 // will use a MUBUF load.
1337 // FIXME?: We also need to do this if unaligned, but we don't know the
1338 // alignment here.
1339 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1340 return isLegalGlobalAddressingMode(AM);
1341
1342 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1343 // SMRD instructions have an 8-bit, dword offset on SI.
1344 if (!isUInt<8>(AM.BaseOffs / 4))
1345 return false;
1346 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1347 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1348 // in 8-bits, it can use a smaller encoding.
1349 if (!isUInt<32>(AM.BaseOffs / 4))
1350 return false;
1351 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1352 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1353 if (!isUInt<20>(AM.BaseOffs))
1354 return false;
1355 } else
1356 llvm_unreachable("unhandled generation")::llvm::llvm_unreachable_internal("unhandled generation", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1356)
;
1357
1358 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1359 return true;
1360
1361 if (AM.Scale == 1 && AM.HasBaseReg)
1362 return true;
1363
1364 return false;
1365 }
1366
1367 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
1368 return isLegalMUBUFAddressingMode(AM);
1369
1370 if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1371 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1372 // field.
1373 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1374 // an 8-bit dword offset but we don't know the alignment here.
1375 if (!isUInt<16>(AM.BaseOffs))
1376 return false;
1377
1378 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1379 return true;
1380
1381 if (AM.Scale == 1 && AM.HasBaseReg)
1382 return true;
1383
1384 return false;
1385 }
1386
1387 if (AS == AMDGPUAS::FLAT_ADDRESS || AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1388 // For an unknown address space, this usually means that this is for some
1389 // reason being used for pure arithmetic, and not based on some addressing
1390 // computation. We don't have instructions that compute pointers with any
1391 // addressing modes, so treat them as having no offset like flat
1392 // instructions.
1393 return isLegalFlatAddressingMode(AM);
1394 }
1395
1396 // Assume a user alias of global for unknown address spaces.
1397 return isLegalGlobalAddressingMode(AM);
1398}
1399
1400bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1401 const MachineFunction &MF) const {
1402 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1403 return (MemVT.getSizeInBits() <= 4 * 32);
1404 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1405 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1406 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1407 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1408 return (MemVT.getSizeInBits() <= 2 * 32);
1409 }
1410 return true;
1411}
1412
1413bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1414 unsigned Size, unsigned AddrSpace, Align Alignment,
1415 MachineMemOperand::Flags Flags, unsigned *IsFast) const {
1416 if (IsFast)
1417 *IsFast = 0;
1418
1419 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1420 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1421 // Check if alignment requirements for ds_read/write instructions are
1422 // disabled.
1423 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1424 return false;
1425
1426 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1427 if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1428 Alignment < RequiredAlignment)
1429 return false;
1430
1431 // Either, the alignment requirements are "enabled", or there is an
1432 // unaligned LDS access related hardware bug though alignment requirements
1433 // are "disabled". In either case, we need to check for proper alignment
1434 // requirements.
1435 //
1436 switch (Size) {
1437 case 64:
1438 // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1439 // address is negative, then the instruction is incorrectly treated as
1440 // out-of-bounds even if base + offsets is in bounds. Split vectorized
1441 // loads here to avoid emitting ds_read2_b32. We may re-combine the
1442 // load later in the SILoadStoreOptimizer.
1443 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1444 return false;
1445
1446 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1447 // can do a 4 byte aligned, 8 byte access in a single operation using
1448 // ds_read2/write2_b32 with adjacent offsets.
1449 RequiredAlignment = Align(4);
1450
1451 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1452 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1453 // ds_write2_b32 depending on the alignment. In either case with either
1454 // alignment there is no faster way of doing this.
1455
1456 // The numbers returned here and below are not additive, it is a 'speed
1457 // rank'. They are just meant to be compared to decide if a certain way
1458 // of lowering an operation is faster than another. For that purpose
1459 // naturally aligned operation gets it bitsize to indicate that "it
1460 // operates with a speed comparable to N-bit wide load". With the full
1461 // alignment ds128 is slower than ds96 for example. If underaligned it
1462 // is comparable to a speed of a single dword access, which would then
1463 // mean 32 < 128 and it is faster to issue a wide load regardless.
1464 // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
1465 // wider load which will not be aligned anymore the latter is slower.
1466 if (IsFast)
1467 *IsFast = (Alignment >= RequiredAlignment) ? 64
1468 : (Alignment < Align(4)) ? 32
1469 : 1;
1470 return true;
1471 }
1472
1473 break;
1474 case 96:
1475 if (!Subtarget->hasDS96AndDS128())
1476 return false;
1477
1478 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1479 // gfx8 and older.
1480
1481 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1482 // Naturally aligned access is fastest. However, also report it is Fast
1483 // if memory is aligned less than DWORD. A narrow load or store will be
1484 // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1485 // be more of them, so overall we will pay less penalty issuing a single
1486 // instruction.
1487
1488 // See comment on the values above.
1489 if (IsFast)
1490 *IsFast = (Alignment >= RequiredAlignment) ? 96
1491 : (Alignment < Align(4)) ? 32
1492 : 1;
1493 return true;
1494 }
1495
1496 break;
1497 case 128:
1498 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1499 return false;
1500
1501 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1502 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
1503 // single operation using ds_read2/write2_b64.
1504 RequiredAlignment = Align(8);
1505
1506 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1507 // Naturally aligned access is fastest. However, also report it is Fast
1508 // if memory is aligned less than DWORD. A narrow load or store will be
1509 // be equally slow as a single ds_read_b128/ds_write_b128, but there
1510 // will be more of them, so overall we will pay less penalty issuing a
1511 // single instruction.
1512
1513 // See comment on the values above.
1514 if (IsFast)
1515 *IsFast = (Alignment >= RequiredAlignment) ? 128
1516 : (Alignment < Align(4)) ? 32
1517 : 1;
1518 return true;
1519 }
1520
1521 break;
1522 default:
1523 if (Size > 32)
1524 return false;
1525
1526 break;
1527 }
1528
1529 // See comment on the values above.
1530 // Note that we have a single-dword or sub-dword here, so if underaligned
1531 // it is a slowest possible access, hence returned value is 0.
1532 if (IsFast)
1533 *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
1534
1535 return Alignment >= RequiredAlignment ||
1536 Subtarget->hasUnalignedDSAccessEnabled();
1537 }
1538
1539 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1540 bool AlignedBy4 = Alignment >= Align(4);
1541 if (IsFast)
1542 *IsFast = AlignedBy4;
1543
1544 return AlignedBy4 ||
1545 Subtarget->enableFlatScratch() ||
1546 Subtarget->hasUnalignedScratchAccess();
1547 }
1548
1549 // FIXME: We have to be conservative here and assume that flat operations
1550 // will access scratch. If we had access to the IR function, then we
1551 // could determine if any private memory was used in the function.
1552 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1553 !Subtarget->hasUnalignedScratchAccess()) {
1554 bool AlignedBy4 = Alignment >= Align(4);
1555 if (IsFast)
1556 *IsFast = AlignedBy4;
1557
1558 return AlignedBy4;
1559 }
1560
1561 // So long as they are correct, wide global memory operations perform better
1562 // than multiple smaller memory ops -- even when misaligned
1563 if (AMDGPU::isExtendedGlobalAddrSpace(AddrSpace)) {
1564 if (IsFast)
1565 *IsFast = Size;
1566
1567 return Alignment >= Align(4) ||
1568 Subtarget->hasUnalignedBufferAccessEnabled();
1569 }
1570
1571 // Smaller than dword value must be aligned.
1572 if (Size < 32)
1573 return false;
1574
1575 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1576 // byte-address are ignored, thus forcing Dword alignment.
1577 // This applies to private, global, and constant memory.
1578 if (IsFast)
1579 *IsFast = 1;
1580
1581 return Size >= 32 && Alignment >= Align(4);
1582}
1583
1584bool SITargetLowering::allowsMisalignedMemoryAccesses(
1585 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1586 unsigned *IsFast) const {
1587 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1588 Alignment, Flags, IsFast);
1589}
1590
1591EVT SITargetLowering::getOptimalMemOpType(
1592 const MemOp &Op, const AttributeList &FuncAttributes) const {
1593 // FIXME: Should account for address space here.
1594
1595 // The default fallback uses the private pointer size as a guess for a type to
1596 // use. Make sure we switch these to 64-bit accesses.
1597
1598 if (Op.size() >= 16 &&
1599 Op.isDstAligned(Align(4))) // XXX: Should only do for global
1600 return MVT::v4i32;
1601
1602 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1603 return MVT::v2i32;
1604
1605 // Use the default.
1606 return MVT::Other;
1607}
1608
1609bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1610 const MemSDNode *MemNode = cast<MemSDNode>(N);
1611 return MemNode->getMemOperand()->getFlags() & MONoClobber;
1612}
1613
1614bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1615 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1616 AS == AMDGPUAS::PRIVATE_ADDRESS;
1617}
1618
1619bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1620 unsigned DestAS) const {
1621 // Flat -> private/local is a simple truncate.
1622 // Flat -> global is no-op
1623 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1624 return true;
1625
1626 const GCNTargetMachine &TM =
1627 static_cast<const GCNTargetMachine &>(getTargetMachine());
1628 return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1629}
1630
1631bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1632 const MemSDNode *MemNode = cast<MemSDNode>(N);
1633
1634 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1635}
1636
1637TargetLoweringBase::LegalizeTypeAction
1638SITargetLowering::getPreferredVectorAction(MVT VT) const {
1639 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1640 VT.getScalarType().bitsLE(MVT::i16))
1641 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1642 return TargetLoweringBase::getPreferredVectorAction(VT);
1643}
1644
1645bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1646 Type *Ty) const {
1647 // FIXME: Could be smarter if called for vector constants.
1648 return true;
1649}
1650
1651bool SITargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
1652 unsigned Index) const {
1653 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
1654 return false;
1655
1656 // TODO: Add more cases that are cheap.
1657 return Index == 0;
1658}
1659
1660bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1661 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1662 switch (Op) {
1663 case ISD::LOAD:
1664 case ISD::STORE:
1665
1666 // These operations are done with 32-bit instructions anyway.
1667 case ISD::AND:
1668 case ISD::OR:
1669 case ISD::XOR:
1670 case ISD::SELECT:
1671 // TODO: Extensions?
1672 return true;
1673 default:
1674 return false;
1675 }
1676 }
1677
1678 // SimplifySetCC uses this function to determine whether or not it should
1679 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1680 if (VT == MVT::i1 && Op == ISD::SETCC)
1681 return false;
1682
1683 return TargetLowering::isTypeDesirableForOp(Op, VT);
1684}
1685
1686SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1687 const SDLoc &SL,
1688 SDValue Chain,
1689 uint64_t Offset) const {
1690 const DataLayout &DL = DAG.getDataLayout();
1691 MachineFunction &MF = DAG.getMachineFunction();
1692 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1693
1694 const ArgDescriptor *InputPtrReg;
1695 const TargetRegisterClass *RC;
1696 LLT ArgTy;
1697 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1698
1699 std::tie(InputPtrReg, RC, ArgTy) =
1700 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1701
1702 // We may not have the kernarg segment argument if we have no kernel
1703 // arguments.
1704 if (!InputPtrReg)
1705 return DAG.getConstant(0, SL, PtrVT);
1706
1707 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1708 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1709 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1710
1711 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1712}
1713
1714SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1715 const SDLoc &SL) const {
1716 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1717 FIRST_IMPLICIT);
1718 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1719}
1720
1721SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
1722 const SDLoc &SL) const {
1723
1724 Function &F = DAG.getMachineFunction().getFunction();
1725 std::optional<uint32_t> KnownSize =
1726 AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
1727 if (KnownSize.has_value())
1728 return DAG.getConstant(*KnownSize, SL, MVT::i32);
1729 return SDValue();
1730}
1731
1732SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1733 const SDLoc &SL, SDValue Val,
1734 bool Signed,
1735 const ISD::InputArg *Arg) const {
1736 // First, if it is a widened vector, narrow it.
1737 if (VT.isVector() &&
1738 VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1739 EVT NarrowedVT =
1740 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1741 VT.getVectorNumElements());
1742 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1743 DAG.getConstant(0, SL, MVT::i32));
1744 }
1745
1746 // Then convert the vector elements or scalar value.
1747 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1748 VT.bitsLT(MemVT)) {
1749 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1750 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1751 }
1752
1753 if (MemVT.isFloatingPoint())
1754 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1755 else if (Signed)
1756 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1757 else
1758 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1759
1760 return Val;
1761}
1762
1763SDValue SITargetLowering::lowerKernargMemParameter(
1764 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1765 uint64_t Offset, Align Alignment, bool Signed,
1766 const ISD::InputArg *Arg) const {
1767 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1768
1769 // Try to avoid using an extload by loading earlier than the argument address,
1770 // and extracting the relevant bits. The load should hopefully be merged with
1771 // the previous argument.
1772 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1773 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1774 int64_t AlignDownOffset = alignDown(Offset, 4);
1775 int64_t OffsetDiff = Offset - AlignDownOffset;
1776
1777 EVT IntVT = MemVT.changeTypeToInteger();
1778
1779 // TODO: If we passed in the base kernel offset we could have a better
1780 // alignment than 4, but we don't really need it.
1781 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1782 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1783 MachineMemOperand::MODereferenceable |
1784 MachineMemOperand::MOInvariant);
1785
1786 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1787 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1788
1789 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1790 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1791 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1792
1793
1794 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1795 }
1796
1797 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1798 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1799 MachineMemOperand::MODereferenceable |
1800 MachineMemOperand::MOInvariant);
1801
1802 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1803 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1804}
1805
1806SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1807 const SDLoc &SL, SDValue Chain,
1808 const ISD::InputArg &Arg) const {
1809 MachineFunction &MF = DAG.getMachineFunction();
1810 MachineFrameInfo &MFI = MF.getFrameInfo();
1811
1812 if (Arg.Flags.isByVal()) {
1813 unsigned Size = Arg.Flags.getByValSize();
1814 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1815 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1816 }
1817
1818 unsigned ArgOffset = VA.getLocMemOffset();
1819 unsigned ArgSize = VA.getValVT().getStoreSize();
1820
1821 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1822
1823 // Create load nodes to retrieve arguments from the stack.
1824 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1825 SDValue ArgValue;
1826
1827 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1828 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1829 MVT MemVT = VA.getValVT();
1830
1831 switch (VA.getLocInfo()) {
1832 default:
1833 break;
1834 case CCValAssign::BCvt:
1835 MemVT = VA.getLocVT();
1836 break;
1837 case CCValAssign::SExt:
1838 ExtType = ISD::SEXTLOAD;
1839 break;
1840 case CCValAssign::ZExt:
1841 ExtType = ISD::ZEXTLOAD;
1842 break;
1843 case CCValAssign::AExt:
1844 ExtType = ISD::EXTLOAD;
1845 break;
1846 }
1847
1848 ArgValue = DAG.getExtLoad(
1849 ExtType, SL, VA.getLocVT(), Chain, FIN,
1850 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1851 MemVT);
1852 return ArgValue;
1853}
1854
1855SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1856 const SIMachineFunctionInfo &MFI,
1857 EVT VT,
1858 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1859 const ArgDescriptor *Reg;
1860 const TargetRegisterClass *RC;
1861 LLT Ty;
1862
1863 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1864 if (!Reg) {
1865 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1866 // It's possible for a kernarg intrinsic call to appear in a kernel with
1867 // no allocated segment, in which case we do not add the user sgpr
1868 // argument, so just return null.
1869 return DAG.getConstant(0, SDLoc(), VT);
1870 }
1871
1872 // It's undefined behavior if a function marked with the amdgpu-no-*
1873 // attributes uses the corresponding intrinsic.
1874 return DAG.getUNDEF(VT);
1875 }
1876
1877 return loadInputValue(DAG, RC, VT, SDLoc(DAG.getEntryNode()), *Reg);
1878}
1879
1880static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1881 CallingConv::ID CallConv,
1882 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1883 FunctionType *FType,
1884 SIMachineFunctionInfo *Info) {
1885 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1886 const ISD::InputArg *Arg = &Ins[I];
1887
1888 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "vector type argument should have been split"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 1889, __extension__
__PRETTY_FUNCTION__))
1889 "vector type argument should have been split")(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "vector type argument should have been split"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"vector type argument should have been split\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 1889, __extension__
__PRETTY_FUNCTION__))
;
1890
1891 // First check if it's a PS input addr.
1892 if (CallConv == CallingConv::AMDGPU_PS &&
1893 !Arg->Flags.isInReg() && PSInputNum <= 15) {
1894 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1895
1896 // Inconveniently only the first part of the split is marked as isSplit,
1897 // so skip to the end. We only want to increment PSInputNum once for the
1898 // entire split argument.
1899 if (Arg->Flags.isSplit()) {
1900 while (!Arg->Flags.isSplitEnd()) {
1901 assert((!Arg->VT.isVector() ||(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "unexpected vector split in ps argument type"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 1903, __extension__
__PRETTY_FUNCTION__))
1902 Arg->VT.getScalarSizeInBits() == 16) &&(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "unexpected vector split in ps argument type"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 1903, __extension__
__PRETTY_FUNCTION__))
1903 "unexpected vector split in ps argument type")(static_cast <bool> ((!Arg->VT.isVector() || Arg->
VT.getScalarSizeInBits() == 16) && "unexpected vector split in ps argument type"
) ? void (0) : __assert_fail ("(!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && \"unexpected vector split in ps argument type\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 1903, __extension__
__PRETTY_FUNCTION__))
;
1904 if (!SkipArg)
1905 Splits.push_back(*Arg);
1906 Arg = &Ins[++I];
1907 }
1908 }
1909
1910 if (SkipArg) {
1911 // We can safely skip PS inputs.
1912 Skipped.set(Arg->getOrigArgIndex());
1913 ++PSInputNum;
1914 continue;
1915 }
1916
1917 Info->markPSInputAllocated(PSInputNum);
1918 if (Arg->Used)
1919 Info->markPSInputEnabled(PSInputNum);
1920
1921 ++PSInputNum;
1922 }
1923
1924 Splits.push_back(*Arg);
1925 }
1926}
1927
1928// Allocate special inputs passed in VGPRs.
1929void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1930 MachineFunction &MF,
1931 const SIRegisterInfo &TRI,
1932 SIMachineFunctionInfo &Info) const {
1933 const LLT S32 = LLT::scalar(32);
1934 MachineRegisterInfo &MRI = MF.getRegInfo();
1935
1936 if (Info.hasWorkItemIDX()) {
1937 Register Reg = AMDGPU::VGPR0;
1938 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1939
1940 CCInfo.AllocateReg(Reg);
1941 unsigned Mask = (Subtarget->hasPackedTID() &&
1942 Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1943 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1944 }
1945
1946 if (Info.hasWorkItemIDY()) {
1947 assert(Info.hasWorkItemIDX())(static_cast <bool> (Info.hasWorkItemIDX()) ? void (0) :
__assert_fail ("Info.hasWorkItemIDX()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1947, __extension__ __PRETTY_FUNCTION__))
;
1948 if (Subtarget->hasPackedTID()) {
1949 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1950 0x3ff << 10));
1951 } else {
1952 unsigned Reg = AMDGPU::VGPR1;
1953 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1954
1955 CCInfo.AllocateReg(Reg);
1956 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1957 }
1958 }
1959
1960 if (Info.hasWorkItemIDZ()) {
1961 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY())(static_cast <bool> (Info.hasWorkItemIDX() && Info
.hasWorkItemIDY()) ? void (0) : __assert_fail ("Info.hasWorkItemIDX() && Info.hasWorkItemIDY()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 1961, __extension__
__PRETTY_FUNCTION__))
;
1962 if (Subtarget->hasPackedTID()) {
1963 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1964 0x3ff << 20));
1965 } else {
1966 unsigned Reg = AMDGPU::VGPR2;
1967 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1968
1969 CCInfo.AllocateReg(Reg);
1970 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1971 }
1972 }
1973}
1974
1975// Try to allocate a VGPR at the end of the argument list, or if no argument
1976// VGPRs are left allocating a stack slot.
1977// If \p Mask is is given it indicates bitfield position in the register.
1978// If \p Arg is given use it with new ]p Mask instead of allocating new.
1979static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1980 ArgDescriptor Arg = ArgDescriptor()) {
1981 if (Arg.isSet())
1982 return ArgDescriptor::createArg(Arg, Mask);
1983
1984 ArrayRef<MCPhysReg> ArgVGPRs = ArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1985 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1986 if (RegIdx == ArgVGPRs.size()) {
1987 // Spill to stack required.
1988 int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1989
1990 return ArgDescriptor::createStack(Offset, Mask);
1991 }
1992
1993 unsigned Reg = ArgVGPRs[RegIdx];
1994 Reg = CCInfo.AllocateReg(Reg);
1995 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 1995, __extension__ __PRETTY_FUNCTION__))
;
1996
1997 MachineFunction &MF = CCInfo.getMachineFunction();
1998 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1999 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2000 return ArgDescriptor::createRegister(Reg, Mask);
2001}
2002
2003static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2004 const TargetRegisterClass *RC,
2005 unsigned NumArgRegs) {
2006 ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
2007 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2008 if (RegIdx == ArgSGPRs.size())
2009 report_fatal_error("ran out of SGPRs for arguments");
2010
2011 unsigned Reg = ArgSGPRs[RegIdx];
2012 Reg = CCInfo.AllocateReg(Reg);
2013 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2013, __extension__ __PRETTY_FUNCTION__))
;
2014
2015 MachineFunction &MF = CCInfo.getMachineFunction();
2016 MF.addLiveIn(Reg, RC);
2017 return ArgDescriptor::createRegister(Reg);
2018}
2019
2020// If this has a fixed position, we still should allocate the register in the
2021// CCInfo state. Technically we could get away with this for values passed
2022// outside of the normal argument range.
2023static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2024 const TargetRegisterClass *RC,
2025 MCRegister Reg) {
2026 Reg = CCInfo.AllocateReg(Reg);
2027 assert(Reg != AMDGPU::NoRegister)(static_cast <bool> (Reg != AMDGPU::NoRegister) ? void (
0) : __assert_fail ("Reg != AMDGPU::NoRegister", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2027, __extension__ __PRETTY_FUNCTION__))
;
2028 MachineFunction &MF = CCInfo.getMachineFunction();
2029 MF.addLiveIn(Reg, RC);
2030}
2031
2032static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2033 if (Arg) {
2034 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2035 Arg.getRegister());
2036 } else
2037 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2038}
2039
2040static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2041 if (Arg) {
2042 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2043 Arg.getRegister());
2044 } else
2045 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2046}
2047
2048/// Allocate implicit function VGPR arguments at the end of allocated user
2049/// arguments.
2050void SITargetLowering::allocateSpecialInputVGPRs(
2051 CCState &CCInfo, MachineFunction &MF,
2052 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2053 const unsigned Mask = 0x3ff;
2054 ArgDescriptor Arg;
2055
2056 if (Info.hasWorkItemIDX()) {
2057 Arg = allocateVGPR32Input(CCInfo, Mask);
2058 Info.setWorkItemIDX(Arg);
2059 }
2060
2061 if (Info.hasWorkItemIDY()) {
2062 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2063 Info.setWorkItemIDY(Arg);
2064 }
2065
2066 if (Info.hasWorkItemIDZ())
2067 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2068}
2069
2070/// Allocate implicit function VGPR arguments in fixed registers.
2071void SITargetLowering::allocateSpecialInputVGPRsFixed(
2072 CCState &CCInfo, MachineFunction &MF,
2073 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2074 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2075 if (!Reg)
2076 report_fatal_error("failed to allocated VGPR for implicit arguments");
2077
2078 const unsigned Mask = 0x3ff;
2079 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2080 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2081 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2082}
2083
2084void SITargetLowering::allocateSpecialInputSGPRs(
2085 CCState &CCInfo,
2086 MachineFunction &MF,
2087 const SIRegisterInfo &TRI,
2088 SIMachineFunctionInfo &Info) const {
2089 auto &ArgInfo = Info.getArgInfo();
2090
2091 // TODO: Unify handling with private memory pointers.
2092 if (Info.hasDispatchPtr())
2093 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2094
2095 const Module *M = MF.getFunction().getParent();
2096 if (Info.hasQueuePtr() &&
2097 AMDGPU::getCodeObjectVersion(*M) < AMDGPU::AMDHSA_COV5)
2098 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2099
2100 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2101 // constant offset from the kernarg segment.
2102 if (Info.hasImplicitArgPtr())
2103 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2104
2105 if (Info.hasDispatchID())
2106 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2107
2108 // flat_scratch_init is not applicable for non-kernel functions.
2109
2110 if (Info.hasWorkGroupIDX())
2111 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2112
2113 if (Info.hasWorkGroupIDY())
2114 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2115
2116 if (Info.hasWorkGroupIDZ())
2117 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2118
2119 if (Info.hasLDSKernelId())
2120 allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
2121}
2122
2123// Allocate special inputs passed in user SGPRs.
2124void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2125 MachineFunction &MF,
2126 const SIRegisterInfo &TRI,
2127 SIMachineFunctionInfo &Info) const {
2128 if (Info.hasImplicitBufferPtr()) {
2129 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2130 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2131 CCInfo.AllocateReg(ImplicitBufferPtrReg);
2132 }
2133
2134 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2135 if (Info.hasPrivateSegmentBuffer()) {
2136 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2137 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2138 CCInfo.AllocateReg(PrivateSegmentBufferReg);
2139 }
2140
2141 if (Info.hasDispatchPtr()) {
2142 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2143 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2144 CCInfo.AllocateReg(DispatchPtrReg);
2145 }
2146
2147 const Module *M = MF.getFunction().getParent();
2148 if (Info.hasQueuePtr() &&
2149 AMDGPU::getCodeObjectVersion(*M) < AMDGPU::AMDHSA_COV5) {
2150 Register QueuePtrReg = Info.addQueuePtr(TRI);
2151 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2152 CCInfo.AllocateReg(QueuePtrReg);
2153 }
2154
2155 if (Info.hasKernargSegmentPtr()) {
2156 MachineRegisterInfo &MRI = MF.getRegInfo();
2157 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2158 CCInfo.AllocateReg(InputPtrReg);
2159
2160 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2161 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2162 }
2163
2164 if (Info.hasDispatchID()) {
2165 Register DispatchIDReg = Info.addDispatchID(TRI);
2166 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2167 CCInfo.AllocateReg(DispatchIDReg);
2168 }
2169
2170 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2171 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2172 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2173 CCInfo.AllocateReg(FlatScratchInitReg);
2174 }
2175
2176 if (Info.hasLDSKernelId()) {
2177 Register Reg = Info.addLDSKernelId();
2178 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2179 CCInfo.AllocateReg(Reg);
2180 }
2181
2182 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2183 // these from the dispatch pointer.
2184}
2185
2186// Allocate special input registers that are initialized per-wave.
2187void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2188 MachineFunction &MF,
2189 SIMachineFunctionInfo &Info,
2190 CallingConv::ID CallConv,
2191 bool IsShader) const {
2192 bool HasArchitectedSGPRs = Subtarget->hasArchitectedSGPRs();
2193 if (Subtarget->hasUserSGPRInit16Bug() && !IsShader) {
2194 // Note: user SGPRs are handled by the front-end for graphics shaders
2195 // Pad up the used user SGPRs with dead inputs.
2196
2197 // TODO: NumRequiredSystemSGPRs computation should be adjusted appropriately
2198 // before enabling architected SGPRs for workgroup IDs.
2199 assert(!HasArchitectedSGPRs && "Unhandled feature for the subtarget")(static_cast <bool> (!HasArchitectedSGPRs && "Unhandled feature for the subtarget"
) ? void (0) : __assert_fail ("!HasArchitectedSGPRs && \"Unhandled feature for the subtarget\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2199, __extension__
__PRETTY_FUNCTION__))
;
2200
2201 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
2202 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
2203 // rely on it to reach 16 since if we end up having no stack usage, it will
2204 // not really be added.
2205 unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() +
2206 Info.hasWorkGroupIDY() +
2207 Info.hasWorkGroupIDZ() +
2208 Info.hasWorkGroupInfo();
2209 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
2210 Register Reg = Info.addReservedUserSGPR();
2211 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2212 CCInfo.AllocateReg(Reg);
2213 }
2214 }
2215
2216 if (Info.hasWorkGroupIDX()) {
2217 Register Reg = Info.addWorkGroupIDX(HasArchitectedSGPRs);
2218 if (!HasArchitectedSGPRs)
2219 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2220
2221 CCInfo.AllocateReg(Reg);
2222 }
2223
2224 if (Info.hasWorkGroupIDY()) {
2225 Register Reg = Info.addWorkGroupIDY(HasArchitectedSGPRs);
2226 if (!HasArchitectedSGPRs)
2227 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2228
2229 CCInfo.AllocateReg(Reg);
2230 }
2231
2232 if (Info.hasWorkGroupIDZ()) {
2233 Register Reg = Info.addWorkGroupIDZ(HasArchitectedSGPRs);
2234 if (!HasArchitectedSGPRs)
2235 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2236
2237 CCInfo.AllocateReg(Reg);
2238 }
2239
2240 if (Info.hasWorkGroupInfo()) {
2241 Register Reg = Info.addWorkGroupInfo();
2242 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2243 CCInfo.AllocateReg(Reg);
2244 }
2245
2246 if (Info.hasPrivateSegmentWaveByteOffset()) {
2247 // Scratch wave offset passed in system SGPR.
2248 unsigned PrivateSegmentWaveByteOffsetReg;
2249
2250 if (IsShader) {
2251 PrivateSegmentWaveByteOffsetReg =
2252 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2253
2254 // This is true if the scratch wave byte offset doesn't have a fixed
2255 // location.
2256 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2257 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2258 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2259 }
2260 } else
2261 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2262
2263 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2264 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2265 }
2266
2267 assert(!Subtarget->hasUserSGPRInit16Bug() || IsShader ||(static_cast <bool> (!Subtarget->hasUserSGPRInit16Bug
() || IsShader || Info.getNumPreloadedSGPRs() >= 16) ? void
(0) : __assert_fail ("!Subtarget->hasUserSGPRInit16Bug() || IsShader || Info.getNumPreloadedSGPRs() >= 16"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2268, __extension__
__PRETTY_FUNCTION__))
2268 Info.getNumPreloadedSGPRs() >= 16)(static_cast <bool> (!Subtarget->hasUserSGPRInit16Bug
() || IsShader || Info.getNumPreloadedSGPRs() >= 16) ? void
(0) : __assert_fail ("!Subtarget->hasUserSGPRInit16Bug() || IsShader || Info.getNumPreloadedSGPRs() >= 16"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2268, __extension__
__PRETTY_FUNCTION__))
;
2269}
2270
2271static void reservePrivateMemoryRegs(const TargetMachine &TM,
2272 MachineFunction &MF,
2273 const SIRegisterInfo &TRI,
2274 SIMachineFunctionInfo &Info) {
2275 // Now that we've figured out where the scratch register inputs are, see if
2276 // should reserve the arguments and use them directly.
2277 MachineFrameInfo &MFI = MF.getFrameInfo();
2278 bool HasStackObjects = MFI.hasStackObjects();
2279 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2280
2281 // Record that we know we have non-spill stack objects so we don't need to
2282 // check all stack objects later.
2283 if (HasStackObjects)
2284 Info.setHasNonSpillStackObjects(true);
2285
2286 // Everything live out of a block is spilled with fast regalloc, so it's
2287 // almost certain that spilling will be required.
2288 if (TM.getOptLevel() == CodeGenOpt::None)
2289 HasStackObjects = true;
2290
2291 // For now assume stack access is needed in any callee functions, so we need
2292 // the scratch registers to pass in.
2293 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2294
2295 if (!ST.enableFlatScratch()) {
2296 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2297 // If we have stack objects, we unquestionably need the private buffer
2298 // resource. For the Code Object V2 ABI, this will be the first 4 user
2299 // SGPR inputs. We can reserve those and use them directly.
2300
2301 Register PrivateSegmentBufferReg =
2302 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2303 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2304 } else {
2305 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2306 // We tentatively reserve the last registers (skipping the last registers
2307 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2308 // we'll replace these with the ones immediately after those which were
2309 // really allocated. In the prologue copies will be inserted from the
2310 // argument to these reserved registers.
2311
2312 // Without HSA, relocations are used for the scratch pointer and the
2313 // buffer resource setup is always inserted in the prologue. Scratch wave
2314 // offset is still in an input SGPR.
2315 Info.setScratchRSrcReg(ReservedBufferReg);
2316 }
2317 }
2318
2319 MachineRegisterInfo &MRI = MF.getRegInfo();
2320
2321 // For entry functions we have to set up the stack pointer if we use it,
2322 // whereas non-entry functions get this "for free". This means there is no
2323 // intrinsic advantage to using S32 over S34 in cases where we do not have
2324 // calls but do need a frame pointer (i.e. if we are requested to have one
2325 // because frame pointer elimination is disabled). To keep things simple we
2326 // only ever use S32 as the call ABI stack pointer, and so using it does not
2327 // imply we need a separate frame pointer.
2328 //
2329 // Try to use s32 as the SP, but move it if it would interfere with input
2330 // arguments. This won't work with calls though.
2331 //
2332 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2333 // registers.
2334 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2335 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2336 } else {
2337 assert(AMDGPU::isShader(MF.getFunction().getCallingConv()))(static_cast <bool> (AMDGPU::isShader(MF.getFunction().
getCallingConv())) ? void (0) : __assert_fail ("AMDGPU::isShader(MF.getFunction().getCallingConv())"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2337, __extension__
__PRETTY_FUNCTION__))
;
2338
2339 if (MFI.hasCalls())
2340 report_fatal_error("call in graphics shader with too many input SGPRs");
2341
2342 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2343 if (!MRI.isLiveIn(Reg)) {
2344 Info.setStackPtrOffsetReg(Reg);
2345 break;
2346 }
2347 }
2348
2349 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2350 report_fatal_error("failed to find register for SP");
2351 }
2352
2353 // hasFP should be accurate for entry functions even before the frame is
2354 // finalized, because it does not rely on the known stack size, only
2355 // properties like whether variable sized objects are present.
2356 if (ST.getFrameLowering()->hasFP(MF)) {
2357 Info.setFrameOffsetReg(AMDGPU::SGPR33);
2358 }
2359}
2360
2361bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2362 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2363 return !Info->isEntryFunction();
2364}
2365
2366void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2367
2368}
2369
2370void SITargetLowering::insertCopiesSplitCSR(
2371 MachineBasicBlock *Entry,
2372 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2373 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2374
2375 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2376 if (!IStart)
2377 return;
2378
2379 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2380 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2381 MachineBasicBlock::iterator MBBI = Entry->begin();
2382 for (const MCPhysReg *I = IStart; *I; ++I) {
2383 const TargetRegisterClass *RC = nullptr;
2384 if (AMDGPU::SReg_64RegClass.contains(*I))
2385 RC = &AMDGPU::SGPR_64RegClass;
2386 else if (AMDGPU::SReg_32RegClass.contains(*I))
2387 RC = &AMDGPU::SGPR_32RegClass;
2388 else
2389 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2389)
;
2390
2391 Register NewVR = MRI->createVirtualRegister(RC);
2392 // Create copy from CSR to a virtual register.
2393 Entry->addLiveIn(*I);
2394 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2395 .addReg(*I);
2396
2397 // Insert the copy-back instructions right before the terminator.
2398 for (auto *Exit : Exits)
2399 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2400 TII->get(TargetOpcode::COPY), *I)
2401 .addReg(NewVR);
2402 }
2403}
2404
2405SDValue SITargetLowering::LowerFormalArguments(
2406 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2407 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2408 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2409 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2410
2411 MachineFunction &MF = DAG.getMachineFunction();
2412 const Function &Fn = MF.getFunction();
2413 FunctionType *FType = MF.getFunction().getFunctionType();
2414 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2415
2416 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2417 DiagnosticInfoUnsupported NoGraphicsHSA(
2418 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2419 DAG.getContext()->diagnose(NoGraphicsHSA);
2420 return DAG.getEntryNode();
2421 }
2422
2423 Info->allocateKnownAddressLDSGlobal(Fn);
2424
2425 SmallVector<ISD::InputArg, 16> Splits;
2426 SmallVector<CCValAssign, 16> ArgLocs;
2427 BitVector Skipped(Ins.size());
2428 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2429 *DAG.getContext());
2430
2431 bool IsGraphics = AMDGPU::isGraphics(CallConv);
2432 bool IsKernel = AMDGPU::isKernel(CallConv);
2433 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2434
2435 if (IsGraphics) {
2436 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo
() && !Info->hasLDSKernelId() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() && !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
2437 !Info->hasWorkGroupInfo() && !Info->hasLDSKernelId() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo
() && !Info->hasLDSKernelId() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() && !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
2438 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo
() && !Info->hasLDSKernelId() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() && !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
2439 !Info->hasWorkItemIDZ())(static_cast <bool> (!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo
() && !Info->hasLDSKernelId() && !Info->
hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ()) ? void (0) : __assert_fail ("!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() && !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
;
2440 if (!Subtarget->enableFlatScratch())
2441 assert(!Info->hasFlatScratchInit())(static_cast <bool> (!Info->hasFlatScratchInit()) ? void
(0) : __assert_fail ("!Info->hasFlatScratchInit()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2441, __extension__ __PRETTY_FUNCTION__))
;
2442 if (CallConv != CallingConv::AMDGPU_CS || !Subtarget->hasArchitectedSGPRs())
2443 assert(!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&(static_cast <bool> (!Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
()) ? void (0) : __assert_fail ("!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2444, __extension__
__PRETTY_FUNCTION__))
2444 !Info->hasWorkGroupIDZ())(static_cast <bool> (!Info->hasWorkGroupIDX() &&
!Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ
()) ? void (0) : __assert_fail ("!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && !Info->hasWorkGroupIDZ()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2444, __extension__
__PRETTY_FUNCTION__))
;
2445 }
2446
2447 if (CallConv == CallingConv::AMDGPU_PS) {
2448 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2449
2450 // At least one interpolation mode must be enabled or else the GPU will
2451 // hang.
2452 //
2453 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2454 // set PSInputAddr, the user wants to enable some bits after the compilation
2455 // based on run-time states. Since we can't know what the final PSInputEna
2456 // will look like, so we shouldn't do anything here and the user should take
2457 // responsibility for the correct programming.
2458 //
2459 // Otherwise, the following restrictions apply:
2460 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2461 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2462 // enabled too.
2463 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2464 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2465 CCInfo.AllocateReg(AMDGPU::VGPR0);
2466 CCInfo.AllocateReg(AMDGPU::VGPR1);
2467 Info->markPSInputAllocated(0);
2468 Info->markPSInputEnabled(0);
2469 }
2470 if (Subtarget->isAmdPalOS()) {
2471 // For isAmdPalOS, the user does not enable some bits after compilation
2472 // based on run-time states; the register values being generated here are
2473 // the final ones set in hardware. Therefore we need to apply the
2474 // workaround to PSInputAddr and PSInputEnable together. (The case where
2475 // a bit is set in PSInputAddr but not PSInputEnable is where the
2476 // frontend set up an input arg for a particular interpolation mode, but
2477 // nothing uses that input arg. Really we should have an earlier pass
2478 // that removes such an arg.)
2479 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2480 if ((PsInputBits & 0x7F) == 0 ||
2481 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2482 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
2483 }
2484 } else if (IsKernel) {
2485 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX())(static_cast <bool> (Info->hasWorkGroupIDX() &&
Info->hasWorkItemIDX()) ? void (0) : __assert_fail ("Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2485, __extension__
__PRETTY_FUNCTION__))
;
2486 } else {
2487 Splits.append(Ins.begin(), Ins.end());
2488 }
2489
2490 if (IsEntryFunc) {
2491 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2492 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2493 } else if (!IsGraphics) {
2494 // For the fixed ABI, pass workitem IDs in the last argument register.
2495 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2496 }
2497
2498 if (IsKernel) {
2499 analyzeFormalArgumentsCompute(CCInfo, Ins);
2500 } else {
2501 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2502 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2503 }
2504
2505 SmallVector<SDValue, 16> Chains;
2506
2507 // FIXME: This is the minimum kernel argument alignment. We should improve
2508 // this to the maximum alignment of the arguments.
2509 //
2510 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2511 // kern arg offset.
2512 const Align KernelArgBaseAlign = Align(16);
2513
2514 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2515 const ISD::InputArg &Arg = Ins[i];
2516 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2517 InVals.push_back(DAG.getUNDEF(Arg.VT));
2518 continue;
2519 }
2520
2521 CCValAssign &VA = ArgLocs[ArgIdx++];
2522 MVT VT = VA.getLocVT();
2523
2524 if (IsEntryFunc && VA.isMemLoc()) {
2525 VT = Ins[i].VT;
2526 EVT MemVT = VA.getLocVT();
2527
2528 const uint64_t Offset = VA.getLocMemOffset();
2529 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2530
2531 if (Arg.Flags.isByRef()) {
2532 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2533
2534 const GCNTargetMachine &TM =
2535 static_cast<const GCNTargetMachine &>(getTargetMachine());
2536 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2537 Arg.Flags.getPointerAddrSpace())) {
2538 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2539 Arg.Flags.getPointerAddrSpace());
2540 }
2541
2542 InVals.push_back(Ptr);
2543 continue;
2544 }
2545
2546 SDValue Arg = lowerKernargMemParameter(
2547 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2548 Chains.push_back(Arg.getValue(1));
2549
2550 auto *ParamTy =
2551 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2552 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2553 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2554 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2555 // On SI local pointers are just offsets into LDS, so they are always
2556 // less than 16-bits. On CI and newer they could potentially be
2557 // real pointers, so we can't guarantee their size.
2558 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2559 DAG.getValueType(MVT::i16));
2560 }
2561
2562 InVals.push_back(Arg);
2563 continue;
2564 } else if (!IsEntryFunc && VA.isMemLoc()) {
2565 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2566 InVals.push_back(Val);
2567 if (!Arg.Flags.isByVal())
2568 Chains.push_back(Val.getValue(1));
2569 continue;
2570 }
2571
2572 assert(VA.isRegLoc() && "Parameter must be in a register!")(static_cast <bool> (VA.isRegLoc() && "Parameter must be in a register!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Parameter must be in a register!\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2572, __extension__
__PRETTY_FUNCTION__))
;
2573
2574 Register Reg = VA.getLocReg();
2575 const TargetRegisterClass *RC = nullptr;
2576 if (AMDGPU::VGPR_32RegClass.contains(Reg))
2577 RC = &AMDGPU::VGPR_32RegClass;
2578 else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2579 RC = &AMDGPU::SGPR_32RegClass;
2580 else
2581 llvm_unreachable("Unexpected register class in LowerFormalArguments!")::llvm::llvm_unreachable_internal("Unexpected register class in LowerFormalArguments!"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2581)
;
2582 EVT ValVT = VA.getValVT();
2583
2584 Reg = MF.addLiveIn(Reg, RC);
2585 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2586
2587 if (Arg.Flags.isSRet()) {
2588 // The return object should be reasonably addressable.
2589
2590 // FIXME: This helps when the return is a real sret. If it is a
2591 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2592 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2593 unsigned NumBits
2594 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2595 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2596 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2597 }
2598
2599 // If this is an 8 or 16-bit value, it is really passed promoted
2600 // to 32 bits. Insert an assert[sz]ext to capture this, then
2601 // truncate to the right size.
2602 switch (VA.getLocInfo()) {
2603 case CCValAssign::Full:
2604 break;
2605 case CCValAssign::BCvt:
2606 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2607 break;
2608 case CCValAssign::SExt:
2609 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2610 DAG.getValueType(ValVT));
2611 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2612 break;
2613 case CCValAssign::ZExt:
2614 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2615 DAG.getValueType(ValVT));
2616 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2617 break;
2618 case CCValAssign::AExt:
2619 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2620 break;
2621 default:
2622 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2622)
;
2623 }
2624
2625 InVals.push_back(Val);
2626 }
2627
2628 // Start adding system SGPRs.
2629 if (IsEntryFunc) {
2630 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2631 } else {
2632 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2633 if (!IsGraphics)
2634 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2635 }
2636
2637 auto &ArgUsageInfo =
2638 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2639 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2640
2641 unsigned StackArgSize = CCInfo.getNextStackOffset();
2642 Info->setBytesInStackArgArea(StackArgSize);
2643
2644 return Chains.empty() ? Chain :
2645 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2646}
2647
2648// TODO: If return values can't fit in registers, we should return as many as
2649// possible in registers before passing on stack.
2650bool SITargetLowering::CanLowerReturn(
2651 CallingConv::ID CallConv,
2652 MachineFunction &MF, bool IsVarArg,
2653 const SmallVectorImpl<ISD::OutputArg> &Outs,
2654 LLVMContext &Context) const {
2655 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2656 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2657 // for shaders. Vector types should be explicitly handled by CC.
2658 if (AMDGPU::isEntryFunctionCC(CallConv))
2659 return true;
2660
2661 SmallVector<CCValAssign, 16> RVLocs;
2662 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2663 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2664}
2665
2666SDValue
2667SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2668 bool isVarArg,
2669 const SmallVectorImpl<ISD::OutputArg> &Outs,
2670 const SmallVectorImpl<SDValue> &OutVals,
2671 const SDLoc &DL, SelectionDAG &DAG) const {
2672 MachineFunction &MF = DAG.getMachineFunction();
2673 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2674
2675 if (AMDGPU::isKernel(CallConv)) {
2676 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2677 OutVals, DL, DAG);
2678 }
2679
2680 bool IsShader = AMDGPU::isShader(CallConv);
2681
2682 Info->setIfReturnsVoid(Outs.empty());
2683 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2684
2685 // CCValAssign - represent the assignment of the return value to a location.
2686 SmallVector<CCValAssign, 48> RVLocs;
2687 SmallVector<ISD::OutputArg, 48> Splits;
2688
2689 // CCState - Info about the registers and stack slots.
2690 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2691 *DAG.getContext());
2692
2693 // Analyze outgoing return values.
2694 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2695
2696 SDValue Glue;
2697 SmallVector<SDValue, 48> RetOps;
2698 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2699
2700 // Copy the result values into the output registers.
2701 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2702 ++I, ++RealRVLocIdx) {
2703 CCValAssign &VA = RVLocs[I];
2704 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2704, __extension__
__PRETTY_FUNCTION__))
;
2705 // TODO: Partially return in registers if return values don't fit.
2706 SDValue Arg = OutVals[RealRVLocIdx];
2707
2708 // Copied from other backends.
2709 switch (VA.getLocInfo()) {
2710 case CCValAssign::Full:
2711 break;
2712 case CCValAssign::BCvt:
2713 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2714 break;
2715 case CCValAssign::SExt:
2716 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2717 break;
2718 case CCValAssign::ZExt:
2719 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2720 break;
2721 case CCValAssign::AExt:
2722 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2723 break;
2724 default:
2725 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2725)
;
2726 }
2727
2728 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Glue);
2729 Glue = Chain.getValue(1);
2730 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2731 }
2732
2733 // FIXME: Does sret work properly?
2734 if (!Info->isEntryFunction()) {
2735 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2736 const MCPhysReg *I =
2737 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2738 if (I) {
2739 for (; *I; ++I) {
2740 if (AMDGPU::SReg_64RegClass.contains(*I))
2741 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2742 else if (AMDGPU::SReg_32RegClass.contains(*I))
2743 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2744 else
2745 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2745)
;
2746 }
2747 }
2748 }
2749
2750 // Update chain and glue.
2751 RetOps[0] = Chain;
2752 if (Glue.getNode())
2753 RetOps.push_back(Glue);
2754
2755 unsigned Opc = AMDGPUISD::ENDPGM;
2756 if (!IsWaveEnd)
2757 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_GLUE;
2758 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2759}
2760
2761SDValue SITargetLowering::LowerCallResult(
2762 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
2763 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2764 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2765 SDValue ThisVal) const {
2766 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2767
2768 // Assign locations to each value returned by this call.
2769 SmallVector<CCValAssign, 16> RVLocs;
2770 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2771 *DAG.getContext());
2772 CCInfo.AnalyzeCallResult(Ins, RetCC);
2773
2774 // Copy all of the result registers out of their specified physreg.
2775 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2776 CCValAssign VA = RVLocs[i];
2777 SDValue Val;
2778
2779 if (VA.isRegLoc()) {
2780 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
2781 Chain = Val.getValue(1);
2782 InGlue = Val.getValue(2);
2783 } else if (VA.isMemLoc()) {
2784 report_fatal_error("TODO: return values in memory");
2785 } else
2786 llvm_unreachable("unknown argument location type")::llvm::llvm_unreachable_internal("unknown argument location type"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 2786)
;
2787
2788 switch (VA.getLocInfo()) {
2789 case CCValAssign::Full:
2790 break;
2791 case CCValAssign::BCvt:
2792 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2793 break;
2794 case CCValAssign::ZExt:
2795 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2796 DAG.getValueType(VA.getValVT()));
2797 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2798 break;
2799 case CCValAssign::SExt:
2800 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2801 DAG.getValueType(VA.getValVT()));
2802 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2803 break;
2804 case CCValAssign::AExt:
2805 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2806 break;
2807 default:
2808 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2808)
;
2809 }
2810
2811 InVals.push_back(Val);
2812 }
2813
2814 return Chain;
2815}
2816
2817// Add code to pass special inputs required depending on used features separate
2818// from the explicit user arguments present in the IR.
2819void SITargetLowering::passSpecialInputs(
2820 CallLoweringInfo &CLI,
2821 CCState &CCInfo,
2822 const SIMachineFunctionInfo &Info,
2823 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2824 SmallVectorImpl<SDValue> &MemOpChains,
2825 SDValue Chain) const {
2826 // If we don't have a call site, this was a call inserted by
2827 // legalization. These can never use special inputs.
2828 if (!CLI.CB)
2829 return;
2830
2831 SelectionDAG &DAG = CLI.DAG;
2832 const SDLoc &DL = CLI.DL;
2833 const Function &F = DAG.getMachineFunction().getFunction();
2834
2835 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2836 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2837
2838 const AMDGPUFunctionArgInfo *CalleeArgInfo
2839 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2840 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2841 auto &ArgUsageInfo =
2842 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2843 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2844 }
2845
2846 // TODO: Unify with private memory register handling. This is complicated by
2847 // the fact that at least in kernels, the input argument is not necessarily
2848 // in the same location as the input.
2849 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2850 StringLiteral> ImplicitAttrs[] = {
2851 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2852 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2853 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2854 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2855 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2856 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2857 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"},
2858 {AMDGPUFunctionArgInfo::LDS_KERNEL_ID,"amdgpu-no-lds-kernel-id"},
2859 };
2860
2861 for (auto Attr : ImplicitAttrs) {
2862 const ArgDescriptor *OutgoingArg;
2863 const TargetRegisterClass *ArgRC;
2864 LLT ArgTy;
2865
2866 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2867
2868 // If the callee does not use the attribute value, skip copying the value.
2869 if (CLI.CB->hasFnAttr(Attr.second))
2870 continue;
2871
2872 std::tie(OutgoingArg, ArgRC, ArgTy) =
2873 CalleeArgInfo->getPreloadedValue(InputID);
2874 if (!OutgoingArg)
2875 continue;
2876
2877 const ArgDescriptor *IncomingArg;
2878 const TargetRegisterClass *IncomingArgRC;
2879 LLT Ty;
2880 std::tie(IncomingArg, IncomingArgRC, Ty) =
2881 CallerArgInfo.getPreloadedValue(InputID);
2882 assert(IncomingArgRC == ArgRC)(static_cast <bool> (IncomingArgRC == ArgRC) ? void (0)
: __assert_fail ("IncomingArgRC == ArgRC", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 2882, __extension__ __PRETTY_FUNCTION__))
;
2883
2884 // All special arguments are ints for now.
2885 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2886 SDValue InputReg;
2887
2888 if (IncomingArg) {
2889 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2890 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2891 // The implicit arg ptr is special because it doesn't have a corresponding
2892 // input for kernels, and is computed from the kernarg segment pointer.
2893 InputReg = getImplicitArgPtr(DAG, DL);
2894 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
2895 std::optional<uint32_t> Id =
2896 AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
2897 if (Id.has_value()) {
2898 InputReg = DAG.getConstant(*Id, DL, ArgVT);
2899 } else {
2900 InputReg = DAG.getUNDEF(ArgVT);
2901 }
2902 } else {
2903 // We may have proven the input wasn't needed, although the ABI is
2904 // requiring it. We just need to allocate the register appropriately.
2905 InputReg = DAG.getUNDEF(ArgVT);
2906 }
2907
2908 if (OutgoingArg->isRegister()) {
2909 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2910 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2911 report_fatal_error("failed to allocate implicit input argument");
2912 } else {
2913 unsigned SpecialArgOffset =
2914 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2915 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2916 SpecialArgOffset);
2917 MemOpChains.push_back(ArgStore);
2918 }
2919 }
2920
2921 // Pack workitem IDs into a single register or pass it as is if already
2922 // packed.
2923 const ArgDescriptor *OutgoingArg;
2924 const TargetRegisterClass *ArgRC;
2925 LLT Ty;
2926
2927 std::tie(OutgoingArg, ArgRC, Ty) =
2928 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2929 if (!OutgoingArg)
2930 std::tie(OutgoingArg, ArgRC, Ty) =
2931 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2932 if (!OutgoingArg)
2933 std::tie(OutgoingArg, ArgRC, Ty) =
2934 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2935 if (!OutgoingArg)
2936 return;
2937
2938 const ArgDescriptor *IncomingArgX = std::get<0>(
2939 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2940 const ArgDescriptor *IncomingArgY = std::get<0>(
2941 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2942 const ArgDescriptor *IncomingArgZ = std::get<0>(
2943 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2944
2945 SDValue InputReg;
2946 SDLoc SL;
2947
2948 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2949 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2950 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2951
2952 // If incoming ids are not packed we need to pack them.
2953 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2954 NeedWorkItemIDX) {
2955 if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2956 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2957 } else {
2958 InputReg = DAG.getConstant(0, DL, MVT::i32);
2959 }
2960 }
2961
2962 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2963 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2964 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2965 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2966 DAG.getShiftAmountConstant(10, MVT::i32, SL));
2967 InputReg = InputReg.getNode() ?
2968 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2969 }
2970
2971 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2972 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2973 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2974 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2975 DAG.getShiftAmountConstant(20, MVT::i32, SL));
2976 InputReg = InputReg.getNode() ?
2977 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2978 }
2979
2980 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2981 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2982 // We're in a situation where the outgoing function requires the workitem
2983 // ID, but the calling function does not have it (e.g a graphics function
2984 // calling a C calling convention function). This is illegal, but we need
2985 // to produce something.
2986 InputReg = DAG.getUNDEF(MVT::i32);
2987 } else {
2988 // Workitem ids are already packed, any of present incoming arguments
2989 // will carry all required fields.
2990 ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2991 IncomingArgX ? *IncomingArgX :
2992 IncomingArgY ? *IncomingArgY :
2993 *IncomingArgZ, ~0u);
2994 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2995 }
2996 }
2997
2998 if (OutgoingArg->isRegister()) {
2999 if (InputReg)
3000 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3001
3002 CCInfo.AllocateReg(OutgoingArg->getRegister());
3003 } else {
3004 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3005 if (InputReg) {
3006 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3007 SpecialArgOffset);
3008 MemOpChains.push_back(ArgStore);
3009 }
3010 }
3011}
3012
3013static bool canGuaranteeTCO(CallingConv::ID CC) {
3014 return CC == CallingConv::Fast;
3015}
3016
3017/// Return true if we might ever do TCO for calls with this calling convention.
3018static bool mayTailCallThisCC(CallingConv::ID CC) {
3019 switch (CC) {
3020 case CallingConv::C:
3021 case CallingConv::AMDGPU_Gfx:
3022 return true;
3023 default:
3024 return canGuaranteeTCO(CC);
3025 }
3026}
3027
3028bool SITargetLowering::isEligibleForTailCallOptimization(
3029 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3030 const SmallVectorImpl<ISD::OutputArg> &Outs,
3031 const SmallVectorImpl<SDValue> &OutVals,
3032 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3033 if (!mayTailCallThisCC(CalleeCC))
3034 return false;
3035
3036 // For a divergent call target, we need to do a waterfall loop over the
3037 // possible callees which precludes us from using a simple jump.
3038 if (Callee->isDivergent())
3039 return false;
3040
3041 MachineFunction &MF = DAG.getMachineFunction();
3042 const Function &CallerF = MF.getFunction();
3043 CallingConv::ID CallerCC = CallerF.getCallingConv();
3044 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3045 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3046
3047 // Kernels aren't callable, and don't have a live in return address so it
3048 // doesn't make sense to do a tail call with entry functions.
3049 if (!CallerPreserved)
3050 return false;
3051
3052 bool CCMatch = CallerCC == CalleeCC;
3053
3054 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3055 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3056 return true;
3057 return false;
3058 }
3059
3060 // TODO: Can we handle var args?
3061 if (IsVarArg)
3062 return false;
3063
3064 for (const Argument &Arg : CallerF.args()) {
3065 if (Arg.hasByValAttr())
3066 return false;
3067 }
3068
3069 LLVMContext &Ctx = *DAG.getContext();
3070
3071 // Check that the call results are passed in the same way.
3072 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3073 CCAssignFnForCall(CalleeCC, IsVarArg),
3074 CCAssignFnForCall(CallerCC, IsVarArg)))
3075 return false;
3076
3077 // The callee has to preserve all registers the caller needs to preserve.
3078 if (!CCMatch) {
3079 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3080 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3081 return false;
3082 }
3083
3084 // Nothing more to check if the callee is taking no arguments.
3085 if (Outs.empty())
3086 return true;
3087
3088 SmallVector<CCValAssign, 16> ArgLocs;
3089 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3090
3091 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3092
3093 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3094 // If the stack arguments for this call do not fit into our own save area then
3095 // the call cannot be made tail.
3096 // TODO: Is this really necessary?
3097 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3098 return false;
3099
3100 const MachineRegisterInfo &MRI = MF.getRegInfo();
3101 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3102}
3103
3104bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3105 if (!CI->isTailCall())
3106 return false;
3107
3108 const Function *ParentFn = CI->getParent()->getParent();
3109 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3110 return false;
3111 return true;
3112}
3113
3114// The wave scratch offset register is used as the global base pointer.
3115SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3116 SmallVectorImpl<SDValue> &InVals) const {
3117 SelectionDAG &DAG = CLI.DAG;
3118 const SDLoc &DL = CLI.DL;
3119 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3120 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3121 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3122 SDValue Chain = CLI.Chain;
3123 SDValue Callee = CLI.Callee;
3124 bool &IsTailCall = CLI.IsTailCall;
3125 CallingConv::ID CallConv = CLI.CallConv;
3126 bool IsVarArg = CLI.IsVarArg;
3127 bool IsSibCall = false;
3128 bool IsThisReturn = false;
3129 MachineFunction &MF = DAG.getMachineFunction();
3130
3131 if (Callee.isUndef() || isNullConstant(Callee)) {
3132 if (!CLI.IsTailCall) {
3133 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3134 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3135 }
3136
3137 return Chain;
3138 }
3139
3140 if (IsVarArg) {
3141 return lowerUnhandledCall(CLI, InVals,
3142 "unsupported call to variadic function ");
3143 }
3144
3145 if (!CLI.CB)
3146 report_fatal_error("unsupported libcall legalization");
3147
3148 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3149 return lowerUnhandledCall(CLI, InVals,
3150 "unsupported required tail call to function ");
3151 }
3152
3153 if (AMDGPU::isShader(CallConv)) {
3154 // Note the issue is with the CC of the called function, not of the call
3155 // itself.
3156 return lowerUnhandledCall(CLI, InVals,
3157 "unsupported call to a shader function ");
3158 }
3159
3160 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3161 CallConv != CallingConv::AMDGPU_Gfx) {
3162 // Only allow calls with specific calling conventions.
3163 return lowerUnhandledCall(CLI, InVals,
3164 "unsupported calling convention for call from "
3165 "graphics shader of function ");
3166 }
3167
3168 if (IsTailCall) {
3169 IsTailCall = isEligibleForTailCallOptimization(
3170 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3171 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3172 report_fatal_error("failed to perform tail call elimination on a call "
3173 "site marked musttail");
3174 }
3175
3176 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3177
3178 // A sibling call is one where we're under the usual C ABI and not planning
3179 // to change that but can still do a tail call:
3180 if (!TailCallOpt && IsTailCall)
3181 IsSibCall = true;
3182
3183 if (IsTailCall)
3184 ++NumTailCalls;
3185 }
3186
3187 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3188 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3189 SmallVector<SDValue, 8> MemOpChains;
3190
3191 // Analyze operands of the call, assigning locations to each operand.
3192 SmallVector<CCValAssign, 16> ArgLocs;
3193 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3194 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3195
3196 if (CallConv != CallingConv::AMDGPU_Gfx) {
3197 // With a fixed ABI, allocate fixed registers before user arguments.
3198 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3199 }
3200
3201 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3202
3203 // Get a count of how many bytes are to be pushed on the stack.
3204 unsigned NumBytes = CCInfo.getNextStackOffset();
3205
3206 if (IsSibCall) {
3207 // Since we're not changing the ABI to make this a tail call, the memory
3208 // operands are already available in the caller's incoming argument space.
3209 NumBytes = 0;
3210 }
3211
3212 // FPDiff is the byte offset of the call's argument area from the callee's.
3213 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3214 // by this amount for a tail call. In a sibling call it must be 0 because the
3215 // caller will deallocate the entire stack and the callee still expects its
3216 // arguments to begin at SP+0. Completely unused for non-tail calls.
3217 int32_t FPDiff = 0;
3218 MachineFrameInfo &MFI = MF.getFrameInfo();
3219
3220 // Adjust the stack pointer for the new arguments...
3221 // These operations are automatically eliminated by the prolog/epilog pass
3222 if (!IsSibCall) {
3223 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3224
3225 if (!Subtarget->enableFlatScratch()) {
3226 SmallVector<SDValue, 4> CopyFromChains;
3227
3228 // In the HSA case, this should be an identity copy.
3229 SDValue ScratchRSrcReg
3230 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3231 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3232 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3233 Chain = DAG.getTokenFactor(DL, CopyFromChains);
3234 }
3235 }
3236
3237 MVT PtrVT = MVT::i32;
3238
3239 // Walk the register/memloc assignments, inserting copies/loads.
3240 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3241 CCValAssign &VA = ArgLocs[i];
3242 SDValue Arg = OutVals[i];
3243
3244 // Promote the value if needed.
3245 switch (VA.getLocInfo()) {
3246 case CCValAssign::Full:
3247 break;
3248 case CCValAssign::BCvt:
3249 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3250 break;
3251 case CCValAssign::ZExt:
3252 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3253 break;
3254 case CCValAssign::SExt:
3255 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3256 break;
3257 case CCValAssign::AExt:
3258 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3259 break;
3260 case CCValAssign::FPExt:
3261 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3262 break;
3263 default:
3264 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3264)
;
3265 }
3266
3267 if (VA.isRegLoc()) {
3268 RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
3269 } else {
3270 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3270, __extension__ __PRETTY_FUNCTION__))
;
3271
3272 SDValue DstAddr;
3273 MachinePointerInfo DstInfo;
3274
3275 unsigned LocMemOffset = VA.getLocMemOffset();
3276 int32_t Offset = LocMemOffset;
3277
3278 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3279 MaybeAlign Alignment;
3280
3281 if (IsTailCall) {
3282 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3283 unsigned OpSize = Flags.isByVal() ?
3284 Flags.getByValSize() : VA.getValVT().getStoreSize();
3285
3286 // FIXME: We can have better than the minimum byval required alignment.
3287 Alignment =
3288 Flags.isByVal()
3289 ? Flags.getNonZeroByValAlign()
3290 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3291
3292 Offset = Offset + FPDiff;
3293 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3294
3295 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3296 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3297
3298 // Make sure any stack arguments overlapping with where we're storing
3299 // are loaded before this eventual operation. Otherwise they'll be
3300 // clobbered.
3301
3302 // FIXME: Why is this really necessary? This seems to just result in a
3303 // lot of code to copy the stack and write them back to the same
3304 // locations, which are supposed to be immutable?
3305 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3306 } else {
3307 // Stores to the argument stack area are relative to the stack pointer.
3308 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3309 MVT::i32);
3310 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3311 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3312 Alignment =
3313 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3314 }
3315
3316 if (Outs[i].Flags.isByVal()) {
3317 SDValue SizeNode =
3318 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3319 SDValue Cpy =
3320 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3321 Outs[i].Flags.getNonZeroByValAlign(),
3322 /*isVol = */ false, /*AlwaysInline = */ true,
3323 /*isTailCall = */ false, DstInfo,
3324 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3325
3326 MemOpChains.push_back(Cpy);
3327 } else {
3328 SDValue Store =
3329 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3330 MemOpChains.push_back(Store);
3331 }
3332 }
3333 }
3334
3335 if (!MemOpChains.empty())
3336 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3337
3338 // Build a sequence of copy-to-reg nodes chained together with token chain
3339 // and flag operands which copy the outgoing args into the appropriate regs.
3340 SDValue InGlue;
3341 for (auto &RegToPass : RegsToPass) {
3342 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3343 RegToPass.second, InGlue);
3344 InGlue = Chain.getValue(1);
3345 }
3346
3347
3348 // We don't usually want to end the call-sequence here because we would tidy
3349 // the frame up *after* the call, however in the ABI-changing tail-call case
3350 // we've carefully laid out the parameters so that when sp is reset they'll be
3351 // in the correct location.
3352 if (IsTailCall && !IsSibCall) {
3353 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
3354 InGlue = Chain.getValue(1);
3355 }
3356
3357 std::vector<SDValue> Ops;
3358 Ops.push_back(Chain);
3359 Ops.push_back(Callee);
3360 // Add a redundant copy of the callee global which will not be legalized, as
3361 // we need direct access to the callee later.
3362 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3363 const GlobalValue *GV = GSD->getGlobal();
3364 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3365 } else {
3366 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3367 }
3368
3369 if (IsTailCall) {
3370 // Each tail call may have to adjust the stack by a different amount, so
3371 // this information must travel along with the operation for eventual
3372 // consumption by emitEpilogue.
3373 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3374 }
3375
3376 // Add argument registers to the end of the list so that they are known live
3377 // into the call.
3378 for (auto &RegToPass : RegsToPass) {
3379 Ops.push_back(DAG.getRegister(RegToPass.first,
3380 RegToPass.second.getValueType()));
3381 }
3382
3383 // Add a register mask operand representing the call-preserved registers.
3384
3385 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3386 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3387 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 3387, __extension__
__PRETTY_FUNCTION__))
;
3388 Ops.push_back(DAG.getRegisterMask(Mask));
3389
3390 if (InGlue.getNode())
3391 Ops.push_back(InGlue);
3392
3393 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3394
3395 // If we're doing a tall call, use a TC_RETURN here rather than an
3396 // actual call instruction.
3397 if (IsTailCall) {
3398 MFI.setHasTailCall();
3399 unsigned OPC = CallConv == CallingConv::AMDGPU_Gfx ?
3400 AMDGPUISD::TC_RETURN_GFX : AMDGPUISD::TC_RETURN;
3401 return DAG.getNode(OPC, DL, NodeTys, Ops);
3402 }
3403
3404 // Returns a chain and a flag for retval copy to use.
3405 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3406 Chain = Call.getValue(0);
3407 InGlue = Call.getValue(1);
3408
3409 uint64_t CalleePopBytes = NumBytes;
3410 Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InGlue, DL);
3411 if (!Ins.empty())
3412 InGlue = Chain.getValue(1);
3413
3414 // Handle result values, copying them out of physregs into vregs that we
3415 // return.
3416 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3417 InVals, IsThisReturn,
3418 IsThisReturn ? OutVals[0] : SDValue());
3419}
3420
3421// This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3422// except for applying the wave size scale to the increment amount.
3423SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3424 SDValue Op, SelectionDAG &DAG) const {
3425 const MachineFunction &MF = DAG.getMachineFunction();
3426 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3427
3428 SDLoc dl(Op);
3429 EVT VT = Op.getValueType();
3430 SDValue Tmp1 = Op;
3431 SDValue Tmp2 = Op.getValue(1);
3432 SDValue Tmp3 = Op.getOperand(2);
3433 SDValue Chain = Tmp1.getOperand(0);
3434
3435 Register SPReg = Info->getStackPtrOffsetReg();
3436
3437 // Chain the dynamic stack allocation so that it doesn't modify the stack
3438 // pointer when other instructions are using the stack.
3439 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3440
3441 SDValue Size = Tmp2.getOperand(1);
3442 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3443 Chain = SP.getValue(1);
3444 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3445 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3446 const TargetFrameLowering *TFL = ST.getFrameLowering();
3447 unsigned Opc =
3448 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3449 ISD::ADD : ISD::SUB;
3450
3451 SDValue ScaledSize = DAG.getNode(
3452 ISD::SHL, dl, VT, Size,
3453 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3454
3455 Align StackAlign = TFL->getStackAlign();
3456 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3457 if (Alignment && *Alignment > StackAlign) {
3458 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3459 DAG.getConstant(-(uint64_t)Alignment->value()
3460 << ST.getWavefrontSizeLog2(),
3461 dl, VT));
3462 }
3463
3464 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
3465 Tmp2 = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
3466
3467 return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3468}
3469
3470SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3471 SelectionDAG &DAG) const {
3472 // We only handle constant sizes here to allow non-entry block, static sized
3473 // allocas. A truly dynamic value is more difficult to support because we
3474 // don't know if the size value is uniform or not. If the size isn't uniform,
3475 // we would need to do a wave reduction to get the maximum size to know how
3476 // much to increment the uniform stack pointer.
3477 SDValue Size = Op.getOperand(1);
3478 if (isa<ConstantSDNode>(Size))
3479 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3480
3481 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3482}
3483
3484Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3485 const MachineFunction &MF) const {
3486 Register Reg = StringSwitch<Register>(RegName)
3487 .Case("m0", AMDGPU::M0)
3488 .Case("exec", AMDGPU::EXEC)
3489 .Case("exec_lo", AMDGPU::EXEC_LO)
3490 .Case("exec_hi", AMDGPU::EXEC_HI)
3491 .Case("flat_scratch", AMDGPU::FLAT_SCR)
3492 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3493 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3494 .Default(Register());
3495
3496 if (Reg == AMDGPU::NoRegister) {
3497 report_fatal_error(Twine("invalid register name \""
3498 + StringRef(RegName) + "\"."));
3499
3500 }
3501
3502 if (!Subtarget->hasFlatScrRegister() &&
3503 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3504 report_fatal_error(Twine("invalid register \""
3505 + StringRef(RegName) + "\" for subtarget."));
3506 }
3507
3508 switch (Reg) {
3509 case AMDGPU::M0:
3510 case AMDGPU::EXEC_LO:
3511 case AMDGPU::EXEC_HI:
3512 case AMDGPU::FLAT_SCR_LO:
3513 case AMDGPU::FLAT_SCR_HI:
3514 if (VT.getSizeInBits() == 32)
3515 return Reg;
3516 break;
3517 case AMDGPU::EXEC:
3518 case AMDGPU::FLAT_SCR:
3519 if (VT.getSizeInBits() == 64)
3520 return Reg;
3521 break;
3522 default:
3523 llvm_unreachable("missing register type checking")::llvm::llvm_unreachable_internal("missing register type checking"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 3523)
;
3524 }
3525
3526 report_fatal_error(Twine("invalid type for register \""
3527 + StringRef(RegName) + "\"."));
3528}
3529
3530// If kill is not the last instruction, split the block so kill is always a
3531// proper terminator.
3532MachineBasicBlock *
3533SITargetLowering::splitKillBlock(MachineInstr &MI,
3534 MachineBasicBlock *BB) const {
3535 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3536 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3537 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3538 return SplitBB;
3539}
3540
3541// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3542// \p MI will be the only instruction in the loop body block. Otherwise, it will
3543// be the first instruction in the remainder block.
3544//
3545/// \returns { LoopBody, Remainder }
3546static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3547splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3548 MachineFunction *MF = MBB.getParent();
3549 MachineBasicBlock::iterator I(&MI);
3550
3551 // To insert the loop we need to split the block. Move everything after this
3552 // point to a new block, and insert a new empty block between the two.
3553 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3554 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3555 MachineFunction::iterator MBBI(MBB);
3556 ++MBBI;
3557
3558 MF->insert(MBBI, LoopBB);
3559 MF->insert(MBBI, RemainderBB);
3560
3561 LoopBB->addSuccessor(LoopBB);
3562 LoopBB->addSuccessor(RemainderBB);
3563
3564 // Move the rest of the block into a new block.
3565 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3566
3567 if (InstInLoop) {
3568 auto Next = std::next(I);
3569
3570 // Move instruction to loop body.
3571 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3572
3573 // Move the rest of the block.
3574 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3575 } else {
3576 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3577 }
3578
3579 MBB.addSuccessor(LoopBB);
3580
3581 return std::pair(LoopBB, RemainderBB);
3582}
3583
3584/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3585void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3586 MachineBasicBlock *MBB = MI.getParent();
3587 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3588 auto I = MI.getIterator();
3589 auto E = std::next(I);
3590
3591 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3592 .addImm(0);
3593
3594 MIBundleBuilder Bundler(*MBB, I, E);
3595 finalizeBundle(*MBB, Bundler.begin());
3596}
3597
3598MachineBasicBlock *
3599SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3600 MachineBasicBlock *BB) const {
3601 const DebugLoc &DL = MI.getDebugLoc();
3602
3603 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3604
3605 MachineBasicBlock *LoopBB;
3606 MachineBasicBlock *RemainderBB;
3607 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3608
3609 // Apparently kill flags are only valid if the def is in the same block?
3610 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3611 Src->setIsKill(false);
3612
3613 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3614
3615 MachineBasicBlock::iterator I = LoopBB->end();
3616
3617 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3618 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3619
3620 // Clear TRAP_STS.MEM_VIOL
3621 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3622 .addImm(0)
3623 .addImm(EncodedReg);
3624
3625 bundleInstWithWaitcnt(MI);
3626
3627 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3628
3629 // Load and check TRAP_STS.MEM_VIOL
3630 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3631 .addImm(EncodedReg);
3632
3633 // FIXME: Do we need to use an isel pseudo that may clobber scc?
3634 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3635 .addReg(Reg, RegState::Kill)
3636 .addImm(0);
3637 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3638 .addMBB(LoopBB);
3639
3640 return RemainderBB;
3641}
3642
3643// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3644// wavefront. If the value is uniform and just happens to be in a VGPR, this
3645// will only do one iteration. In the worst case, this will loop 64 times.
3646//
3647// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3648static MachineBasicBlock::iterator
3649emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3650 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3651 const DebugLoc &DL, const MachineOperand &Idx,
3652 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3653 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3654 Register &SGPRIdxReg) {
3655
3656 MachineFunction *MF = OrigBB.getParent();
3657 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3658 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3659 MachineBasicBlock::iterator I = LoopBB.begin();
3660
3661 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3662 Register PhiExec = MRI.createVirtualRegister(BoolRC);
3663 Register NewExec = MRI.createVirtualRegister(BoolRC);
3664 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3665 Register CondReg = MRI.createVirtualRegister(BoolRC);
3666
3667 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3668 .addReg(InitReg)
3669 .addMBB(&OrigBB)
3670 .addReg(ResultReg)
3671 .addMBB(&LoopBB);
3672
3673 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3674 .addReg(InitSaveExecReg)
3675 .addMBB(&OrigBB)
3676 .addReg(NewExec)
3677 .addMBB(&LoopBB);
3678
3679 // Read the next variant <- also loop target.
3680 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3681 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3682
3683 // Compare the just read M0 value to all possible Idx values.
3684 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3685 .addReg(CurrentIdxReg)
3686 .addReg(Idx.getReg(), 0, Idx.getSubReg());
3687
3688 // Update EXEC, save the original EXEC value to VCC.
3689 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3690 : AMDGPU::S_AND_SAVEEXEC_B64),
3691 NewExec)
3692 .addReg(CondReg, RegState::Kill);
3693
3694 MRI.setSimpleHint(NewExec, CondReg);
3695
3696 if (UseGPRIdxMode) {
3697 if (Offset == 0) {
3698 SGPRIdxReg = CurrentIdxReg;
3699 } else {
3700 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3701 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3702 .addReg(CurrentIdxReg, RegState::Kill)
3703 .addImm(Offset);
3704 }
3705 } else {
3706 // Move index from VCC into M0
3707 if (Offset == 0) {
3708 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3709 .addReg(CurrentIdxReg, RegState::Kill);
3710 } else {
3711 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3712 .addReg(CurrentIdxReg, RegState::Kill)
3713 .addImm(Offset);
3714 }
3715 }
3716
3717 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3718 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3719 MachineInstr *InsertPt =
3720 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3721 : AMDGPU::S_XOR_B64_term), Exec)
3722 .addReg(Exec)
3723 .addReg(NewExec);
3724
3725 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3726 // s_cbranch_scc0?
3727
3728 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3729 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3730 .addMBB(&LoopBB);
3731
3732 return InsertPt->getIterator();
3733}
3734
3735// This has slightly sub-optimal regalloc when the source vector is killed by
3736// the read. The register allocator does not understand that the kill is
3737// per-workitem, so is kept alive for the whole loop so we end up not re-using a
3738// subregister from it, using 1 more VGPR than necessary. This was saved when
3739// this was expanded after register allocation.
3740static MachineBasicBlock::iterator
3741loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3742 unsigned InitResultReg, unsigned PhiReg, int Offset,
3743 bool UseGPRIdxMode, Register &SGPRIdxReg) {
3744 MachineFunction *MF = MBB.getParent();
3745 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3746 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3747 MachineRegisterInfo &MRI = MF->getRegInfo();
3748 const DebugLoc &DL = MI.getDebugLoc();
3749 MachineBasicBlock::iterator I(&MI);
3750
3751 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3752 Register DstReg = MI.getOperand(0).getReg();
3753 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3754 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3755 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3756 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3757
3758 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3759
3760 // Save the EXEC mask
3761 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3762 .addReg(Exec);
3763
3764 MachineBasicBlock *LoopBB;
3765 MachineBasicBlock *RemainderBB;
3766 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3767
3768 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3769
3770 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3771 InitResultReg, DstReg, PhiReg, TmpExec,
3772 Offset, UseGPRIdxMode, SGPRIdxReg);
3773
3774 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3775 MachineFunction::iterator MBBI(LoopBB);
3776 ++MBBI;
3777 MF->insert(MBBI, LandingPad);
3778 LoopBB->removeSuccessor(RemainderBB);
3779 LandingPad->addSuccessor(RemainderBB);
3780 LoopBB->addSuccessor(LandingPad);
3781 MachineBasicBlock::iterator First = LandingPad->begin();
3782 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3783 .addReg(SaveExec);
3784
3785 return InsPt;
3786}
3787
3788// Returns subreg index, offset
3789static std::pair<unsigned, int>
3790computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3791 const TargetRegisterClass *SuperRC,
3792 unsigned VecReg,
3793 int Offset) {
3794 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3795
3796 // Skip out of bounds offsets, or else we would end up using an undefined
3797 // register.
3798 if (Offset >= NumElts || Offset < 0)
3799 return std::pair(AMDGPU::sub0, Offset);
3800
3801 return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3802}
3803
3804static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3805 MachineRegisterInfo &MRI, MachineInstr &MI,
3806 int Offset) {
3807 MachineBasicBlock *MBB = MI.getParent();
3808 const DebugLoc &DL = MI.getDebugLoc();
3809 MachineBasicBlock::iterator I(&MI);
3810
3811 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3812
3813 assert(Idx->getReg() != AMDGPU::NoRegister)(static_cast <bool> (Idx->getReg() != AMDGPU::NoRegister
) ? void (0) : __assert_fail ("Idx->getReg() != AMDGPU::NoRegister"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 3813, __extension__
__PRETTY_FUNCTION__))
;
3814
3815 if (Offset == 0) {
3816 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3817 } else {
3818 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3819 .add(*Idx)
3820 .addImm(Offset);
3821 }
3822}
3823
3824static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3825 MachineRegisterInfo &MRI, MachineInstr &MI,
3826 int Offset) {
3827 MachineBasicBlock *MBB = MI.getParent();
3828 const DebugLoc &DL = MI.getDebugLoc();
3829 MachineBasicBlock::iterator I(&MI);
3830
3831 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3832
3833 if (Offset == 0)
3834 return Idx->getReg();
3835
3836 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3837 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3838 .add(*Idx)
3839 .addImm(Offset);
3840 return Tmp;
3841}
3842
3843static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3844 MachineBasicBlock &MBB,
3845 const GCNSubtarget &ST) {
3846 const SIInstrInfo *TII = ST.getInstrInfo();
3847 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3848 MachineFunction *MF = MBB.getParent();
3849 MachineRegisterInfo &MRI = MF->getRegInfo();
3850
3851 Register Dst = MI.getOperand(0).getReg();
3852 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3853 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3854 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3855
3856 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3857 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3858
3859 unsigned SubReg;
3860 std::tie(SubReg, Offset)
3861 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3862
3863 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3864
3865 // Check for a SGPR index.
3866 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3867 MachineBasicBlock::iterator I(&MI);
3868 const DebugLoc &DL = MI.getDebugLoc();
3869
3870 if (UseGPRIdxMode) {
3871 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3872 // to avoid interfering with other uses, so probably requires a new
3873 // optimization pass.
3874 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3875
3876 const MCInstrDesc &GPRIDXDesc =
3877 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3878 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3879 .addReg(SrcReg)
3880 .addReg(Idx)
3881 .addImm(SubReg);
3882 } else {
3883 setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3884
3885 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3886 .addReg(SrcReg, 0, SubReg)
3887 .addReg(SrcReg, RegState::Implicit);
3888 }
3889
3890 MI.eraseFromParent();
3891
3892 return &MBB;
3893 }
3894
3895 // Control flow needs to be inserted if indexing with a VGPR.
3896 const DebugLoc &DL = MI.getDebugLoc();
3897 MachineBasicBlock::iterator I(&MI);
3898
3899 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3900 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3901
3902 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3903
3904 Register SGPRIdxReg;
3905 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3906 UseGPRIdxMode, SGPRIdxReg);
3907
3908 MachineBasicBlock *LoopBB = InsPt->getParent();
3909
3910 if (UseGPRIdxMode) {
3911 const MCInstrDesc &GPRIDXDesc =
3912 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3913
3914 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3915 .addReg(SrcReg)
3916 .addReg(SGPRIdxReg)
3917 .addImm(SubReg);
3918 } else {
3919 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3920 .addReg(SrcReg, 0, SubReg)
3921 .addReg(SrcReg, RegState::Implicit);
3922 }
3923
3924 MI.eraseFromParent();
3925
3926 return LoopBB;
3927}
3928
3929static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3930 MachineBasicBlock &MBB,
3931 const GCNSubtarget &ST) {
3932 const SIInstrInfo *TII = ST.getInstrInfo();
3933 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3934 MachineFunction *MF = MBB.getParent();
3935 MachineRegisterInfo &MRI = MF->getRegInfo();
3936
3937 Register Dst = MI.getOperand(0).getReg();
3938 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3939 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3940 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3941 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3942 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3943 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3944
3945 // This can be an immediate, but will be folded later.
3946 assert(Val->getReg())(static_cast <bool> (Val->getReg()) ? void (0) : __assert_fail
("Val->getReg()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 3946, __extension__ __PRETTY_FUNCTION__))
;
3947
3948 unsigned SubReg;
3949 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3950 SrcVec->getReg(),
3951 Offset);
3952 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3953
3954 if (Idx->getReg() == AMDGPU::NoRegister) {
3955 MachineBasicBlock::iterator I(&MI);
3956 const DebugLoc &DL = MI.getDebugLoc();
3957
3958 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp",
3958, __extension__ __PRETTY_FUNCTION__))
;
3959
3960 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3961 .add(*SrcVec)
3962 .add(*Val)
3963 .addImm(SubReg);
3964
3965 MI.eraseFromParent();
3966 return &MBB;
3967 }
3968
3969 // Check for a SGPR index.
3970 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3971 MachineBasicBlock::iterator I(&MI);
3972 const DebugLoc &DL = MI.getDebugLoc();
3973
3974 if (UseGPRIdxMode) {
3975 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3976
3977 const MCInstrDesc &GPRIDXDesc =
3978 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3979 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3980 .addReg(SrcVec->getReg())
3981 .add(*Val)
3982 .addReg(Idx)
3983 .addImm(SubReg);
3984 } else {
3985 setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3986
3987 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3988 TRI.getRegSizeInBits(*VecRC), 32, false);
3989 BuildMI(MBB, I, DL, MovRelDesc, Dst)
3990 .addReg(SrcVec->getReg())
3991 .add(*Val)
3992 .addImm(SubReg);
3993 }
3994 MI.eraseFromParent();
3995 return &MBB;
3996 }
3997
3998 // Control flow needs to be inserted if indexing with a VGPR.
3999 if (Val->isReg())
4000 MRI.clearKillFlags(Val->getReg());
4001
4002 const DebugLoc &DL = MI.getDebugLoc();
4003
4004 Register PhiReg = MRI.createVirtualRegister(VecRC);
4005
4006 Register SGPRIdxReg;
4007 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4008 UseGPRIdxMode, SGPRIdxReg);
4009 MachineBasicBlock *LoopBB = InsPt->getParent();
4010
4011 if (UseGPRIdxMode) {
4012 const MCInstrDesc &GPRIDXDesc =
4013 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4014
4015 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4016 .addReg(PhiReg)
4017 .add(*Val)
4018 .addReg(SGPRIdxReg)
4019 .addImm(AMDGPU::sub0);
4020 } else {
4021 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4022 TRI.getRegSizeInBits(*VecRC), 32, false);
4023 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4024 .addReg(PhiReg)
4025 .add(*Val)
4026 .addImm(AMDGPU::sub0);
4027 }
4028
4029 MI.eraseFromParent();
4030 return LoopBB;
4031}
4032
4033MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4034 MachineInstr &MI, MachineBasicBlock *BB) const {
4035
4036 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4037 MachineFunction *MF = BB->getParent();
4038 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4039
4040 switch (MI.getOpcode()) {
4041 case AMDGPU::S_UADDO_PSEUDO:
4042 case AMDGPU::S_USUBO_PSEUDO: {
4043 const DebugLoc &DL = MI.getDebugLoc();
4044 MachineOperand &Dest0 = MI.getOperand(0);
4045 MachineOperand &Dest1 = MI.getOperand(1);
4046 MachineOperand &Src0 = MI.getOperand(2);
4047 MachineOperand &Src1 = MI.getOperand(3);
4048
4049 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4050 ? AMDGPU::S_ADD_I32
4051 : AMDGPU::S_SUB_I32;
4052 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4053
4054 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4055 .addImm(1)
4056 .addImm(0);
4057
4058 MI.eraseFromParent();
4059 return BB;
4060 }
4061 case AMDGPU::S_ADD_U64_PSEUDO:
4062 case AMDGPU::S_SUB_U64_PSEUDO: {
4063 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4064 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4065 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4066 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4067 const DebugLoc &DL = MI.getDebugLoc();
4068
4069 MachineOperand &Dest = MI.getOperand(0);
4070 MachineOperand &Src0 = MI.getOperand(1);
4071 MachineOperand &Src1 = MI.getOperand(2);
4072
4073 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4074 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4075
4076 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4077 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4078 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4079 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4080
4081 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4082 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4083 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4084 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4085
4086 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4087
4088 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4089 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4090 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4091 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4092 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4093 .addReg(DestSub0)
4094 .addImm(AMDGPU::sub0)
4095 .addReg(DestSub1)
4096 .addImm(AMDGPU::sub1);
4097 MI.eraseFromParent();
4098 return BB;
4099 }
4100 case AMDGPU::V_ADD_U64_PSEUDO:
4101 case AMDGPU::V_SUB_U64_PSEUDO: {
4102 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4103 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4104 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4105 const DebugLoc &DL = MI.getDebugLoc();
4106
4107 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4108
4109 MachineOperand &Dest = MI.getOperand(0);
4110 MachineOperand &Src0 = MI.getOperand(1);
4111 MachineOperand &Src1 = MI.getOperand(2);
4112
4113 if (IsAdd && ST.hasLshlAddB64()) {
4114 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4115 Dest.getReg())
4116 .add(Src0)
4117 .addImm(0)
4118 .add(Src1);
4119 TII->legalizeOperands(*Add);
4120 MI.eraseFromParent();
4121 return BB;
4122 }
4123
4124 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4125
4126 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4127 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4128
4129 Register CarryReg = MRI.createVirtualRegister(CarryRC);
4130 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4131
4132 const TargetRegisterClass *Src0RC = Src0.isReg()
4133 ? MRI.getRegClass(Src0.getReg())
4134 : &AMDGPU::VReg_64RegClass;
4135 const TargetRegisterClass *Src1RC = Src1.isReg()
4136 ? MRI.getRegClass(Src1.getReg())
4137 : &AMDGPU::VReg_64RegClass;
4138
4139 const TargetRegisterClass *Src0SubRC =
4140 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
4141 const TargetRegisterClass *Src1SubRC =
4142 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
4143
4144 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4145 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4146 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4147 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4148
4149 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4150 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4151 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4152 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4153
4154 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4155 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4156 .addReg(CarryReg, RegState::Define)
4157 .add(SrcReg0Sub0)
4158 .add(SrcReg1Sub0)
4159 .addImm(0); // clamp bit
4160
4161 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4162 MachineInstr *HiHalf =
4163 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4164 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4165 .add(SrcReg0Sub1)
4166 .add(SrcReg1Sub1)
4167 .addReg(CarryReg, RegState::Kill)
4168 .addImm(0); // clamp bit
4169
4170 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4171 .addReg(DestSub0)
4172 .addImm(AMDGPU::sub0)
4173 .addReg(DestSub1)
4174 .addImm(AMDGPU::sub1);
4175 TII->legalizeOperands(*LoHalf);
4176 TII->legalizeOperands(*HiHalf);
4177 MI.eraseFromParent();
4178 return BB;
4179 }
4180 case AMDGPU::S_ADD_CO_PSEUDO:
4181 case AMDGPU::S_SUB_CO_PSEUDO: {
4182 // This pseudo has a chance to be selected
4183 // only from uniform add/subcarry node. All the VGPR operands
4184 // therefore assumed to be splat vectors.
4185 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4186 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4187 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4188 MachineBasicBlock::iterator MII = MI;
4189 const DebugLoc &DL = MI.getDebugLoc();
4190 MachineOperand &Dest = MI.getOperand(0);
4191 MachineOperand &CarryDest = MI.getOperand(1);
4192 MachineOperand &Src0 = MI.getOperand(2);
4193 MachineOperand &Src1 = MI.getOperand(3);
4194 MachineOperand &Src2 = MI.getOperand(4);
4195 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4196 ? AMDGPU::S_ADDC_U32
4197 : AMDGPU::S_SUBB_U32;
4198 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4199 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4200 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4201 .addReg(Src0.getReg());
4202 Src0.setReg(RegOp0);
4203 }
4204 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4205 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4206 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4207 .addReg(Src1.getReg());
4208 Src1.setReg(RegOp1);
4209 }
4210 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4211 if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4212 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4213 .addReg(Src2.getReg());
4214 Src2.setReg(RegOp2);
4215 }
4216
4217 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4218 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4219 assert(WaveSize == 64 || WaveSize == 32)(static_cast <bool> (WaveSize == 64 || WaveSize == 32) ?
void (0) : __assert_fail ("WaveSize == 64 || WaveSize == 32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4219, __extension__
__PRETTY_FUNCTION__))
;
4220
4221 if (WaveSize == 64) {
4222 if (ST.hasScalarCompareEq64()) {
4223 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4224 .addReg(Src2.getReg())
4225 .addImm(0);
4226 } else {
4227 const TargetRegisterClass *SubRC =
4228 TRI->getSubRegisterClass(Src2RC, AMDGPU::sub0);
4229 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4230 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4231 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4232 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4233 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4234
4235 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4236 .add(Src2Sub0)
4237 .add(Src2Sub1);
4238
4239 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4240 .addReg(Src2_32, RegState::Kill)
4241 .addImm(0);
4242 }
4243 } else {
4244 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4245 .addReg(Src2.getReg())
4246 .addImm(0);
4247 }
4248
4249 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4250
4251 unsigned SelOpc =
4252 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4253
4254 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4255 .addImm(-1)
4256 .addImm(0);
4257
4258 MI.eraseFromParent();
4259 return BB;
4260 }
4261 case AMDGPU::SI_INIT_M0: {
4262 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4263 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4264 .add(MI.getOperand(0));
4265 MI.eraseFromParent();
4266 return BB;
4267 }
4268 case AMDGPU::GET_GROUPSTATICSIZE: {
4269 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||(static_cast <bool> (getTargetMachine().getTargetTriple
().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple
().getOS() == Triple::AMDPAL) ? void (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4270, __extension__
__PRETTY_FUNCTION__))
4270 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)(static_cast <bool> (getTargetMachine().getTargetTriple
().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple
().getOS() == Triple::AMDPAL) ? void (0) : __assert_fail ("getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4270, __extension__
__PRETTY_FUNCTION__))
;
4271 DebugLoc DL = MI.getDebugLoc();
4272 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4273 .add(MI.getOperand(0))
4274 .addImm(MFI->getLDSSize());
4275 MI.eraseFromParent();
4276 return BB;
4277 }
4278 case AMDGPU::SI_INDIRECT_SRC_V1:
4279 case AMDGPU::SI_INDIRECT_SRC_V2:
4280 case AMDGPU::SI_INDIRECT_SRC_V4:
4281 case AMDGPU::SI_INDIRECT_SRC_V8:
4282 case AMDGPU::SI_INDIRECT_SRC_V9:
4283 case AMDGPU::SI_INDIRECT_SRC_V10:
4284 case AMDGPU::SI_INDIRECT_SRC_V11:
4285 case AMDGPU::SI_INDIRECT_SRC_V12:
4286 case AMDGPU::SI_INDIRECT_SRC_V16:
4287 case AMDGPU::SI_INDIRECT_SRC_V32:
4288 return emitIndirectSrc(MI, *BB, *getSubtarget());
4289 case AMDGPU::SI_INDIRECT_DST_V1:
4290 case AMDGPU::SI_INDIRECT_DST_V2:
4291 case AMDGPU::SI_INDIRECT_DST_V4:
4292 case AMDGPU::SI_INDIRECT_DST_V8:
4293 case AMDGPU::SI_INDIRECT_DST_V9:
4294 case AMDGPU::SI_INDIRECT_DST_V10:
4295 case AMDGPU::SI_INDIRECT_DST_V11:
4296 case AMDGPU::SI_INDIRECT_DST_V12:
4297 case AMDGPU::SI_INDIRECT_DST_V16:
4298 case AMDGPU::SI_INDIRECT_DST_V32:
4299 return emitIndirectDst(MI, *BB, *getSubtarget());
4300 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4301 case AMDGPU::SI_KILL_I1_PSEUDO:
4302 return splitKillBlock(MI, BB);
4303 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4304 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4305 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4306 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4307
4308 Register Dst = MI.getOperand(0).getReg();
4309 Register Src0 = MI.getOperand(1).getReg();
4310 Register Src1 = MI.getOperand(2).getReg();
4311 const DebugLoc &DL = MI.getDebugLoc();
4312 Register SrcCond = MI.getOperand(3).getReg();
4313
4314 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4315 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4316 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4317 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4318
4319 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4320 .addReg(SrcCond);
4321 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4322 .addImm(0)
4323 .addReg(Src0, 0, AMDGPU::sub0)
4324 .addImm(0)
4325 .addReg(Src1, 0, AMDGPU::sub0)
4326 .addReg(SrcCondCopy);
4327 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4328 .addImm(0)
4329 .addReg(Src0, 0, AMDGPU::sub1)
4330 .addImm(0)
4331 .addReg(Src1, 0, AMDGPU::sub1)
4332 .addReg(SrcCondCopy);
4333
4334 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4335 .addReg(DstLo)
4336 .addImm(AMDGPU::sub0)
4337 .addReg(DstHi)
4338 .addImm(AMDGPU::sub1);
4339 MI.eraseFromParent();
4340 return BB;
4341 }
4342 case AMDGPU::SI_BR_UNDEF: {
4343 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4344 const DebugLoc &DL = MI.getDebugLoc();
4345 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4346 .add(MI.getOperand(0));
4347 Br->getOperand(1).setIsUndef(); // read undef SCC
4348 MI.eraseFromParent();
4349 return BB;
4350 }
4351 case AMDGPU::ADJCALLSTACKUP:
4352 case AMDGPU::ADJCALLSTACKDOWN: {
4353 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4354 MachineInstrBuilder MIB(*MF, &MI);
4355 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4356 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4357 return BB;
4358 }
4359 case AMDGPU::SI_CALL_ISEL: {
4360 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4361 const DebugLoc &DL = MI.getDebugLoc();
4362
4363 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4364
4365 MachineInstrBuilder MIB;
4366 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4367
4368 for (const MachineOperand &MO : MI.operands())
4369 MIB.add(MO);
4370
4371 MIB.cloneMemRefs(MI);
4372 MI.eraseFromParent();
4373 return BB;
4374 }
4375 case AMDGPU::V_ADD_CO_U32_e32:
4376 case AMDGPU::V_SUB_CO_U32_e32:
4377 case AMDGPU::V_SUBREV_CO_U32_e32: {
4378 // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4379 const DebugLoc &DL = MI.getDebugLoc();
4380 unsigned Opc = MI.getOpcode();
4381
4382 bool NeedClampOperand = false;
4383 if (TII->pseudoToMCOpcode(Opc) == -1) {
4384 Opc = AMDGPU::getVOPe64(Opc);
4385 NeedClampOperand = true;
4386 }
4387
4388 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4389 if (TII->isVOP3(*I)) {
4390 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4391 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4392 I.addReg(TRI->getVCC(), RegState::Define);
4393 }
4394 I.add(MI.getOperand(1))
4395 .add(MI.getOperand(2));
4396 if (NeedClampOperand)
4397 I.addImm(0); // clamp bit for e64 encoding
4398
4399 TII->legalizeOperands(*I);
4400
4401 MI.eraseFromParent();
4402 return BB;
4403 }
4404 case AMDGPU::V_ADDC_U32_e32:
4405 case AMDGPU::V_SUBB_U32_e32:
4406 case AMDGPU::V_SUBBREV_U32_e32:
4407 // These instructions have an implicit use of vcc which counts towards the
4408 // constant bus limit.
4409 TII->legalizeOperands(MI);
4410 return BB;
4411 case AMDGPU::DS_GWS_INIT:
4412 case AMDGPU::DS_GWS_SEMA_BR:
4413 case AMDGPU::DS_GWS_BARRIER:
4414 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0);
4415 [[fallthrough]];
4416 case AMDGPU::DS_GWS_SEMA_V:
4417 case AMDGPU::DS_GWS_SEMA_P:
4418 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4419 // A s_waitcnt 0 is required to be the instruction immediately following.
4420 if (getSubtarget()->hasGWSAutoReplay()) {
4421 bundleInstWithWaitcnt(MI);
4422 return BB;
4423 }
4424
4425 return emitGWSMemViolTestLoop(MI, BB);
4426 case AMDGPU::S_SETREG_B32: {
4427 // Try to optimize cases that only set the denormal mode or rounding mode.
4428 //
4429 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4430 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4431 // instead.
4432 //
4433 // FIXME: This could be predicates on the immediate, but tablegen doesn't
4434 // allow you to have a no side effect instruction in the output of a
4435 // sideeffecting pattern.
4436 unsigned ID, Offset, Width;
4437 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4438 if (ID != AMDGPU::Hwreg::ID_MODE)
4439 return BB;
4440
4441 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4442 const unsigned SetMask = WidthMask << Offset;
4443
4444 if (getSubtarget()->hasDenormModeInst()) {
4445 unsigned SetDenormOp = 0;
4446 unsigned SetRoundOp = 0;
4447
4448 // The dedicated instructions can only set the whole denorm or round mode
4449 // at once, not a subset of bits in either.
4450 if (SetMask ==
4451 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4452 // If this fully sets both the round and denorm mode, emit the two
4453 // dedicated instructions for these.
4454 SetRoundOp = AMDGPU::S_ROUND_MODE;
4455 SetDenormOp = AMDGPU::S_DENORM_MODE;
4456 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4457 SetRoundOp = AMDGPU::S_ROUND_MODE;
4458 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4459 SetDenormOp = AMDGPU::S_DENORM_MODE;
4460 }
4461
4462 if (SetRoundOp || SetDenormOp) {
4463 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4464 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4465 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4466 unsigned ImmVal = Def->getOperand(1).getImm();
4467 if (SetRoundOp) {
4468 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4469 .addImm(ImmVal & 0xf);
4470
4471 // If we also have the denorm mode, get just the denorm mode bits.
4472 ImmVal >>= 4;
4473 }
4474
4475 if (SetDenormOp) {
4476 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4477 .addImm(ImmVal & 0xf);
4478 }
4479
4480 MI.eraseFromParent();
4481 return BB;
4482 }
4483 }
4484 }
4485
4486 // If only FP bits are touched, used the no side effects pseudo.
4487 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4488 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4489 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4490
4491 return BB;
4492 }
4493 case AMDGPU::S_INVERSE_BALLOT_U32:
4494 case AMDGPU::S_INVERSE_BALLOT_U64: {
4495 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4496 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4497 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4498 const DebugLoc &DL = MI.getDebugLoc();
4499 const Register DstReg = MI.getOperand(0).getReg();
4500 Register MaskReg = MI.getOperand(1).getReg();
4501
4502 const bool IsVALU = TRI->isVectorRegister(MRI, MaskReg);
4503
4504 if (IsVALU) {
4505 MaskReg = TII->readlaneVGPRToSGPR(MaskReg, MI, MRI);
4506 }
4507
4508 BuildMI(*BB, &MI, DL, TII->get(AMDGPU::COPY), DstReg).addReg(MaskReg);
4509 MI.eraseFromParent();
4510 return BB;
4511 }
4512 default:
4513 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4514 }
4515}
4516
4517bool SITargetLowering::hasAtomicFaddRtnForTy(SDValue &Op) const {
4518 switch (Op.getValue(0).getSimpleValueType().SimpleTy) {
4519 case MVT::f32:
4520 return Subtarget->hasAtomicFaddRtnInsts();
4521 case MVT::v2f16:
4522 case MVT::f64:
4523 return Subtarget->hasGFX90AInsts();
4524 default:
4525 return false;
4526 }
4527}
4528
4529bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4530 // This currently forces unfolding various combinations of fsub into fma with
4531 // free fneg'd operands. As long as we have fast FMA (controlled by
4532 // isFMAFasterThanFMulAndFAdd), we should perform these.
4533
4534 // When fma is quarter rate, for f64 where add / sub are at best half rate,
4535 // most of these combines appear to be cycle neutral but save on instruction
4536 // count / code size.
4537 return true;
4538}
4539
4540bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4541
4542EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4543 EVT VT) const {
4544 if (!VT.isVector()) {
4545 return MVT::i1;
4546 }
4547 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4548}
4549
4550MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4551 // TODO: Should i16 be used always if legal? For now it would force VALU
4552 // shifts.
4553 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4554}
4555
4556LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4557 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4558 ? Ty.changeElementSize(16)
4559 : Ty.changeElementSize(32);
4560}
4561
4562// Answering this is somewhat tricky and depends on the specific device which
4563// have different rates for fma or all f64 operations.
4564//
4565// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4566// regardless of which device (although the number of cycles differs between
4567// devices), so it is always profitable for f64.
4568//
4569// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4570// only on full rate devices. Normally, we should prefer selecting v_mad_f32
4571// which we can always do even without fused FP ops since it returns the same
4572// result as the separate operations and since it is always full
4573// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4574// however does not support denormals, so we do report fma as faster if we have
4575// a fast fma device and require denormals.
4576//
4577bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4578 EVT VT) const {
4579 VT = VT.getScalarType();
4580
4581 switch (VT.getSimpleVT().SimpleTy) {
4582 case MVT::f32: {
4583 // If mad is not available this depends only on if f32 fma is full rate.
4584 if (!Subtarget->hasMadMacF32Insts())
4585 return Subtarget->hasFastFMAF32();
4586
4587 // Otherwise f32 mad is always full rate and returns the same result as
4588 // the separate operations so should be preferred over fma.
4589 // However does not support denormals.
4590 if (hasFP32Denormals(MF))
4591 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4592
4593 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4594 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4595 }
4596 case MVT::f64:
4597 return true;
4598 case MVT::f16:
4599 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4600 default:
4601 break;
4602 }
4603
4604 return false;
4605}
4606
4607bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4608 LLT Ty) const {
4609 switch (Ty.getScalarSizeInBits()) {
4610 case 16:
4611 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4612 case 32:
4613 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4614 case 64:
4615 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4616 default:
4617 break;
4618 }
4619
4620 return false;
4621}
4622
4623bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4624 if (!Ty.isScalar())
4625 return false;
4626
4627 if (Ty.getScalarSizeInBits() == 16)
4628 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4629 if (Ty.getScalarSizeInBits() == 32)
4630 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4631
4632 return false;
4633}
4634
4635bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4636 const SDNode *N) const {
4637 // TODO: Check future ftz flag
4638 // v_mad_f32/v_mac_f32 do not support denormals.
4639 EVT VT = N->getValueType(0);
4640 if (VT == MVT::f32)
4641 return Subtarget->hasMadMacF32Insts() &&
4642 !hasFP32Denormals(DAG.getMachineFunction());
4643 if (VT == MVT::f16) {
4644 return Subtarget->hasMadF16() &&
4645 !hasFP64FP16Denormals(DAG.getMachineFunction());
4646 }
4647
4648 return false;
4649}
4650
4651//===----------------------------------------------------------------------===//
4652// Custom DAG Lowering Operations
4653//===----------------------------------------------------------------------===//
4654
4655// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4656// wider vector type is legal.
4657SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4658 SelectionDAG &DAG) const {
4659 unsigned Opc = Op.getOpcode();
4660 EVT VT = Op.getValueType();
4661 assert(VT == MVT::v4f16 || VT == MVT::v4i16)(static_cast <bool> (VT == MVT::v4f16 || VT == MVT::v4i16
) ? void (0) : __assert_fail ("VT == MVT::v4f16 || VT == MVT::v4i16"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4661, __extension__
__PRETTY_FUNCTION__))
;
4662
4663 SDValue Lo, Hi;
4664 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4665
4666 SDLoc SL(Op);
4667 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4668 Op->getFlags());
4669 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4670 Op->getFlags());
4671
4672 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4673}
4674
4675// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4676// wider vector type is legal.
4677SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4678 SelectionDAG &DAG) const {
4679 unsigned Opc = Op.getOpcode();
4680 EVT VT = Op.getValueType();
4681 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4684, __extension__
__PRETTY_FUNCTION__))
4682 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4684, __extension__
__PRETTY_FUNCTION__))
4683 VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4684, __extension__
__PRETTY_FUNCTION__))
4684 VT == MVT::v32f32)(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4684, __extension__
__PRETTY_FUNCTION__))
;
4685
4686 SDValue Lo0, Hi0;
4687 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4688 SDValue Lo1, Hi1;
4689 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4690
4691 SDLoc SL(Op);
4692
4693 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4694 Op->getFlags());
4695 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4696 Op->getFlags());
4697
4698 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4699}
4700
4701SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4702 SelectionDAG &DAG) const {
4703 unsigned Opc = Op.getOpcode();
4704 EVT VT = Op.getValueType();
4705 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4708, __extension__
__PRETTY_FUNCTION__))
4706 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4708, __extension__
__PRETTY_FUNCTION__))
4707 VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4708, __extension__
__PRETTY_FUNCTION__))
4708 VT == MVT::v32f32)(static_cast <bool> (VT == MVT::v4i16 || VT == MVT::v4f16
|| VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 ||
VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 ||
VT == MVT::v16f32 || VT == MVT::v32f32) ? void (0) : __assert_fail
("VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4708, __extension__
__PRETTY_FUNCTION__))
;
4709
4710 SDValue Lo0, Hi0;
4711 SDValue Op0 = Op.getOperand(0);
4712 std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4713 ? DAG.SplitVectorOperand(Op.getNode(), 0)
4714 : std::pair(Op0, Op0);
4715 SDValue Lo1, Hi1;
4716 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4717 SDValue Lo2, Hi2;
4718 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4719
4720 SDLoc SL(Op);
4721 auto ResVT = DAG.GetSplitDestVTs(VT);
4722
4723 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4724 Op->getFlags());
4725 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4726 Op->getFlags());
4727
4728 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4729}
4730
4731
4732SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4733 switch (Op.getOpcode()) {
4734 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4735 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4736 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4737 case ISD::LOAD: {
4738 SDValue Result = LowerLOAD(Op, DAG);
4739 assert((!Result.getNode() ||(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4741, __extension__
__PRETTY_FUNCTION__))
4740 Result.getNode()->getNumValues() == 2) &&(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4741, __extension__
__PRETTY_FUNCTION__))
4741 "Load should return a value and a chain")(static_cast <bool> ((!Result.getNode() || Result.getNode
()->getNumValues() == 2) && "Load should return a value and a chain"
) ? void (0) : __assert_fail ("(!Result.getNode() || Result.getNode()->getNumValues() == 2) && \"Load should return a value and a chain\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4741, __extension__
__PRETTY_FUNCTION__))
;
4742 return Result;
4743 }
4744
4745 case ISD::FSIN:
4746 case ISD::FCOS:
4747 return LowerTrig(Op, DAG);
4748 case ISD::SELECT: return LowerSELECT(Op, DAG);
4749 case ISD::FDIV: return LowerFDIV(Op, DAG);
4750 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4751 case ISD::STORE: return LowerSTORE(Op, DAG);
4752 case ISD::GlobalAddress: {
4753 MachineFunction &MF = DAG.getMachineFunction();
4754 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4755 return LowerGlobalAddress(MFI, Op, DAG);
4756 }
4757 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4758 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4759 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4760 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4761 case ISD::INSERT_SUBVECTOR:
4762 return lowerINSERT_SUBVECTOR(Op, DAG);
4763 case ISD::INSERT_VECTOR_ELT:
4764 return lowerINSERT_VECTOR_ELT(Op, DAG);
4765 case ISD::EXTRACT_VECTOR_ELT:
4766 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4767 case ISD::VECTOR_SHUFFLE:
4768 return lowerVECTOR_SHUFFLE(Op, DAG);
4769 case ISD::SCALAR_TO_VECTOR:
4770 return lowerSCALAR_TO_VECTOR(Op, DAG);
4771 case ISD::BUILD_VECTOR:
4772 return lowerBUILD_VECTOR(Op, DAG);
4773 case ISD::FP_ROUND:
4774 return lowerFP_ROUND(Op, DAG);
4775 case ISD::FPTRUNC_ROUND: {
4776 unsigned Opc;
4777 SDLoc DL(Op);
4778
4779 if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4780 return SDValue();
4781
4782 // Get the rounding mode from the last operand
4783 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4784 if (RoundMode == (int)RoundingMode::TowardPositive)
4785 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4786 else if (RoundMode == (int)RoundingMode::TowardNegative)
4787 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4788 else
4789 return SDValue();
4790
4791 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4792 }
4793 case ISD::TRAP:
4794 return lowerTRAP(Op, DAG);
4795 case ISD::DEBUGTRAP:
4796 return lowerDEBUGTRAP(Op, DAG);
4797 case ISD::FABS:
4798 case ISD::FNEG:
4799 case ISD::FCANONICALIZE:
4800 case ISD::BSWAP:
4801 return splitUnaryVectorOp(Op, DAG);
4802 case ISD::FMINNUM:
4803 case ISD::FMAXNUM:
4804 return lowerFMINNUM_FMAXNUM(Op, DAG);
4805 case ISD::FMA:
4806 return splitTernaryVectorOp(Op, DAG);
4807 case ISD::FP_TO_SINT:
4808 case ISD::FP_TO_UINT:
4809 return LowerFP_TO_INT(Op, DAG);
4810 case ISD::SHL:
4811 case ISD::SRA:
4812 case ISD::SRL:
4813 case ISD::ADD:
4814 case ISD::SUB:
4815 case ISD::MUL:
4816 case ISD::SMIN:
4817 case ISD::SMAX:
4818 case ISD::UMIN:
4819 case ISD::UMAX:
4820 case ISD::FADD:
4821 case ISD::FMUL:
4822 case ISD::FMINNUM_IEEE:
4823 case ISD::FMAXNUM_IEEE:
4824 case ISD::UADDSAT:
4825 case ISD::USUBSAT:
4826 case ISD::SADDSAT:
4827 case ISD::SSUBSAT:
4828 return splitBinaryVectorOp(Op, DAG);
4829 case ISD::SMULO:
4830 case ISD::UMULO:
4831 return lowerXMULO(Op, DAG);
4832 case ISD::SMUL_LOHI:
4833 case ISD::UMUL_LOHI:
4834 return lowerXMUL_LOHI(Op, DAG);
4835 case ISD::DYNAMIC_STACKALLOC:
4836 return LowerDYNAMIC_STACKALLOC(Op, DAG);
4837 }
4838 return SDValue();
4839}
4840
4841// Used for D16: Casts the result of an instruction into the right vector,
4842// packs values if loads return unpacked values.
4843static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4844 const SDLoc &DL,
4845 SelectionDAG &DAG, bool Unpacked) {
4846 if (!LoadVT.isVector())
4847 return Result;
4848
4849 // Cast back to the original packed type or to a larger type that is a
4850 // multiple of 32 bit for D16. Widening the return type is a required for
4851 // legalization.
4852 EVT FittingLoadVT = LoadVT;
4853 if ((LoadVT.getVectorNumElements() % 2) == 1) {
4854 FittingLoadVT =
4855 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4856 LoadVT.getVectorNumElements() + 1);
4857 }
4858
4859 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4860 // Truncate to v2i16/v4i16.
4861 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4862
4863 // Workaround legalizer not scalarizing truncate after vector op
4864 // legalization but not creating intermediate vector trunc.
4865 SmallVector<SDValue, 4> Elts;
4866 DAG.ExtractVectorElements(Result, Elts);
4867 for (SDValue &Elt : Elts)
4868 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4869
4870 // Pad illegal v1i16/v3fi6 to v4i16
4871 if ((LoadVT.getVectorNumElements() % 2) == 1)
4872 Elts.push_back(DAG.getUNDEF(MVT::i16));
4873
4874 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4875
4876 // Bitcast to original type (v2f16/v4f16).
4877 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4878 }
4879
4880 // Cast back to the original packed type.
4881 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4882}
4883
4884SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4885 MemSDNode *M,
4886 SelectionDAG &DAG,
4887 ArrayRef<SDValue> Ops,
4888 bool IsIntrinsic) const {
4889 SDLoc DL(M);
4890
4891 bool Unpacked = Subtarget->hasUnpackedD16VMem();
4892 EVT LoadVT = M->getValueType(0);
4893
4894 EVT EquivLoadVT = LoadVT;
4895 if (LoadVT.isVector()) {
4896 if (Unpacked) {
4897 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4898 LoadVT.getVectorNumElements());
4899 } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4900 // Widen v3f16 to legal type
4901 EquivLoadVT =
4902 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4903 LoadVT.getVectorNumElements() + 1);
4904 }
4905 }
4906
4907 // Change from v4f16/v2f16 to EquivLoadVT.
4908 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4909
4910 SDValue Load
4911 = DAG.getMemIntrinsicNode(
4912 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4913 VTList, Ops, M->getMemoryVT(),
4914 M->getMemOperand());
4915
4916 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4917
4918 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4919}
4920
4921SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4922 SelectionDAG &DAG,
4923 ArrayRef<SDValue> Ops) const {
4924 SDLoc DL(M);
4925 EVT LoadVT = M->getValueType(0);
4926 EVT EltType = LoadVT.getScalarType();
4927 EVT IntVT = LoadVT.changeTypeToInteger();
4928
4929 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4930
4931 assert(M->getNumValues() == 2 || M->getNumValues() == 3)(static_cast <bool> (M->getNumValues() == 2 || M->
getNumValues() == 3) ? void (0) : __assert_fail ("M->getNumValues() == 2 || M->getNumValues() == 3"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 4931, __extension__
__PRETTY_FUNCTION__))
;
4932 bool IsTFE = M->getNumValues() == 3;
4933
4934 unsigned Opc;
4935 if (IsFormat) {
4936 Opc = IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_TFE
4937 : AMDGPUISD::BUFFER_LOAD_FORMAT;
4938 } else {
4939 // TODO: Support non-format TFE loads.
4940 if (IsTFE)
4941 return SDValue();
4942 Opc = AMDGPUISD::BUFFER_LOAD;
4943 }
4944
4945 if (IsD16) {
4946 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4947 }
4948
4949 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4950 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4951 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4952
4953 if (isTypeLegal(LoadVT)) {
4954 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4955 M->getMemOperand(), DAG);
4956 }
4957
4958 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4959 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4960 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4961 M->getMemOperand(), DAG);
4962 return DAG.getMergeValues(
4963 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4964 DL);
4965}
4966
4967static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4968 SDNode *N, SelectionDAG &DAG) {
4969 EVT VT = N->getValueType(0);
4970 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4971 unsigned CondCode = CD->getZExtValue();
4972 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4973 return DAG.getUNDEF(VT);
4974
4975 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4976
4977 SDValue LHS = N->getOperand(1);
4978 SDValue RHS = N->getOperand(2);
4979
4980 SDLoc DL(N);
4981
4982 EVT CmpVT = LHS.getValueType();
4983 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4984 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4985 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4986 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4987 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4988 }
4989
4990 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4991
4992 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4993 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4994
4995 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4996 DAG.getCondCode(CCOpcode));
4997 if (VT.bitsEq(CCVT))
4998 return SetCC;
4999 return DAG.getZExtOrTrunc(SetCC, DL, VT);
5000}
5001
5002static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
5003 SDNode *N, SelectionDAG &DAG) {
5004 EVT VT = N->getValueType(0);
5005 const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
5006
5007 unsigned CondCode = CD->getZExtValue();
5008 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
5009 return DAG.getUNDEF(VT);
5010
5011 SDValue Src0 = N->getOperand(1);
5012 SDValue Src1 = N->getOperand(2);
5013 EVT CmpVT = Src0.getValueType();
5014 SDLoc SL(N);
5015
5016 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
5017 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5018 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5019 }
5020
5021 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5022 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5023 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5024 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5025 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5026 Src1, DAG.getCondCode(CCOpcode));
5027 if (VT.bitsEq(CCVT))
5028 return SetCC;
5029 return DAG.getZExtOrTrunc(SetCC, SL, VT);
5030}
5031
5032static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5033 SelectionDAG &DAG) {
5034 EVT VT = N->getValueType(0);
5035 SDValue Src = N->getOperand(1);
5036 SDLoc SL(N);
5037
5038 if (Src.getOpcode() == ISD::SETCC) {
5039 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5040 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5041 Src.getOperand(1), Src.getOperand(2));
5042 }
5043 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5044 // (ballot 0) -> 0
5045 if (Arg->isZero())
5046 return DAG.getConstant(0, SL, VT);
5047
5048 // (ballot 1) -> EXEC/EXEC_LO
5049 if (Arg->isOne()) {
5050 Register Exec;
5051 if (VT.getScalarSizeInBits() == 32)
5052 Exec = AMDGPU::EXEC_LO;
5053 else if (VT.getScalarSizeInBits() == 64)
5054 Exec = AMDGPU::EXEC;
5055 else
5056 return SDValue();
5057
5058 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5059 }
5060 }
5061
5062 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5063 // ISD::SETNE)
5064 return DAG.getNode(
5065 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5066 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5067}
5068
5069void SITargetLowering::ReplaceNodeResults(SDNode *N,
5070 SmallVectorImpl<SDValue> &Results,
5071 SelectionDAG &DAG) const {
5072 switch (N->getOpcode()) {
5073 case ISD::INSERT_VECTOR_ELT: {
5074 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5075 Results.push_back(Res);
5076 return;
5077 }
5078 case ISD::EXTRACT_VECTOR_ELT: {
5079 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5080 Results.push_back(Res);
5081 return;
5082 }
5083 case ISD::INTRINSIC_WO_CHAIN: {
5084 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5085 switch (IID) {
5086 case Intrinsic::amdgcn_cvt_pkrtz: {
5087 SDValue Src0 = N->getOperand(1);
5088 SDValue Src1 = N->getOperand(2);
5089 SDLoc SL(N);
5090 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5091 Src0, Src1);
5092 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5093 return;
5094 }
5095 case Intrinsic::amdgcn_cvt_pknorm_i16:
5096 case Intrinsic::amdgcn_cvt_pknorm_u16:
5097 case Intrinsic::amdgcn_cvt_pk_i16:
5098 case Intrinsic::amdgcn_cvt_pk_u16: {
5099 SDValue Src0 = N->getOperand(1);
5100 SDValue Src1 = N->getOperand(2);
5101 SDLoc SL(N);
5102 unsigned Opcode;
5103
5104 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5105 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5106 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5107 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5108 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5109 Opcode = AMDGPUISD::CVT_PK_I16_I32;
5110 else
5111 Opcode = AMDGPUISD::CVT_PK_U16_U32;
5112
5113 EVT VT = N->getValueType(0);
5114 if (isTypeLegal(VT))
5115 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5116 else {
5117 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5118 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5119 }
5120 return;
5121 }
5122 }
5123 break;
5124 }
5125 case ISD::INTRINSIC_W_CHAIN: {
5126 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5127 if (Res.getOpcode() == ISD::MERGE_VALUES) {
5128 // FIXME: Hacky
5129 for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5130 Results.push_back(Res.getOperand(I));
5131 }
5132 } else {
5133 Results.push_back(Res);
5134 Results.push_back(Res.getValue(1));
5135 }
5136 return;
5137 }
5138
5139 break;
5140 }
5141 case ISD::SELECT: {
5142 SDLoc SL(N);
5143 EVT VT = N->getValueType(0);
5144 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5145 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5146 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5147
5148 EVT SelectVT = NewVT;
5149 if (NewVT.bitsLT(MVT::i32)) {
5150 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5151 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5152 SelectVT = MVT::i32;
5153 }
5154
5155 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5156 N->getOperand(0), LHS, RHS);
5157
5158 if (NewVT != SelectVT)
5159 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5160 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5161 return;
5162 }
5163 case ISD::FNEG: {
5164 if (N->getValueType(0) != MVT::v2f16)
5165 break;
5166
5167 SDLoc SL(N);
5168 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5169
5170 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5171 BC,
5172 DAG.getConstant(0x80008000, SL, MVT::i32));
5173 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5174 return;
5175 }
5176 case ISD::FABS: {
5177 if (N->getValueType(0) != MVT::v2f16)
5178 break;
5179
5180 SDLoc SL(N);
5181 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5182
5183 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5184 BC,
5185 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5186 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5187 return;
5188 }
5189 default:
5190 break;
5191 }
5192}
5193
5194/// Helper function for LowerBRCOND
5195static SDNode *findUser(SDValue Value, unsigned Opcode) {
5196
5197 SDNode *Parent = Value.getNode();
5198 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5199 I != E; ++I) {
5200
5201 if (I.getUse().get() != Value)
5202 continue;
5203
5204 if (I->getOpcode() == Opcode)
5205 return *I;
5206 }
5207 return nullptr;
5208}
5209
5210unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5211 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5212 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5213 case Intrinsic::amdgcn_if:
5214 return AMDGPUISD::IF;
5215 case Intrinsic::amdgcn_else:
5216 return AMDGPUISD::ELSE;
5217 case Intrinsic::amdgcn_loop:
5218 return AMDGPUISD::LOOP;
5219 case Intrinsic::amdgcn_end_cf:
5220 llvm_unreachable("should not occur")::llvm::llvm_unreachable_internal("should not occur", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5220)
;
5221 default:
5222 return 0;
5223 }
5224 }
5225
5226 // break, if_break, else_break are all only used as inputs to loop, not
5227 // directly as branch conditions.
5228 return 0;
5229}
5230
5231bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5232 const Triple &TT = getTargetMachine().getTargetTriple();
5233 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5234 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5235 AMDGPU::shouldEmitConstantsToTextSection(TT);
5236}
5237
5238bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5239 // FIXME: Either avoid relying on address space here or change the default
5240 // address space for functions to avoid the explicit check.
5241 return (GV->getValueType()->isFunctionTy() ||
5242 !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5243 !shouldEmitFixup(GV) &&
5244 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5245}
5246
5247bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5248 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5249}
5250
5251bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5252 if (!GV->hasExternalLinkage())
5253 return true;
5254
5255 const auto OS = getTargetMachine().getTargetTriple().getOS();
5256 return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5257}
5258
5259/// This transforms the control flow intrinsics to get the branch destination as
5260/// last parameter, also switches branch target with BR if the need arise
5261SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5262 SelectionDAG &DAG) const {
5263 SDLoc DL(BRCOND);
5264
5265 SDNode *Intr = BRCOND.getOperand(1).getNode();
5266 SDValue Target = BRCOND.getOperand(2);
5267 SDNode *BR = nullptr;
5268 SDNode *SetCC = nullptr;
5269
5270 if (Intr->getOpcode() == ISD::SETCC) {
5271 // As long as we negate the condition everything is fine
5272 SetCC = Intr;
5273 Intr = SetCC->getOperand(0).getNode();
5274
5275 } else {
5276 // Get the target from BR if we don't negate the condition
5277 BR = findUser(BRCOND, ISD::BR);
5278 assert(BR && "brcond missing unconditional branch user")(static_cast <bool> (BR && "brcond missing unconditional branch user"
) ? void (0) : __assert_fail ("BR && \"brcond missing unconditional branch user\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5278, __extension__
__PRETTY_FUNCTION__))
;
5279 Target = BR->getOperand(1);
5280 }
5281
5282 unsigned CFNode = isCFIntrinsic(Intr);
5283 if (CFNode == 0) {
5284 // This is a uniform branch so we don't need to legalize.
5285 return BRCOND;
5286 }
5287
5288 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5289 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5290
5291 assert(!SetCC ||(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5294, __extension__
__PRETTY_FUNCTION__))
5292 (SetCC->getConstantOperandVal(1) == 1 &&(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5294, __extension__
__PRETTY_FUNCTION__))
5293 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5294, __extension__
__PRETTY_FUNCTION__))
5294 ISD::SETNE))(static_cast <bool> (!SetCC || (SetCC->getConstantOperandVal
(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand
(2).getNode())->get() == ISD::SETNE)) ? void (0) : __assert_fail
("!SetCC || (SetCC->getConstantOperandVal(1) == 1 && cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == ISD::SETNE)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5294, __extension__
__PRETTY_FUNCTION__))
;
5295
5296 // operands of the new intrinsic call
5297 SmallVector<SDValue, 4> Ops;
5298 if (HaveChain)
5299 Ops.push_back(BRCOND.getOperand(0));
5300
5301 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
5302 Ops.push_back(Target);
5303
5304 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5305
5306 // build the new intrinsic call
5307 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5308
5309 if (!HaveChain) {
5310 SDValue Ops[] = {
5311 SDValue(Result, 0),
5312 BRCOND.getOperand(0)
5313 };
5314
5315 Result = DAG.getMergeValues(Ops, DL).getNode();
5316 }
5317
5318 if (BR) {
5319 // Give the branch instruction our target
5320 SDValue Ops[] = {
5321 BR->getOperand(0),
5322 BRCOND.getOperand(2)
5323 };
5324 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5325 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5326 }
5327
5328 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5329
5330 // Copy the intrinsic results to registers
5331 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5332 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5333 if (!CopyToReg)
5334 continue;
5335
5336 Chain = DAG.getCopyToReg(
5337 Chain, DL,
5338 CopyToReg->getOperand(1),
5339 SDValue(Result, i - 1),
5340 SDValue());
5341
5342 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5343 }
5344
5345 // Remove the old intrinsic from the chain
5346 DAG.ReplaceAllUsesOfValueWith(
5347 SDValue(Intr, Intr->getNumValues() - 1),
5348 Intr->getOperand(0));
5349
5350 return Chain;
5351}
5352
5353SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5354 SelectionDAG &DAG) const {
5355 MVT VT = Op.getSimpleValueType();
5356 SDLoc DL(Op);
5357 // Checking the depth
5358 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5359 return DAG.getConstant(0, DL, VT);
5360
5361 MachineFunction &MF = DAG.getMachineFunction();
5362 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5363 // Check for kernel and shader functions
5364 if (Info->isEntryFunction())
5365 return DAG.getConstant(0, DL, VT);
5366
5367 MachineFrameInfo &MFI = MF.getFrameInfo();
5368 // There is a call to @llvm.returnaddress in this function
5369 MFI.setReturnAddressIsTaken(true);
5370
5371 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5372 // Get the return address reg and mark it as an implicit live-in
5373 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5374
5375 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5376}
5377
5378SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5379 SDValue Op,
5380 const SDLoc &DL,
5381 EVT VT) const {
5382 return Op.getValueType().bitsLE(VT) ?
5383 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5384 DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5385 DAG.getTargetConstant(0, DL, MVT::i32));
5386}
5387
5388SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5389 assert(Op.getValueType() == MVT::f16 &&(static_cast <bool> (Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type")
? void (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5390, __extension__
__PRETTY_FUNCTION__))
5390 "Do not know how to custom lower FP_ROUND for non-f16 type")(static_cast <bool> (Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type")
? void (0) : __assert_fail ("Op.getValueType() == MVT::f16 && \"Do not know how to custom lower FP_ROUND for non-f16 type\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5390, __extension__
__PRETTY_FUNCTION__))
;
5391
5392 SDValue Src = Op.getOperand(0);
5393 EVT SrcVT = Src.getValueType();
5394 if (SrcVT != MVT::f64)
5395 return Op;
5396
5397 SDLoc DL(Op);
5398
5399 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5400 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5401 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5402}
5403
5404SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5405 SelectionDAG &DAG) const {
5406 EVT VT = Op.getValueType();
5407 const MachineFunction &MF = DAG.getMachineFunction();
5408 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5409 bool IsIEEEMode = Info->getMode().IEEE;
5410
5411 // FIXME: Assert during selection that this is only selected for
5412 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5413 // mode functions, but this happens to be OK since it's only done in cases
5414 // where there is known no sNaN.
5415 if (IsIEEEMode)
5416 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5417
5418 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16)
5419 return splitBinaryVectorOp(Op, DAG);
5420 return Op;
5421}
5422
5423SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5424 EVT VT = Op.getValueType();
5425 SDLoc SL(Op);
5426 SDValue LHS = Op.getOperand(0);
5427 SDValue RHS = Op.getOperand(1);
5428 bool isSigned = Op.getOpcode() == ISD::SMULO;
5429
5430 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5431 const APInt &C = RHSC->getAPIntValue();
5432 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5433 if (C.isPowerOf2()) {
5434 // smulo(x, signed_min) is same as umulo(x, signed_min).
5435 bool UseArithShift = isSigned && !C.isMinSignedValue();
5436 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5437 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5438 SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5439 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5440 SL, VT, Result, ShiftAmt),
5441 LHS, ISD::SETNE);
5442 return DAG.getMergeValues({ Result, Overflow }, SL);
5443 }
5444 }
5445
5446 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5447 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5448 SL, VT, LHS, RHS);
5449
5450 SDValue Sign = isSigned
5451 ? DAG.getNode(ISD::SRA, SL, VT, Result,
5452 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5453 : DAG.getConstant(0, SL, VT);
5454 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5455
5456 return DAG.getMergeValues({ Result, Overflow }, SL);
5457}
5458
5459SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5460 if (Op->isDivergent()) {
5461 // Select to V_MAD_[IU]64_[IU]32.
5462 return Op;
5463 }
5464 if (Subtarget->hasSMulHi()) {
5465 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5466 return SDValue();
5467 }
5468 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5469 // calculate the high part, so we might as well do the whole thing with
5470 // V_MAD_[IU]64_[IU]32.
5471 return Op;
5472}
5473
5474SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5475 if (!Subtarget->isTrapHandlerEnabled() ||
5476 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5477 return lowerTrapEndpgm(Op, DAG);
5478
5479 const Module *M = DAG.getMachineFunction().getFunction().getParent();
5480 unsigned CodeObjectVersion = AMDGPU::getCodeObjectVersion(*M);
5481 if (CodeObjectVersion <= AMDGPU::AMDHSA_COV3)
5482 return lowerTrapHsaQueuePtr(Op, DAG);
5483
5484 return Subtarget->supportsGetDoorbellID() ? lowerTrapHsa(Op, DAG) :
5485 lowerTrapHsaQueuePtr(Op, DAG);
5486}
5487
5488SDValue SITargetLowering::lowerTrapEndpgm(
5489 SDValue Op, SelectionDAG &DAG) const {
5490 SDLoc SL(Op);
5491 SDValue Chain = Op.getOperand(0);
5492 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5493}
5494
5495SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5496 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5497 MachineFunction &MF = DAG.getMachineFunction();
5498 uint64_t Offset = getImplicitParameterOffset(MF, Param);
5499 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5500 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5501 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5502 MachineMemOperand::MODereferenceable |
5503 MachineMemOperand::MOInvariant);
5504}
5505
5506SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5507 SDValue Op, SelectionDAG &DAG) const {
5508 SDLoc SL(Op);
5509 SDValue Chain = Op.getOperand(0);
5510
5511 SDValue QueuePtr;
5512 // For code object version 5, QueuePtr is passed through implicit kernarg.
5513 const Module *M = DAG.getMachineFunction().getFunction().getParent();
5514 if (AMDGPU::getCodeObjectVersion(*M) >= AMDGPU::AMDHSA_COV5) {
5515 QueuePtr =
5516 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5517 } else {
5518 MachineFunction &MF = DAG.getMachineFunction();
5519 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5520 Register UserSGPR = Info->getQueuePtrUserSGPR();
5521
5522 if (UserSGPR == AMDGPU::NoRegister) {
5523 // We probably are in a function incorrectly marked with
5524 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5525 // trap, so just use a null pointer.
5526 QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5527 } else {
5528 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5529 MVT::i64);
5530 }
5531 }
5532
5533 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5534 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5535 QueuePtr, SDValue());
5536
5537 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5538 SDValue Ops[] = {
5539 ToReg,
5540 DAG.getTargetConstant(TrapID, SL, MVT::i16),
5541 SGPR01,
5542 ToReg.getValue(1)
5543 };
5544 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5545}
5546
5547SDValue SITargetLowering::lowerTrapHsa(
5548 SDValue Op, SelectionDAG &DAG) const {
5549 SDLoc SL(Op);
5550 SDValue Chain = Op.getOperand(0);
5551
5552 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5553 SDValue Ops[] = {
5554 Chain,
5555 DAG.getTargetConstant(TrapID, SL, MVT::i16)
5556 };
5557 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5558}
5559
5560SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5561 SDLoc SL(Op);
5562 SDValue Chain = Op.getOperand(0);
5563 MachineFunction &MF = DAG.getMachineFunction();
5564
5565 if (!Subtarget->isTrapHandlerEnabled() ||
5566 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5567 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5568 "debugtrap handler not supported",
5569 Op.getDebugLoc(),
5570 DS_Warning);
5571 LLVMContext &Ctx = MF.getFunction().getContext();
5572 Ctx.diagnose(NoTrap);
5573 return Chain;
5574 }
5575
5576 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5577 SDValue Ops[] = {
5578 Chain,
5579 DAG.getTargetConstant(TrapID, SL, MVT::i16)
5580 };
5581 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5582}
5583
5584SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5585 SelectionDAG &DAG) const {
5586 if (Subtarget->hasApertureRegs()) {
5587 const unsigned ApertureRegNo = (AS == AMDGPUAS::LOCAL_ADDRESS)
5588 ? AMDGPU::SRC_SHARED_BASE
5589 : AMDGPU::SRC_PRIVATE_BASE;
5590 // Note: this feature (register) is broken. When used as a 32-bit operand,
5591 // it returns a wrong value (all zeroes?). The real value is in the upper 32
5592 // bits.
5593 //
5594 // To work around the issue, directly emit a 64 bit mov from this register
5595 // then extract the high bits. Note that this shouldn't even result in a
5596 // shift being emitted and simply become a pair of registers (e.g.):
5597 // s_mov_b64 s[6:7], src_shared_base
5598 // v_mov_b32_e32 v1, s7
5599 //
5600 // FIXME: It would be more natural to emit a CopyFromReg here, but then copy
5601 // coalescing would kick in and it would think it's okay to use the "HI"
5602 // subregister directly (instead of extracting the HI 32 bits) which is an
5603 // artificial (unusable) register.
5604 // Register TableGen definitions would need an overhaul to get rid of the
5605 // artificial "HI" aperture registers and prevent this kind of issue from
5606 // happening.
5607 SDNode *Mov = DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64,
5608 DAG.getRegister(ApertureRegNo, MVT::i64));
5609 return DAG.getNode(
5610 ISD::TRUNCATE, DL, MVT::i32,
5611 DAG.getNode(ISD::SRL, DL, MVT::i64,
5612 {SDValue(Mov, 0), DAG.getConstant(32, DL, MVT::i64)}));
5613 }
5614
5615 // For code object version 5, private_base and shared_base are passed through
5616 // implicit kernargs.
5617 const Module *M = DAG.getMachineFunction().getFunction().getParent();
5618 if (AMDGPU::getCodeObjectVersion(*M) >= AMDGPU::AMDHSA_COV5) {
5619 ImplicitParameter Param =
5620 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5621 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5622 }
5623
5624 MachineFunction &MF = DAG.getMachineFunction();
5625 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5626 Register UserSGPR = Info->getQueuePtrUserSGPR();
5627 if (UserSGPR == AMDGPU::NoRegister) {
5628 // We probably are in a function incorrectly marked with
5629 // amdgpu-no-queue-ptr. This is undefined.
5630 return DAG.getUNDEF(MVT::i32);
5631 }
5632
5633 SDValue QueuePtr = CreateLiveInRegister(
5634 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5635
5636 // Offset into amd_queue_t for group_segment_aperture_base_hi /
5637 // private_segment_aperture_base_hi.
5638 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5639
5640 SDValue Ptr =
5641 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5642
5643 // TODO: Use custom target PseudoSourceValue.
5644 // TODO: We should use the value from the IR intrinsic call, but it might not
5645 // be available and how do we get it?
5646 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5647 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5648 commonAlignment(Align(64), StructOffset),
5649 MachineMemOperand::MODereferenceable |
5650 MachineMemOperand::MOInvariant);
5651}
5652
5653/// Return true if the value is a known valid address, such that a null check is
5654/// not necessary.
5655static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5656 const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5657 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5658 isa<BasicBlockSDNode>(Val))
5659 return true;
5660
5661 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5662 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5663
5664 // TODO: Search through arithmetic, handle arguments and loads
5665 // marked nonnull.
5666 return false;
5667}
5668
5669SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5670 SelectionDAG &DAG) const {
5671 SDLoc SL(Op);
5672 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5673
5674 SDValue Src = ASC->getOperand(0);
5675 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5676 unsigned SrcAS = ASC->getSrcAddressSpace();
5677
5678 const AMDGPUTargetMachine &TM =
5679 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5680
5681 // flat -> local/private
5682 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5683 unsigned DestAS = ASC->getDestAddressSpace();
5684
5685 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5686 DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5687 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5688
5689 if (isKnownNonNull(Src, DAG, TM, SrcAS))
5690 return Ptr;
5691
5692 unsigned NullVal = TM.getNullPointerValue(DestAS);
5693 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5694 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5695
5696 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5697 SegmentNullPtr);
5698 }
5699 }
5700
5701 // local/private -> flat
5702 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5703 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5704 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5705
5706 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5707 SDValue CvtPtr =
5708 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5709 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5710
5711 if (isKnownNonNull(Src, DAG, TM, SrcAS))
5712 return CvtPtr;
5713
5714 unsigned NullVal = TM.getNullPointerValue(SrcAS);
5715 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5716
5717 SDValue NonNull
5718 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5719
5720 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5721 FlatNullPtr);
5722 }
5723 }
5724
5725 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5726 Op.getValueType() == MVT::i64) {
5727 const SIMachineFunctionInfo *Info =
5728 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5729 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5730 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5731 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5732 }
5733
5734 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5735 Src.getValueType() == MVT::i64)
5736 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5737
5738 // global <-> flat are no-ops and never emitted.
5739
5740 const MachineFunction &MF = DAG.getMachineFunction();
5741 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5742 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5743 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5744
5745 return DAG.getUNDEF(ASC->getValueType(0));
5746}
5747
5748// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5749// the small vector and inserting them into the big vector. That is better than
5750// the default expansion of doing it via a stack slot. Even though the use of
5751// the stack slot would be optimized away afterwards, the stack slot itself
5752// remains.
5753SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5754 SelectionDAG &DAG) const {
5755 SDValue Vec = Op.getOperand(0);
5756 SDValue Ins = Op.getOperand(1);
5757 SDValue Idx = Op.getOperand(2);
5758 EVT VecVT = Vec.getValueType();
5759 EVT InsVT = Ins.getValueType();
5760 EVT EltVT = VecVT.getVectorElementType();
5761 unsigned InsNumElts = InsVT.getVectorNumElements();
5762 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5763 SDLoc SL(Op);
5764
5765 if (EltVT.getScalarSizeInBits() == 16 && IdxVal % 2 == 0) {
5766 // Insert 32-bit registers at a time.
5767 assert(InsNumElts % 2 == 0 && "expect legal vector types")(static_cast <bool> (InsNumElts % 2 == 0 && "expect legal vector types"
) ? void (0) : __assert_fail ("InsNumElts % 2 == 0 && \"expect legal vector types\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5767, __extension__
__PRETTY_FUNCTION__))
;
5768
5769 unsigned VecNumElts = VecVT.getVectorNumElements();
5770 EVT NewVecVT =
5771 EVT::getVectorVT(*DAG.getContext(), MVT::i32, VecNumElts / 2);
5772 EVT NewInsVT = InsNumElts == 2 ? MVT::i32
5773 : EVT::getVectorVT(*DAG.getContext(),
5774 MVT::i32, InsNumElts / 2);
5775
5776 Vec = DAG.getNode(ISD::BITCAST, SL, NewVecVT, Vec);
5777 Ins = DAG.getNode(ISD::BITCAST, SL, NewInsVT, Ins);
5778
5779 for (unsigned I = 0; I != InsNumElts / 2; ++I) {
5780 SDValue Elt;
5781 if (InsNumElts == 2) {
5782 Elt = Ins;
5783 } else {
5784 Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Ins,
5785 DAG.getConstant(I, SL, MVT::i32));
5786 }
5787 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NewVecVT, Vec, Elt,
5788 DAG.getConstant(IdxVal / 2 + I, SL, MVT::i32));
5789 }
5790
5791 return DAG.getNode(ISD::BITCAST, SL, VecVT, Vec);
5792 }
5793
5794 for (unsigned I = 0; I != InsNumElts; ++I) {
5795 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5796 DAG.getConstant(I, SL, MVT::i32));
5797 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5798 DAG.getConstant(IdxVal + I, SL, MVT::i32));
5799 }
5800 return Vec;
5801}
5802
5803SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5804 SelectionDAG &DAG) const {
5805 SDValue Vec = Op.getOperand(0);
5806 SDValue InsVal = Op.getOperand(1);
5807 SDValue Idx = Op.getOperand(2);
5808 EVT VecVT = Vec.getValueType();
5809 EVT EltVT = VecVT.getVectorElementType();
5810 unsigned VecSize = VecVT.getSizeInBits();
5811 unsigned EltSize = EltVT.getSizeInBits();
5812 SDLoc SL(Op);
5813
5814 // Specially handle the case of v4i16 with static indexing.
5815 unsigned NumElts = VecVT.getVectorNumElements();
5816 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5817 if (NumElts == 4 && EltSize == 16 && KIdx) {
5818 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5819
5820 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5821 DAG.getConstant(0, SL, MVT::i32));
5822 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5823 DAG.getConstant(1, SL, MVT::i32));
5824
5825 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5826 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5827
5828 unsigned Idx = KIdx->getZExtValue();
5829 bool InsertLo = Idx < 2;
5830 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5831 InsertLo ? LoVec : HiVec,
5832 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5833 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5834
5835 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5836
5837 SDValue Concat = InsertLo ?
5838 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5839 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5840
5841 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5842 }
5843
5844 // Static indexing does not lower to stack access, and hence there is no need
5845 // for special custom lowering to avoid stack access.
5846 if (isa<ConstantSDNode>(Idx))
5847 return SDValue();
5848
5849 // Avoid stack access for dynamic indexing by custom lowering to
5850 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5851
5852 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits")(static_cast <bool> (VecSize <= 64 && "Expected target vector size to be <= 64 bits"
) ? void (0) : __assert_fail ("VecSize <= 64 && \"Expected target vector size to be <= 64 bits\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 5852, __extension__
__PRETTY_FUNCTION__))
;
5853
5854 MVT IntVT = MVT::getIntegerVT(VecSize);
5855
5856 // Convert vector index to bit-index and get the required bit mask.
5857 assert(isPowerOf2_32(EltSize))(static_cast <bool> (isPowerOf2_32(EltSize)) ? void (0)
: __assert_fail ("isPowerOf2_32(EltSize)", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5857, __extension__ __PRETTY_FUNCTION__))
;
5858 const auto EltMask = maskTrailingOnes<uint64_t>(EltSize);
5859 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5860 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5861 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5862 DAG.getConstant(EltMask, SL, IntVT), ScaledIdx);
5863
5864 // 1. Create a congruent vector with the target value in each element.
5865 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5866 DAG.getSplatBuildVector(VecVT, SL, InsVal));
5867
5868 // 2. Mask off all other indicies except the required index within (1).
5869 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5870
5871 // 3. Mask off the required index within the target vector.
5872 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5873 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5874 DAG.getNOT(SL, BFM, IntVT), BCVec);
5875
5876 // 4. Get (2) and (3) ORed into the target vector.
5877 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5878
5879 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5880}
5881
5882SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5883 SelectionDAG &DAG) const {
5884 SDLoc SL(Op);
5885
5886 EVT ResultVT = Op.getValueType();
5887 SDValue Vec = Op.getOperand(0);
5888 SDValue Idx = Op.getOperand(1);
5889 EVT VecVT = Vec.getValueType();
5890 unsigned VecSize = VecVT.getSizeInBits();
5891 EVT EltVT = VecVT.getVectorElementType();
5892
5893 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5894
5895 // Make sure we do any optimizations that will make it easier to fold
5896 // source modifiers before obscuring it with bit operations.
5897
5898 // XXX - Why doesn't this get called when vector_shuffle is expanded?
5899 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5900 return Combined;
5901
5902 if (VecSize == 128 || VecSize == 256) {
5903 SDValue Lo, Hi;
5904 EVT LoVT, HiVT;
5905 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5906
5907 if (VecSize == 128) {
5908 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5909 Lo = DAG.getBitcast(LoVT,
5910 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5911 DAG.getConstant(0, SL, MVT::i32)));
5912 Hi = DAG.getBitcast(HiVT,
5913 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5914 DAG.getConstant(1, SL, MVT::i32)));
5915 } else {
5916 assert(VecSize == 256)(static_cast <bool> (VecSize == 256) ? void (0) : __assert_fail
("VecSize == 256", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5916, __extension__ __PRETTY_FUNCTION__))
;
5917
5918 SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
5919 SDValue Parts[4];
5920 for (unsigned P = 0; P < 4; ++P) {
5921 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5922 DAG.getConstant(P, SL, MVT::i32));
5923 }
5924
5925 Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
5926 Parts[0], Parts[1]));
5927 Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
5928 Parts[2], Parts[3]));
5929 }
5930
5931 EVT IdxVT = Idx.getValueType();
5932 unsigned NElem = VecVT.getVectorNumElements();
5933 assert(isPowerOf2_32(NElem))(static_cast <bool> (isPowerOf2_32(NElem)) ? void (0) :
__assert_fail ("isPowerOf2_32(NElem)", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5933, __extension__ __PRETTY_FUNCTION__))
;
5934 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5935 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5936 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5938 }
5939
5940 assert(VecSize <= 64)(static_cast <bool> (VecSize <= 64) ? void (0) : __assert_fail
("VecSize <= 64", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5940, __extension__ __PRETTY_FUNCTION__))
;
5941
5942 MVT IntVT = MVT::getIntegerVT(VecSize);
5943
5944 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
5945 SDValue VecBC = peekThroughBitcasts(Vec);
5946 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5947 SDValue Src = VecBC.getOperand(0);
5948 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
5949 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
5950 }
5951
5952 unsigned EltSize = EltVT.getSizeInBits();
5953 assert(isPowerOf2_32(EltSize))(static_cast <bool> (isPowerOf2_32(EltSize)) ? void (0)
: __assert_fail ("isPowerOf2_32(EltSize)", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5953, __extension__ __PRETTY_FUNCTION__))
;
5954
5955 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5956
5957 // Convert vector index to bit-index (* EltSize)
5958 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5959
5960 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5961 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5962
5963 if (ResultVT == MVT::f16) {
5964 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5965 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5966 }
5967
5968 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5969}
5970
5971static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5972 assert(Elt % 2 == 0)(static_cast <bool> (Elt % 2 == 0) ? void (0) : __assert_fail
("Elt % 2 == 0", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 5972, __extension__ __PRETTY_FUNCTION__))
;
5973 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5974}
5975
5976SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5977 SelectionDAG &DAG) const {
5978 SDLoc SL(Op);
5979 EVT ResultVT = Op.getValueType();
5980 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5981
5982 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5983 EVT EltVT = PackVT.getVectorElementType();
5984 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5985
5986 // vector_shuffle <0,1,6,7> lhs, rhs
5987 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5988 //
5989 // vector_shuffle <6,7,2,3> lhs, rhs
5990 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5991 //
5992 // vector_shuffle <6,7,0,1> lhs, rhs
5993 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5994
5995 // Avoid scalarizing when both halves are reading from consecutive elements.
5996 SmallVector<SDValue, 4> Pieces;
5997 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5998 if (elementPairIsContiguous(SVN->getMask(), I)) {
5999 const int Idx = SVN->getMaskElt(I);
6000 int VecIdx = Idx < SrcNumElts ? 0 : 1;
6001 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
6002 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
6003 PackVT, SVN->getOperand(VecIdx),
6004 DAG.getConstant(EltIdx, SL, MVT::i32));
6005 Pieces.push_back(SubVec);
6006 } else {
6007 const int Idx0 = SVN->getMaskElt(I);
6008 const int Idx1 = SVN->getMaskElt(I + 1);
6009 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
6010 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
6011 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
6012 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
6013
6014 SDValue Vec0 = SVN->getOperand(VecIdx0);
6015 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6016 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
6017
6018 SDValue Vec1 = SVN->getOperand(VecIdx1);
6019 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6020 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
6021 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
6022 }
6023 }
6024
6025 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
6026}
6027
6028SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6029 SelectionDAG &DAG) const {
6030 SDValue SVal = Op.getOperand(0);
6031 EVT ResultVT = Op.getValueType();
6032 EVT SValVT = SVal.getValueType();
6033 SDValue UndefVal = DAG.getUNDEF(SValVT);
6034 SDLoc SL(Op);
6035
6036 SmallVector<SDValue, 8> VElts;
6037 VElts.push_back(SVal);
6038 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
6039 VElts.push_back(UndefVal);
6040
6041 return DAG.getBuildVector(ResultVT, SL, VElts);
6042}
6043
6044SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
6045 SelectionDAG &DAG) const {
6046 SDLoc SL(Op);
6047 EVT VT = Op.getValueType();
6048
6049 if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
6050 VT == MVT::v8i16 || VT == MVT::v8f16) {
6051 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
6052 VT.getVectorNumElements() / 2);
6053 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
6054
6055 // Turn into pair of packed build_vectors.
6056 // TODO: Special case for constants that can be materialized with s_mov_b64.
6057 SmallVector<SDValue, 4> LoOps, HiOps;
6058 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
6059 LoOps.push_back(Op.getOperand(I));
6060 HiOps.push_back(Op.getOperand(I + E));
6061 }
6062 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
6063 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
6064
6065 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
6066 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
6067
6068 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
6069 { CastLo, CastHi });
6070 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
6071 }
6072
6073 if (VT == MVT::v16i16 || VT == MVT::v16f16) {
6074 EVT QuarterVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
6075 VT.getVectorNumElements() / 4);
6076 MVT QuarterIntVT = MVT::getIntegerVT(QuarterVT.getSizeInBits());
6077
6078 SmallVector<SDValue, 4> Parts[4];
6079 for (unsigned I = 0, E = VT.getVectorNumElements() / 4; I != E; ++I) {
6080 for (unsigned P = 0; P < 4; ++P)
6081 Parts[P].push_back(Op.getOperand(I + P * E));
6082 }
6083 SDValue Casts[4];
6084 for (unsigned P = 0; P < 4; ++P) {
6085 SDValue Vec = DAG.getBuildVector(QuarterVT, SL, Parts[P]);
6086 Casts[P] = DAG.getNode(ISD::BITCAST, SL, QuarterIntVT, Vec);
6087 }
6088
6089 SDValue Blend =
6090 DAG.getBuildVector(MVT::getVectorVT(QuarterIntVT, 4), SL, Casts);
6091 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
6092 }
6093
6094 assert(VT == MVT::v2f16 || VT == MVT::v2i16)(static_cast <bool> (VT == MVT::v2f16 || VT == MVT::v2i16
) ? void (0) : __assert_fail ("VT == MVT::v2f16 || VT == MVT::v2i16"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6094, __extension__
__PRETTY_FUNCTION__))
;
6095 assert(!Subtarget->hasVOP3PInsts() && "this should be legal")(static_cast <bool> (!Subtarget->hasVOP3PInsts() &&
"this should be legal") ? void (0) : __assert_fail ("!Subtarget->hasVOP3PInsts() && \"this should be legal\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6095, __extension__
__PRETTY_FUNCTION__))
;
6096
6097 SDValue Lo = Op.getOperand(0);
6098 SDValue Hi = Op.getOperand(1);
6099
6100 // Avoid adding defined bits with the zero_extend.
6101 if (Hi.isUndef()) {
6102 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6103 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
6104 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
6105 }
6106
6107 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
6108 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
6109
6110 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
6111 DAG.getConstant(16, SL, MVT::i32));
6112 if (Lo.isUndef())
6113 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
6114
6115 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6116 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
6117
6118 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
6119 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
6120}
6121
6122bool
6123SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6124 // We can fold offsets for anything that doesn't require a GOT relocation.
6125 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
6126 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6127 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6128 !shouldEmitGOTReloc(GA->getGlobal());
6129}
6130
6131static SDValue
6132buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
6133 const SDLoc &DL, int64_t Offset, EVT PtrVT,
6134 unsigned GAFlags = SIInstrInfo::MO_NONE) {
6135 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!")(static_cast <bool> (isInt<32>(Offset + 4) &&
"32-bit offset is expected!") ? void (0) : __assert_fail ("isInt<32>(Offset + 4) && \"32-bit offset is expected!\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6135, __extension__
__PRETTY_FUNCTION__))
;
6136 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6137 // lowered to the following code sequence:
6138 //
6139 // For constant address space:
6140 // s_getpc_b64 s[0:1]
6141 // s_add_u32 s0, s0, $symbol
6142 // s_addc_u32 s1, s1, 0
6143 //
6144 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
6145 // a fixup or relocation is emitted to replace $symbol with a literal
6146 // constant, which is a pc-relative offset from the encoding of the $symbol
6147 // operand to the global variable.
6148 //
6149 // For global address space:
6150 // s_getpc_b64 s[0:1]
6151 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6152 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6153 //
6154 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
6155 // fixups or relocations are emitted to replace $symbol@*@lo and
6156 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6157 // which is a 64-bit pc-relative offset from the encoding of the $symbol
6158 // operand to the global variable.
6159 //
6160 // What we want here is an offset from the value returned by s_getpc
6161 // (which is the address of the s_add_u32 instruction) to the global
6162 // variable, but since the encoding of $symbol starts 4 bytes after the start
6163 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6164 // small. This requires us to add 4 to the global variable offset in order to
6165 // compute the correct address. Similarly for the s_addc_u32 instruction, the
6166 // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6167 // instruction.
6168 SDValue PtrLo =
6169 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6170 SDValue PtrHi;
6171 if (GAFlags == SIInstrInfo::MO_NONE) {
6172 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6173 } else {
6174 PtrHi =
6175 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6176 }
6177 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6178}
6179
6180SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6181 SDValue Op,
6182 SelectionDAG &DAG) const {
6183 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6184 SDLoc DL(GSD);
6185 EVT PtrVT = Op.getValueType();
6186
6187 const GlobalValue *GV = GSD->getGlobal();
6188 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6189 shouldUseLDSConstAddress(GV)) ||
6190 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6191 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6192 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6193 GV->hasExternalLinkage()) {
6194 Type *Ty = GV->getValueType();
6195 // HIP uses an unsized array `extern __shared__ T s[]` or similar
6196 // zero-sized type in other languages to declare the dynamic shared
6197 // memory which size is not known at the compile time. They will be
6198 // allocated by the runtime and placed directly after the static
6199 // allocated ones. They all share the same offset.
6200 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6201 assert(PtrVT == MVT::i32 && "32-bit pointer is expected.")(static_cast <bool> (PtrVT == MVT::i32 && "32-bit pointer is expected."
) ? void (0) : __assert_fail ("PtrVT == MVT::i32 && \"32-bit pointer is expected.\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6201, __extension__
__PRETTY_FUNCTION__))
;
6202 // Adjust alignment for that dynamic shared memory array.
6203 Function &F = DAG.getMachineFunction().getFunction();
6204 MFI->setDynLDSAlign(F, *cast<GlobalVariable>(GV));
6205 return SDValue(
6206 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6207 }
6208 }
6209 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6210 }
6211
6212 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6213 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6214 SIInstrInfo::MO_ABS32_LO);
6215 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6216 }
6217
6218 if (shouldEmitFixup(GV))
6219 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6220 else if (shouldEmitPCReloc(GV))
6221 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6222 SIInstrInfo::MO_REL32);
6223
6224 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6225 SIInstrInfo::MO_GOTPCREL32);
6226
6227 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6228 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6229 const DataLayout &DataLayout = DAG.getDataLayout();
6230 Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6231 MachinePointerInfo PtrInfo
6232 = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6233
6234 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6235 MachineMemOperand::MODereferenceable |
6236 MachineMemOperand::MOInvariant);
6237}
6238
6239SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6240 const SDLoc &DL, SDValue V) const {
6241 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6242 // the destination register.
6243 //
6244 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6245 // so we will end up with redundant moves to m0.
6246 //
6247 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6248
6249 // A Null SDValue creates a glue result.
6250 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6251 V, Chain);
6252 return SDValue(M0, 0);
6253}
6254
6255SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6256 SDValue Op,
6257 MVT VT,
6258 unsigned Offset) const {
6259 SDLoc SL(Op);
6260 SDValue Param = lowerKernargMemParameter(
6261 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6262 // The local size values will have the hi 16-bits as zero.
6263 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6264 DAG.getValueType(VT));
6265}
6266
6267static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6268 EVT VT) {
6269 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6270 "non-hsa intrinsic with hsa target",
6271 DL.getDebugLoc());
6272 DAG.getContext()->diagnose(BadIntrin);
6273 return DAG.getUNDEF(VT);
6274}
6275
6276static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6277 EVT VT) {
6278 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6279 "intrinsic not supported on subtarget",
6280 DL.getDebugLoc());
6281 DAG.getContext()->diagnose(BadIntrin);
6282 return DAG.getUNDEF(VT);
6283}
6284
6285static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6286 ArrayRef<SDValue> Elts) {
6287 assert(!Elts.empty())(static_cast <bool> (!Elts.empty()) ? void (0) : __assert_fail
("!Elts.empty()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6287, __extension__ __PRETTY_FUNCTION__))
;
6288 MVT Type;
6289 unsigned NumElts = Elts.size();
6290
6291 if (NumElts <= 12) {
6292 Type = MVT::getVectorVT(MVT::f32, NumElts);
6293 } else {
6294 assert(Elts.size() <= 16)(static_cast <bool> (Elts.size() <= 16) ? void (0) :
__assert_fail ("Elts.size() <= 16", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 6294, __extension__ __PRETTY_FUNCTION__))
;
6295 Type = MVT::v16f32;
6296 NumElts = 16;
6297 }
6298
6299 SmallVector<SDValue, 16> VecElts(NumElts);
6300 for (unsigned i = 0; i < Elts.size(); ++i) {
6301 SDValue Elt = Elts[i];
6302 if (Elt.getValueType() != MVT::f32)
6303 Elt = DAG.getBitcast(MVT::f32, Elt);
6304 VecElts[i] = Elt;
6305 }
6306 for (unsigned i = Elts.size(); i < NumElts; ++i)
6307 VecElts[i] = DAG.getUNDEF(MVT::f32);
6308
6309 if (NumElts == 1)
6310 return VecElts[0];
6311 return DAG.getBuildVector(Type, DL, VecElts);
6312}
6313
6314static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6315 SDValue Src, int ExtraElts) {
6316 EVT SrcVT = Src.getValueType();
6317
6318 SmallVector<SDValue, 8> Elts;
6319
6320 if (SrcVT.isVector())
6321 DAG.ExtractVectorElements(Src, Elts);
6322 else
6323 Elts.push_back(Src);
6324
6325 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6326 while (ExtraElts--)
6327 Elts.push_back(Undef);
6328
6329 return DAG.getBuildVector(CastVT, DL, Elts);
6330}
6331
6332// Re-construct the required return value for a image load intrinsic.
6333// This is more complicated due to the optional use TexFailCtrl which means the required
6334// return type is an aggregate
6335static SDValue constructRetValue(SelectionDAG &DAG,
6336 MachineSDNode *Result,
6337 ArrayRef<EVT> ResultTypes,
6338 bool IsTexFail, bool Unpacked, bool IsD16,
6339 int DMaskPop, int NumVDataDwords,
6340 const SDLoc &DL) {
6341 // Determine the required return type. This is the same regardless of IsTexFail flag
6342 EVT ReqRetVT = ResultTypes[0];
6343 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6344 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6345 ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6346
6347 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6348 DMaskPop : (DMaskPop + 1) / 2;
6349
6350 MVT DataDwordVT = NumDataDwords == 1 ?
6351 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6352
6353 MVT MaskPopVT = MaskPopDwords == 1 ?
6354 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6355
6356 SDValue Data(Result, 0);
6357 SDValue TexFail;
6358
6359 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6360 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6361 if (MaskPopVT.isVector()) {
6362 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6363 SDValue(Result, 0), ZeroIdx);
6364 } else {
6365 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6366 SDValue(Result, 0), ZeroIdx);
6367 }
6368 }
6369
6370 if (DataDwordVT.isVector())
6371 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6372 NumDataDwords - MaskPopDwords);
6373
6374 if (IsD16)
6375 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6376
6377 EVT LegalReqRetVT = ReqRetVT;
6378 if (!ReqRetVT.isVector()) {
6379 if (!Data.getValueType().isInteger())
6380 Data = DAG.getNode(ISD::BITCAST, DL,
6381 Data.getValueType().changeTypeToInteger(), Data);
6382 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6383 } else {
6384 // We need to widen the return vector to a legal type
6385 if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6386 ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6387 LegalReqRetVT =
6388 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6389 ReqRetVT.getVectorNumElements() + 1);
6390 }
6391 }
6392 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6393
6394 if (IsTexFail) {
6395 TexFail =
6396 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6397 DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6398
6399 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6400 }
6401
6402 if (Result->getNumValues() == 1)
6403 return Data;
6404
6405 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6406}
6407
6408static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6409 SDValue *LWE, bool &IsTexFail) {
6410 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6411
6412 uint64_t Value = TexFailCtrlConst->getZExtValue();
6413 if (Value) {
6414 IsTexFail = true;
6415 }
6416
6417 SDLoc DL(TexFailCtrlConst);
6418 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6419 Value &= ~(uint64_t)0x1;
6420 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6421 Value &= ~(uint64_t)0x2;
6422
6423 return Value == 0;
6424}
6425
6426static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6427 MVT PackVectorVT,
6428 SmallVectorImpl<SDValue> &PackedAddrs,
6429 unsigned DimIdx, unsigned EndIdx,
6430 unsigned NumGradients) {
6431 SDLoc DL(Op);
6432 for (unsigned I = DimIdx; I < EndIdx; I++) {
6433 SDValue Addr = Op.getOperand(I);
6434
6435 // Gradients are packed with undef for each coordinate.
6436 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6437 // 1D: undef,dx/dh; undef,dx/dv
6438 // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6439 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6440 if (((I + 1) >= EndIdx) ||
6441 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6442 I == DimIdx + NumGradients - 1))) {
6443 if (Addr.getValueType() != MVT::i16)
6444 Addr = DAG.getBitcast(MVT::i16, Addr);
6445 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6446 } else {
6447 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6448 I++;
6449 }
6450 Addr = DAG.getBitcast(MVT::f32, Addr);
6451 PackedAddrs.push_back(Addr);
6452 }
6453}
6454
6455SDValue SITargetLowering::lowerImage(SDValue Op,
6456 const AMDGPU::ImageDimIntrinsicInfo *Intr,
6457 SelectionDAG &DAG, bool WithChain) const {
6458 SDLoc DL(Op);
6459 MachineFunction &MF = DAG.getMachineFunction();
6460 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6461 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6462 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6463 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6464 unsigned IntrOpcode = Intr->BaseOpcode;
6465 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6466 bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
6467
6468 SmallVector<EVT, 3> ResultTypes(Op->values());
6469 SmallVector<EVT, 3> OrigResultTypes(Op->values());
6470 bool IsD16 = false;
6471 bool IsG16 = false;
6472 bool IsA16 = false;
6473 SDValue VData;
6474 int NumVDataDwords;
6475 bool AdjustRetType = false;
6476
6477 // Offset of intrinsic arguments
6478 const unsigned ArgOffset = WithChain ? 2 : 1;
6479
6480 unsigned DMask;
6481 unsigned DMaskLanes = 0;
6482
6483 if (BaseOpcode->Atomic) {
6484 VData = Op.getOperand(2);
6485
6486 bool Is64Bit = VData.getValueType() == MVT::i64;
6487 if (BaseOpcode->AtomicX2) {
6488 SDValue VData2 = Op.getOperand(3);
6489 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6490 {VData, VData2});
6491 if (Is64Bit)
6492 VData = DAG.getBitcast(MVT::v4i32, VData);
6493
6494 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6495 DMask = Is64Bit ? 0xf : 0x3;
6496 NumVDataDwords = Is64Bit ? 4 : 2;
6497 } else {
6498 DMask = Is64Bit ? 0x3 : 0x1;
6499 NumVDataDwords = Is64Bit ? 2 : 1;
6500 }
6501 } else {
6502 auto *DMaskConst =
6503 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6504 DMask = DMaskConst->getZExtValue();
6505 DMaskLanes = BaseOpcode->Gather4 ? 4 : llvm::popcount(DMask);
6506
6507 if (BaseOpcode->Store) {
6508 VData = Op.getOperand(2);
6509
6510 MVT StoreVT = VData.getSimpleValueType();
6511 if (StoreVT.getScalarType() == MVT::f16) {
6512 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6513 return Op; // D16 is unsupported for this instruction
6514
6515 IsD16 = true;
6516 VData = handleD16VData(VData, DAG, true);
6517 }
6518
6519 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6520 } else {
6521 // Work out the num dwords based on the dmask popcount and underlying type
6522 // and whether packing is supported.
6523 MVT LoadVT = ResultTypes[0].getSimpleVT();
6524 if (LoadVT.getScalarType() == MVT::f16) {
6525 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6526 return Op; // D16 is unsupported for this instruction
6527
6528 IsD16 = true;
6529 }
6530
6531 // Confirm that the return type is large enough for the dmask specified
6532 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6533 (!LoadVT.isVector() && DMaskLanes > 1))
6534 return Op;
6535
6536 // The sq block of gfx8 and gfx9 do not estimate register use correctly
6537 // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6538 // instructions.
6539 if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6540 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6541 NumVDataDwords = (DMaskLanes + 1) / 2;
6542 else
6543 NumVDataDwords = DMaskLanes;
6544
6545 AdjustRetType = true;
6546 }
6547 }
6548
6549 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6550 SmallVector<SDValue, 4> VAddrs;
6551
6552 // Check for 16 bit addresses or derivatives and pack if true.
6553 MVT VAddrVT =
6554 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6555 MVT VAddrScalarVT = VAddrVT.getScalarType();
6556 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6557 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6558
6559 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6560 VAddrScalarVT = VAddrVT.getScalarType();
6561 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6562 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6563
6564 // Push back extra arguments.
6565 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6566 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6567 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument")(static_cast <bool> (I == Intr->BiasIndex &&
"Got unexpected 16-bit extra argument") ? void (0) : __assert_fail
("I == Intr->BiasIndex && \"Got unexpected 16-bit extra argument\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6567, __extension__
__PRETTY_FUNCTION__))
;
6568 // Special handling of bias when A16 is on. Bias is of type half but
6569 // occupies full 32-bit.
6570 SDValue Bias = DAG.getBuildVector(
6571 MVT::v2f16, DL,
6572 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6573 VAddrs.push_back(Bias);
6574 } else {
6575 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&(static_cast <bool> ((!IsA16 || Intr->NumBiasArgs ==
0 || I != Intr->BiasIndex) && "Bias needs to be converted to 16 bit in A16 mode"
) ? void (0) : __assert_fail ("(!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && \"Bias needs to be converted to 16 bit in A16 mode\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6576, __extension__
__PRETTY_FUNCTION__))
6576 "Bias needs to be converted to 16 bit in A16 mode")(static_cast <bool> ((!IsA16 || Intr->NumBiasArgs ==
0 || I != Intr->BiasIndex) && "Bias needs to be converted to 16 bit in A16 mode"
) ? void (0) : __assert_fail ("(!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && \"Bias needs to be converted to 16 bit in A16 mode\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6576, __extension__
__PRETTY_FUNCTION__))
;
6577 VAddrs.push_back(Op.getOperand(ArgOffset + I));
6578 }
6579 }
6580
6581 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6582 // 16 bit gradients are supported, but are tied to the A16 control
6583 // so both gradients and addresses must be 16 bit
6584 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"require 16 bit args for both gradients and addresses"; } } while
(false)
6585 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 "
"require 16 bit args for both gradients and addresses"; } } while
(false)
6586 "require 16 bit args for both gradients and addresses")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("si-lower")) { dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
"require 16 bit args for both gradients and addresses"; } } while
(false)
;
6587 return Op;
6588 }
6589
6590 if (IsA16) {
6591 if (!ST->hasA16()) {
6592 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)
6593 "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)
;
6594 return Op;
6595 }
6596 }
6597
6598 // We've dealt with incorrect input so we know that if IsA16, IsG16
6599 // are set then we have to compress/pack operands (either address,
6600 // gradient or both)
6601 // In the case where a16 and gradients are tied (no G16 support) then we
6602 // have already verified that both IsA16 and IsG16 are true
6603 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6604 // Activate g16
6605 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6606 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6607 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6608 }
6609
6610 // Add gradients (packed or unpacked)
6611 if (IsG16) {
6612 // Pack the gradients
6613 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6614 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6615 ArgOffset + Intr->GradientStart,
6616 ArgOffset + Intr->CoordStart, Intr->NumGradients);
6617 } else {
6618 for (unsigned I = ArgOffset + Intr->GradientStart;
6619 I < ArgOffset + Intr->CoordStart; I++)
6620 VAddrs.push_back(Op.getOperand(I));
6621 }
6622
6623 // Add addresses (packed or unpacked)
6624 if (IsA16) {
6625 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6626 ArgOffset + Intr->CoordStart, VAddrEnd,
6627 0 /* No gradients */);
6628 } else {
6629 // Add uncompressed address
6630 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6631 VAddrs.push_back(Op.getOperand(I));
6632 }
6633
6634 // If the register allocator cannot place the address registers contiguously
6635 // without introducing moves, then using the non-sequential address encoding
6636 // is always preferable, since it saves VALU instructions and is usually a
6637 // wash in terms of code size or even better.
6638 //
6639 // However, we currently have no way of hinting to the register allocator that
6640 // MIMG addresses should be placed contiguously when it is possible to do so,
6641 // so force non-NSA for the common 2-address case as a heuristic.
6642 //
6643 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6644 // allocation when possible.
6645 //
6646 // Partial NSA is allowed on GFX11 where the final register is a contiguous
6647 // set of the remaining addresses.
6648 const unsigned NSAMaxSize = ST->getNSAMaxSize();
6649 const bool HasPartialNSAEncoding = ST->hasPartialNSAEncoding();
6650 const bool UseNSA = ST->hasNSAEncoding() &&
6651 VAddrs.size() >= ST->getNSAThreshold(MF) &&
6652 (VAddrs.size() <= NSAMaxSize || HasPartialNSAEncoding);
6653 const bool UsePartialNSA =
6654 UseNSA && HasPartialNSAEncoding && VAddrs.size() > NSAMaxSize;
6655
6656 SDValue VAddr;
6657 if (UsePartialNSA) {
6658 VAddr = getBuildDwordsVector(DAG, DL,
6659 ArrayRef(VAddrs).drop_front(NSAMaxSize - 1));
6660 }
6661 else if (!UseNSA) {
6662 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6663 }
6664
6665 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6666 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6667 SDValue Unorm;
6668 if (!BaseOpcode->Sampler) {
6669 Unorm = True;
6670 } else {
6671 auto UnormConst =
6672 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6673
6674 Unorm = UnormConst->getZExtValue() ? True : False;
6675 }
6676
6677 SDValue TFE;
6678 SDValue LWE;
6679 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6680 bool IsTexFail = false;
6681 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6682 return Op;
6683
6684 if (IsTexFail) {
6685 if (!DMaskLanes) {
6686 // Expecting to get an error flag since TFC is on - and dmask is 0
6687 // Force dmask to be at least 1 otherwise the instruction will fail
6688 DMask = 0x1;
6689 DMaskLanes = 1;
6690 NumVDataDwords = 1;
6691 }
6692 NumVDataDwords += 1;
6693 AdjustRetType = true;
6694 }
6695
6696 // Has something earlier tagged that the return type needs adjusting
6697 // This happens if the instruction is a load or has set TexFailCtrl flags
6698 if (AdjustRetType) {
6699 // NumVDataDwords reflects the true number of dwords required in the return type
6700 if (DMaskLanes == 0 && !BaseOpcode->Store) {
6701 // This is a no-op load. This can be eliminated
6702 SDValue Undef = DAG.getUNDEF(Op.getValueType());
6703 if (isa<MemSDNode>(Op))
6704 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6705 return Undef;
6706 }
6707
6708 EVT NewVT = NumVDataDwords > 1 ?
6709 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6710 : MVT::i32;
6711
6712 ResultTypes[0] = NewVT;
6713 if (ResultTypes.size() == 3) {
6714 // Original result was aggregate type used for TexFailCtrl results
6715 // The actual instruction returns as a vector type which has now been
6716 // created. Remove the aggregate result.
6717 ResultTypes.erase(&ResultTypes[1]);
6718 }
6719 }
6720
6721 unsigned CPol = cast<ConstantSDNode>(
6722 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6723 if (BaseOpcode->Atomic)
6724 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6725 if (CPol & ~AMDGPU::CPol::ALL)
6726 return Op;
6727
6728 SmallVector<SDValue, 26> Ops;
6729 if (BaseOpcode->Store || BaseOpcode->Atomic)
6730 Ops.push_back(VData); // vdata
6731 if (UsePartialNSA) {
6732 append_range(Ops, ArrayRef(VAddrs).take_front(NSAMaxSize - 1));
6733 Ops.push_back(VAddr);
6734 }
6735 else if (UseNSA)
6736 append_range(Ops, VAddrs);
6737 else
6738 Ops.push_back(VAddr);
6739 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6740 if (BaseOpcode->Sampler)
6741 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6742 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6743 if (IsGFX10Plus)
6744 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6745 Ops.push_back(Unorm);
6746 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6747 Ops.push_back(IsA16 && // r128, a16 for gfx9
6748 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6749 if (IsGFX10Plus)
6750 Ops.push_back(IsA16 ? True : False);
6751 if (!Subtarget->hasGFX90AInsts()) {
6752 Ops.push_back(TFE); //tfe
6753 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6754 report_fatal_error("TFE is not supported on this GPU");
6755 }
6756 Ops.push_back(LWE); // lwe
6757 if (!IsGFX10Plus)
6758 Ops.push_back(DimInfo->DA ? True : False);
6759 if (BaseOpcode->HasD16)
6760 Ops.push_back(IsD16 ? True : False);
6761 if (isa<MemSDNode>(Op))
6762 Ops.push_back(Op.getOperand(0)); // chain
6763
6764 int NumVAddrDwords =
6765 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6766 int Opcode = -1;
6767
6768 if (IsGFX11Plus) {
6769 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6770 UseNSA ? AMDGPU::MIMGEncGfx11NSA
6771 : AMDGPU::MIMGEncGfx11Default,
6772 NumVDataDwords, NumVAddrDwords);
6773 } else if (IsGFX10Plus) {
6774 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6775 UseNSA ? AMDGPU::MIMGEncGfx10NSA
6776 : AMDGPU::MIMGEncGfx10Default,
6777 NumVDataDwords, NumVAddrDwords);
6778 } else {
6779 if (Subtarget->hasGFX90AInsts()) {
6780 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6781 NumVDataDwords, NumVAddrDwords);
6782 if (Opcode == -1)
6783 report_fatal_error(
6784 "requested image instruction is not supported on this GPU");
6785 }
6786 if (Opcode == -1 &&
6787 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6788 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6789 NumVDataDwords, NumVAddrDwords);
6790 if (Opcode == -1)
6791 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6792 NumVDataDwords, NumVAddrDwords);
6793 }
6794 if (Opcode == -1)
6795 return Op;
6796
6797 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6798 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6799 MachineMemOperand *MemRef = MemOp->getMemOperand();
6800 DAG.setNodeMemRefs(NewNode, {MemRef});
6801 }
6802
6803 if (BaseOpcode->AtomicX2) {
6804 SmallVector<SDValue, 1> Elt;
6805 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6806 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6807 }
6808 if (BaseOpcode->Store)
6809 return SDValue(NewNode, 0);
6810 return constructRetValue(DAG, NewNode,
6811 OrigResultTypes, IsTexFail,
6812 Subtarget->hasUnpackedD16VMem(), IsD16,
6813 DMaskLanes, NumVDataDwords, DL);
6814}
6815
6816SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6817 SDValue Offset, SDValue CachePolicy,
6818 SelectionDAG &DAG) const {
6819 MachineFunction &MF = DAG.getMachineFunction();
6820
6821 const DataLayout &DataLayout = DAG.getDataLayout();
6822 Align Alignment =
6823 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6824
6825 MachineMemOperand *MMO = MF.getMachineMemOperand(
6826 MachinePointerInfo(),
6827 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6828 MachineMemOperand::MOInvariant,
6829 VT.getStoreSize(), Alignment);
6830
6831 if (!Offset->isDivergent()) {
6832 SDValue Ops[] = {
6833 Rsrc,
6834 Offset, // Offset
6835 CachePolicy
6836 };
6837
6838 // Widen vec3 load to vec4.
6839 if (VT.isVector() && VT.getVectorNumElements() == 3) {
6840 EVT WidenedVT =
6841 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6842 auto WidenedOp = DAG.getMemIntrinsicNode(
6843 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6844 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6845 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6846 DAG.getVectorIdxConstant(0, DL));
6847 return Subvector;
6848 }
6849
6850 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6851 DAG.getVTList(VT), Ops, VT, MMO);
6852 }
6853
6854 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6855 // assume that the buffer is unswizzled.
6856 SmallVector<SDValue, 4> Loads;
6857 unsigned NumLoads = 1;
6858 MVT LoadVT = VT.getSimpleVT();
6859 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6860 assert((LoadVT.getScalarType() == MVT::i32 ||(static_cast <bool> ((LoadVT.getScalarType() == MVT::i32
|| LoadVT.getScalarType() == MVT::f32)) ? void (0) : __assert_fail
("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6861, __extension__
__PRETTY_FUNCTION__))
6861 LoadVT.getScalarType() == MVT::f32))(static_cast <bool> ((LoadVT.getScalarType() == MVT::i32
|| LoadVT.getScalarType() == MVT::f32)) ? void (0) : __assert_fail
("(LoadVT.getScalarType() == MVT::i32 || LoadVT.getScalarType() == MVT::f32)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 6861, __extension__
__PRETTY_FUNCTION__))
;
6862
6863 if (NumElts == 8 || NumElts == 16) {
6864 NumLoads = NumElts / 4;
6865 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6866 }
6867
6868 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6869 SDValue Ops[] = {
6870 DAG.getEntryNode(), // Chain
6871 Rsrc, // rsrc
6872 DAG.getConstant(0, DL, MVT::i32), // vindex
6873 {}, // voffset
6874 {}, // soffset
6875 {}, // offset
6876 CachePolicy, // cachepolicy
6877 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6878 };
6879
6880 // Use the alignment to ensure that the required offsets will fit into the
6881 // immediate offsets.
6882 setBufferOffsets(Offset, DAG, &Ops[3],
6883 NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6884
6885 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6886 for (unsigned i = 0; i < NumLoads; ++i) {
6887 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6888 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6889 LoadVT, MMO, DAG));
6890 }
6891
6892 if (NumElts == 8 || NumElts == 16)
6893 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6894
6895 return Loads[0];
6896}
6897
6898SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6899 unsigned Dim,
6900 const ArgDescriptor &Arg) const {
6901 SDLoc SL(Op);
6902 MachineFunction &MF = DAG.getMachineFunction();
6903 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6904 if (MaxID == 0)
6905 return DAG.getConstant(0, SL, MVT::i32);
6906
6907 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6908 SDLoc(DAG.getEntryNode()), Arg);
6909
6910 // Don't bother inserting AssertZext for packed IDs since we're emitting the
6911 // masking operations anyway.
6912 //
6913 // TODO: We could assert the top bit is 0 for the source copy.
6914 if (Arg.isMasked())
6915 return Val;
6916
6917 // Preserve the known bits after expansion to a copy.
6918 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_width(MaxID));
6919 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6920 DAG.getValueType(SmallVT));
6921}
6922
6923SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6924 SelectionDAG &DAG) const {
6925 MachineFunction &MF = DAG.getMachineFunction();
6926 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6927
6928 EVT VT = Op.getValueType();
6929 SDLoc DL(Op);
6930 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6931
6932 // TODO: Should this propagate fast-math-flags?
6933
6934 switch (IntrinsicID) {
6935 case Intrinsic::amdgcn_implicit_buffer_ptr: {
6936 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6937 return emitNonHSAIntrinsicError(DAG, DL, VT);
6938 return getPreloadedValue(DAG, *MFI, VT,
6939 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6940 }
6941 case Intrinsic::amdgcn_dispatch_ptr:
6942 case Intrinsic::amdgcn_queue_ptr: {
6943 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6944 DiagnosticInfoUnsupported BadIntrin(
6945 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6946 DL.getDebugLoc());
6947 DAG.getContext()->diagnose(BadIntrin);
6948 return DAG.getUNDEF(VT);
6949 }
6950
6951 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6952 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6953 return getPreloadedValue(DAG, *MFI, VT, RegID);
6954 }
6955 case Intrinsic::amdgcn_implicitarg_ptr: {
6956 if (MFI->isEntryFunction())
6957 return getImplicitArgPtr(DAG, DL);
6958 return getPreloadedValue(DAG, *MFI, VT,
6959 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6960 }
6961 case Intrinsic::amdgcn_kernarg_segment_ptr: {
6962 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6963 // This only makes sense to call in a kernel, so just lower to null.
6964 return DAG.getConstant(0, DL, VT);
6965 }
6966
6967 return getPreloadedValue(DAG, *MFI, VT,
6968 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6969 }
6970 case Intrinsic::amdgcn_dispatch_id: {
6971 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6972 }
6973 case Intrinsic::amdgcn_rcp:
6974 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6975 case Intrinsic::amdgcn_rsq:
6976 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6977 case Intrinsic::amdgcn_rsq_legacy:
6978 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6979 return emitRemovedIntrinsicError(DAG, DL, VT);
6980 return SDValue();
6981 case Intrinsic::amdgcn_rcp_legacy:
6982 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6983 return emitRemovedIntrinsicError(DAG, DL, VT);
6984 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6985 case Intrinsic::amdgcn_rsq_clamp: {
6986 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6987 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6988
6989 Type *Type = VT.getTypeForEVT(*DAG.getContext());
6990 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6991 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6992
6993 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6994 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6995 DAG.getConstantFP(Max, DL, VT));
6996 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6997 DAG.getConstantFP(Min, DL, VT));
6998 }
6999 case Intrinsic::r600_read_ngroups_x:
7000 if (Subtarget->isAmdHsaOS())
7001 return emitNonHSAIntrinsicError(DAG, DL, VT);
7002
7003 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7004 SI::KernelInputOffsets::NGROUPS_X, Align(4),
7005 false);
7006 case Intrinsic::r600_read_ngroups_y:
7007 if (Subtarget->isAmdHsaOS())
7008 return emitNonHSAIntrinsicError(DAG, DL, VT);
7009
7010 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7011 SI::KernelInputOffsets::NGROUPS_Y, Align(4),
7012 false);
7013 case Intrinsic::r600_read_ngroups_z:
7014 if (Subtarget->isAmdHsaOS())
7015 return emitNonHSAIntrinsicError(DAG, DL, VT);
7016
7017 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7018 SI::KernelInputOffsets::NGROUPS_Z, Align(4),
7019 false);
7020 case Intrinsic::r600_read_global_size_x:
7021 if (Subtarget->isAmdHsaOS())
7022 return emitNonHSAIntrinsicError(DAG, DL, VT);
7023
7024 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7025 SI::KernelInputOffsets::GLOBAL_SIZE_X,
7026 Align(4), false);
7027 case Intrinsic::r600_read_global_size_y:
7028 if (Subtarget->isAmdHsaOS())
7029 return emitNonHSAIntrinsicError(DAG, DL, VT);
7030
7031 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7032 SI::KernelInputOffsets::GLOBAL_SIZE_Y,
7033 Align(4), false);
7034 case Intrinsic::r600_read_global_size_z:
7035 if (Subtarget->isAmdHsaOS())
7036 return emitNonHSAIntrinsicError(DAG, DL, VT);
7037
7038 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7039 SI::KernelInputOffsets::GLOBAL_SIZE_Z,
7040 Align(4), false);
7041 case Intrinsic::r600_read_local_size_x:
7042 if (Subtarget->isAmdHsaOS())
7043 return emitNonHSAIntrinsicError(DAG, DL, VT);
7044
7045 return lowerImplicitZextParam(DAG, Op, MVT::i16,
7046 SI::KernelInputOffsets::LOCAL_SIZE_X);
7047 case Intrinsic::r600_read_local_size_y:
7048 if (Subtarget->isAmdHsaOS())
7049 return emitNonHSAIntrinsicError(DAG, DL, VT);
7050
7051 return lowerImplicitZextParam(DAG, Op, MVT::i16,
7052 SI::KernelInputOffsets::LOCAL_SIZE_Y);
7053 case Intrinsic::r600_read_local_size_z:
7054 if (Subtarget->isAmdHsaOS())
7055 return emitNonHSAIntrinsicError(DAG, DL, VT);
7056
7057 return lowerImplicitZextParam(DAG, Op, MVT::i16,
7058 SI::KernelInputOffsets::LOCAL_SIZE_Z);
7059 case Intrinsic::amdgcn_workgroup_id_x:
7060 return getPreloadedValue(DAG, *MFI, VT,
7061 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
7062 case Intrinsic::amdgcn_workgroup_id_y:
7063 return getPreloadedValue(DAG, *MFI, VT,
7064 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
7065 case Intrinsic::amdgcn_workgroup_id_z:
7066 return getPreloadedValue(DAG, *MFI, VT,
7067 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
7068 case Intrinsic::amdgcn_lds_kernel_id: {
7069 if (MFI->isEntryFunction())
7070 return getLDSKernelId(DAG, DL);
7071 return getPreloadedValue(DAG, *MFI, VT,
7072 AMDGPUFunctionArgInfo::LDS_KERNEL_ID);
7073 }
7074 case Intrinsic::amdgcn_workitem_id_x:
7075 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
7076 case Intrinsic::amdgcn_workitem_id_y:
7077 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
7078 case Intrinsic::amdgcn_workitem_id_z:
7079 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
7080 case Intrinsic::amdgcn_wavefrontsize:
7081 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
7082 SDLoc(Op), MVT::i32);
7083 case Intrinsic::amdgcn_s_buffer_load: {
7084 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
7085 if (CPol & ~AMDGPU::CPol::ALL)
7086 return Op;
7087 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7088 DAG);
7089 }
7090 case Intrinsic::amdgcn_fdiv_fast:
7091 return lowerFDIV_FAST(Op, DAG);
7092 case Intrinsic::amdgcn_sin:
7093 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
7094
7095 case Intrinsic::amdgcn_cos:
7096 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
7097
7098 case Intrinsic::amdgcn_mul_u24:
7099 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
7100 case Intrinsic::amdgcn_mul_i24:
7101 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
7102
7103 case Intrinsic::amdgcn_log_clamp: {
7104 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
7105 return SDValue();
7106
7107 return emitRemovedIntrinsicError(DAG, DL, VT);
7108 }
7109 case Intrinsic::amdgcn_ldexp:
7110 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
7111 Op.getOperand(1), Op.getOperand(2));
7112
7113 case Intrinsic::amdgcn_fract:
7114 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
7115
7116 case Intrinsic::amdgcn_class:
7117 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
7118 Op.getOperand(1), Op.getOperand(2));
7119 case Intrinsic::amdgcn_div_fmas:
7120 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
7121 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7122 Op.getOperand(4));
7123
7124 case Intrinsic::amdgcn_div_fixup:
7125 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
7126 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7127
7128 case Intrinsic::amdgcn_div_scale: {
7129 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
7130
7131 // Translate to the operands expected by the machine instruction. The
7132 // first parameter must be the same as the first instruction.
7133 SDValue Numerator = Op.getOperand(1);
7134 SDValue Denominator = Op.getOperand(2);
7135
7136 // Note this order is opposite of the machine instruction's operations,
7137 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
7138 // intrinsic has the numerator as the first operand to match a normal
7139 // division operation.
7140
7141 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
7142
7143 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
7144 Denominator, Numerator);
7145 }
7146 case Intrinsic::amdgcn_icmp: {
7147 // There is a Pat that handles this variant, so return it as-is.
7148 if (Op.getOperand(1).getValueType() == MVT::i1 &&
7149 Op.getConstantOperandVal(2) == 0 &&
7150 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
7151 return Op;
7152 return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7153 }
7154 case Intrinsic::amdgcn_fcmp: {
7155 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7156 }
7157 case Intrinsic::amdgcn_ballot:
7158 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7159 case Intrinsic::amdgcn_fmed3:
7160 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7161 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7162 case Intrinsic::amdgcn_fdot2:
7163 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7164 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7165 Op.getOperand(4));
7166 case Intrinsic::amdgcn_fmul_legacy:
7167 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7168 Op.getOperand(1), Op.getOperand(2));
7169 case Intrinsic::amdgcn_sffbh:
7170 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7171 case Intrinsic::amdgcn_sbfe:
7172 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7173 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7174 case Intrinsic::amdgcn_ubfe:
7175 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7176 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7177 case Intrinsic::amdgcn_cvt_pkrtz:
7178 case Intrinsic::amdgcn_cvt_pknorm_i16:
7179 case Intrinsic::amdgcn_cvt_pknorm_u16:
7180 case Intrinsic::amdgcn_cvt_pk_i16:
7181 case Intrinsic::amdgcn_cvt_pk_u16: {
7182 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7183 EVT VT = Op.getValueType();
7184 unsigned Opcode;
7185
7186 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7187 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7188 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7189 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7190 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7191 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7192 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7193 Opcode = AMDGPUISD::CVT_PK_I16_I32;
7194 else
7195 Opcode = AMDGPUISD::CVT_PK_U16_U32;
7196
7197 if (isTypeLegal(VT))
7198 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7199
7200 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7201 Op.getOperand(1), Op.getOperand(2));
7202 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7203 }
7204 case Intrinsic::amdgcn_fmad_ftz:
7205 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7206 Op.getOperand(2), Op.getOperand(3));
7207
7208 case Intrinsic::amdgcn_if_break:
7209 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7210 Op->getOperand(1), Op->getOperand(2)), 0);
7211
7212 case Intrinsic::amdgcn_groupstaticsize: {
7213 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7214 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7215 return Op;
7216
7217 const Module *M = MF.getFunction().getParent();
7218 const GlobalValue *GV =
7219 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7220 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7221 SIInstrInfo::MO_ABS32_LO);
7222 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7223 }
7224 case Intrinsic::amdgcn_is_shared:
7225 case Intrinsic::amdgcn_is_private: {
7226 SDLoc SL(Op);
7227 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7228 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7229 SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7230 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7231 Op.getOperand(1));
7232
7233 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7234 DAG.getConstant(1, SL, MVT::i32));
7235 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7236 }
7237 case Intrinsic::amdgcn_perm:
7238 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7239 Op.getOperand(2), Op.getOperand(3));
7240 case Intrinsic::amdgcn_reloc_constant: {
7241 Module *M = const_cast<Module *>(MF.getFunction().getParent());
7242 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7243 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7244 auto RelocSymbol = cast<GlobalVariable>(
7245 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7246 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7247 SIInstrInfo::MO_ABS32_LO);
7248 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7249 }
7250 default:
7251 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7252 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7253 return lowerImage(Op, ImageDimIntr, DAG, false);
7254
7255 return Op;
7256 }
7257}
7258
7259/// Update \p MMO based on the offset inputs to an intrinsic.
7260static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7261 SDValue SOffset, SDValue Offset,
7262 SDValue VIndex = SDValue()) {
7263 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7264 !isa<ConstantSDNode>(Offset)) {
7265 // The combined offset is not known to be constant, so we cannot represent
7266 // it in the MMO. Give up.
7267 MMO->setValue((Value *)nullptr);
7268 return;
7269 }
7270
7271 if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7272 !cast<ConstantSDNode>(VIndex)->isZero())) {
7273 // The strided index component of the address is not known to be zero, so we
7274 // cannot represent it in the MMO. Give up.
7275 MMO->setValue((Value *)nullptr);
7276 return;
7277 }
7278
7279 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7280 cast<ConstantSDNode>(SOffset)->getSExtValue() +
7281 cast<ConstantSDNode>(Offset)->getSExtValue());
7282}
7283
7284SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7285 SelectionDAG &DAG,
7286 unsigned NewOpcode) const {
7287 SDLoc DL(Op);
7288
7289 SDValue VData = Op.getOperand(2);
7290 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7291 SDValue Ops[] = {
7292 Op.getOperand(0), // Chain
7293 VData, // vdata
7294 Op.getOperand(3), // rsrc
7295 DAG.getConstant(0, DL, MVT::i32), // vindex
7296 Offsets.first, // voffset
7297 Op.getOperand(5), // soffset
7298 Offsets.second, // offset
7299 Op.getOperand(6), // cachepolicy
7300 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7301 };
7302
7303 auto *M = cast<MemSDNode>(Op);
7304 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7305
7306 EVT MemVT = VData.getValueType();
7307 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7308 M->getMemOperand());
7309}
7310
7311// Return a value to use for the idxen operand by examining the vindex operand.
7312static unsigned getIdxEn(SDValue VIndex) {
7313 // No need to set idxen if vindex is known to be zero.
7314 return isNullConstant(VIndex) ? 0 : 1;
7315}
7316
7317SDValue
7318SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7319 unsigned NewOpcode) const {
7320 SDLoc DL(Op);
7321
7322 SDValue VData = Op.getOperand(2);
7323 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7324 SDValue Ops[] = {
7325 Op.getOperand(0), // Chain
7326 VData, // vdata
7327 Op.getOperand(3), // rsrc
7328 Op.getOperand(4), // vindex
7329 Offsets.first, // voffset
7330 Op.getOperand(6), // soffset
7331 Offsets.second, // offset
7332 Op.getOperand(7), // cachepolicy
7333 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7334 };
7335
7336 auto *M = cast<MemSDNode>(Op);
7337 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7338
7339 EVT MemVT = VData.getValueType();
7340 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7341 M->getMemOperand());
7342}
7343
7344SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7345 SelectionDAG &DAG) const {
7346 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7347 SDLoc DL(Op);
7348
7349 switch (IntrID) {
7350 case Intrinsic::amdgcn_ds_ordered_add:
7351 case Intrinsic::amdgcn_ds_ordered_swap: {
7352 MemSDNode *M = cast<MemSDNode>(Op);
7353 SDValue Chain = M->getOperand(0);
7354 SDValue M0 = M->getOperand(2);
7355 SDValue Value = M->getOperand(3);
7356 unsigned IndexOperand = M->getConstantOperandVal(7);
7357 unsigned WaveRelease = M->getConstantOperandVal(8);
7358 unsigned WaveDone = M->getConstantOperandVal(9);
7359
7360 unsigned OrderedCountIndex = IndexOperand & 0x3f;
7361 IndexOperand &= ~0x3f;
7362 unsigned CountDw = 0;
7363
7364 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7365 CountDw = (IndexOperand >> 24) & 0xf;
7366 IndexOperand &= ~(0xf << 24);
7367
7368 if (CountDw < 1 || CountDw > 4) {
7369 report_fatal_error(
7370 "ds_ordered_count: dword count must be between 1 and 4");
7371 }
7372 }
7373
7374 if (IndexOperand)
7375 report_fatal_error("ds_ordered_count: bad index operand");
7376
7377 if (WaveDone && !WaveRelease)
7378 report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7379
7380 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7381 unsigned ShaderType =
7382 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7383 unsigned Offset0 = OrderedCountIndex << 2;
7384 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
7385
7386 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7387 Offset1 |= (CountDw - 1) << 6;
7388
7389 if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
7390 Offset1 |= ShaderType << 2;
7391
7392 unsigned Offset = Offset0 | (Offset1 << 8);
7393
7394 SDValue Ops[] = {
7395 Chain,
7396 Value,
7397 DAG.getTargetConstant(Offset, DL, MVT::i16),
7398 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7399 };
7400 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7401 M->getVTList(), Ops, M->getMemoryVT(),
7402 M->getMemOperand());
7403 }
7404 case Intrinsic::amdgcn_atomic_inc:
7405 case Intrinsic::amdgcn_atomic_dec:
7406 case Intrinsic::amdgcn_ds_fadd: {
7407 MemSDNode *M = cast<MemSDNode>(Op);
7408 unsigned Opc;
7409 switch (IntrID) {
7410 case Intrinsic::amdgcn_ds_fadd:
7411 Opc = ISD::ATOMIC_LOAD_FADD;
7412 break;
7413 case Intrinsic::amdgcn_atomic_inc:
7414 Opc = ISD::ATOMIC_LOAD_UINC_WRAP;
7415 break;
7416 case Intrinsic::amdgcn_atomic_dec:
7417 Opc = ISD::ATOMIC_LOAD_UDEC_WRAP;
7418 break;
7419 }
7420
7421 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7422 M->getOperand(0), M->getOperand(2), M->getOperand(3),
7423 M->getMemOperand());
7424 }
7425 case Intrinsic::amdgcn_ds_fmin:
7426 case Intrinsic::amdgcn_ds_fmax: {
7427 MemSDNode *M = cast<MemSDNode>(Op);
7428 unsigned Opc;
7429 switch (IntrID) {
7430 case Intrinsic::amdgcn_atomic_inc:
7431 Opc = ISD::ATOMIC_LOAD_UINC_WRAP;
7432 break;
7433 case Intrinsic::amdgcn_atomic_dec:
7434 Opc = ISD::ATOMIC_LOAD_UDEC_WRAP;
7435 break;
7436 case Intrinsic::amdgcn_ds_fmin:
7437 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7438 break;
7439 case Intrinsic::amdgcn_ds_fmax:
7440 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7441 break;
7442 default:
7443 llvm_unreachable("Unknown intrinsic!")::llvm::llvm_unreachable_internal("Unknown intrinsic!", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7443)
;
7444 }
7445 SDValue Ops[] = {
7446 M->getOperand(0), // Chain
7447 M->getOperand(2), // Ptr
7448 M->getOperand(3) // Value
7449 };
7450
7451 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7452 M->getMemoryVT(), M->getMemOperand());
7453 }
7454 case Intrinsic::amdgcn_buffer_load:
7455 case Intrinsic::amdgcn_buffer_load_format: {
7456 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7457 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7458 unsigned IdxEn = getIdxEn(Op.getOperand(3));
7459 SDValue Ops[] = {
7460 Op.getOperand(0), // Chain
7461 Op.getOperand(2), // rsrc
7462 Op.getOperand(3), // vindex
7463 SDValue(), // voffset -- will be set by setBufferOffsets
7464 SDValue(), // soffset -- will be set by setBufferOffsets
7465 SDValue(), // offset -- will be set by setBufferOffsets
7466 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7467 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7468 };
7469 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7470
7471 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7472 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7473
7474 EVT VT = Op.getValueType();
7475 EVT IntVT = VT.changeTypeToInteger();
7476 auto *M = cast<MemSDNode>(Op);
7477 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7478 EVT LoadVT = Op.getValueType();
7479
7480 if (LoadVT.getScalarType() == MVT::f16)
7481 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7482 M, DAG, Ops);
7483
7484 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7485 if (LoadVT.getScalarType() == MVT::i8 ||
7486 LoadVT.getScalarType() == MVT::i16)
7487 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7488
7489 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7490 M->getMemOperand(), DAG);
7491 }
7492 case Intrinsic::amdgcn_raw_buffer_load:
7493 case Intrinsic::amdgcn_raw_buffer_load_format: {
7494 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7495
7496 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7497 SDValue Ops[] = {
7498 Op.getOperand(0), // Chain
7499 Op.getOperand(2), // rsrc
7500 DAG.getConstant(0, DL, MVT::i32), // vindex
7501 Offsets.first, // voffset
7502 Op.getOperand(4), // soffset
7503 Offsets.second, // offset
7504 Op.getOperand(5), // cachepolicy, swizzled buffer
7505 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7506 };
7507
7508 auto *M = cast<MemSDNode>(Op);
7509 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7510 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7511 }
7512 case Intrinsic::amdgcn_struct_buffer_load:
7513 case Intrinsic::amdgcn_struct_buffer_load_format: {
7514 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7515
7516 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7517 SDValue Ops[] = {
7518 Op.getOperand(0), // Chain
7519 Op.getOperand(2), // rsrc
7520 Op.getOperand(3), // vindex
7521 Offsets.first, // voffset
7522 Op.getOperand(5), // soffset
7523 Offsets.second, // offset
7524 Op.getOperand(6), // cachepolicy, swizzled buffer
7525 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7526 };
7527
7528 auto *M = cast<MemSDNode>(Op);
7529 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7530 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7531 }
7532 case Intrinsic::amdgcn_tbuffer_load: {
7533 MemSDNode *M = cast<MemSDNode>(Op);
7534 EVT LoadVT = Op.getValueType();
7535
7536 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7537 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7538 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7539 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7540 unsigned IdxEn = getIdxEn(Op.getOperand(3));
7541 SDValue Ops[] = {
7542 Op.getOperand(0), // Chain
7543 Op.getOperand(2), // rsrc
7544 Op.getOperand(3), // vindex
7545 Op.getOperand(4), // voffset
7546 Op.getOperand(5), // soffset
7547 Op.getOperand(6), // offset
7548 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7549 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7550 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7551 };
7552
7553 if (LoadVT.getScalarType() == MVT::f16)
7554 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7555 M, DAG, Ops);
7556 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7557 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7558 DAG);
7559 }
7560 case Intrinsic::amdgcn_raw_tbuffer_load: {
7561 MemSDNode *M = cast<MemSDNode>(Op);
7562 EVT LoadVT = Op.getValueType();
7563 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7564
7565 SDValue Ops[] = {
7566 Op.getOperand(0), // Chain
7567 Op.getOperand(2), // rsrc
7568 DAG.getConstant(0, DL, MVT::i32), // vindex
7569 Offsets.first, // voffset
7570 Op.getOperand(4), // soffset
7571 Offsets.second, // offset
7572 Op.getOperand(5), // format
7573 Op.getOperand(6), // cachepolicy, swizzled buffer
7574 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7575 };
7576
7577 if (LoadVT.getScalarType() == MVT::f16)
7578 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7579 M, DAG, Ops);
7580 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7581 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7582 DAG);
7583 }
7584 case Intrinsic::amdgcn_struct_tbuffer_load: {
7585 MemSDNode *M = cast<MemSDNode>(Op);
7586 EVT LoadVT = Op.getValueType();
7587 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7588
7589 SDValue Ops[] = {
7590 Op.getOperand(0), // Chain
7591 Op.getOperand(2), // rsrc
7592 Op.getOperand(3), // vindex
7593 Offsets.first, // voffset
7594 Op.getOperand(5), // soffset
7595 Offsets.second, // offset
7596 Op.getOperand(6), // format
7597 Op.getOperand(7), // cachepolicy, swizzled buffer
7598 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7599 };
7600
7601 if (LoadVT.getScalarType() == MVT::f16)
7602 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7603 M, DAG, Ops);
7604 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7605 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7606 DAG);
7607 }
7608 case Intrinsic::amdgcn_buffer_atomic_swap:
7609 case Intrinsic::amdgcn_buffer_atomic_add:
7610 case Intrinsic::amdgcn_buffer_atomic_sub:
7611 case Intrinsic::amdgcn_buffer_atomic_csub:
7612 case Intrinsic::amdgcn_buffer_atomic_smin:
7613 case Intrinsic::amdgcn_buffer_atomic_umin:
7614 case Intrinsic::amdgcn_buffer_atomic_smax:
7615 case Intrinsic::amdgcn_buffer_atomic_umax:
7616 case Intrinsic::amdgcn_buffer_atomic_and:
7617 case Intrinsic::amdgcn_buffer_atomic_or:
7618 case Intrinsic::amdgcn_buffer_atomic_xor:
7619 case Intrinsic::amdgcn_buffer_atomic_fadd: {
7620 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7621 unsigned IdxEn = getIdxEn(Op.getOperand(4));
7622 SDValue Ops[] = {
7623 Op.getOperand(0), // Chain
7624 Op.getOperand(2), // vdata
7625 Op.getOperand(3), // rsrc
7626 Op.getOperand(4), // vindex
7627 SDValue(), // voffset -- will be set by setBufferOffsets
7628 SDValue(), // soffset -- will be set by setBufferOffsets
7629 SDValue(), // offset -- will be set by setBufferOffsets
7630 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7631 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7632 };
7633 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7634
7635 EVT VT = Op.getValueType();
7636
7637 auto *M = cast<MemSDNode>(Op);
7638 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7639 unsigned Opcode = 0;
7640
7641 switch (IntrID) {
7642 case Intrinsic::amdgcn_buffer_atomic_swap:
7643 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7644 break;
7645 case Intrinsic::amdgcn_buffer_atomic_add:
7646 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7647 break;
7648 case Intrinsic::amdgcn_buffer_atomic_sub:
7649 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7650 break;
7651 case Intrinsic::amdgcn_buffer_atomic_csub:
7652 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7653 break;
7654 case Intrinsic::amdgcn_buffer_atomic_smin:
7655 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7656 break;
7657 case Intrinsic::amdgcn_buffer_atomic_umin:
7658 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7659 break;
7660 case Intrinsic::amdgcn_buffer_atomic_smax:
7661 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7662 break;
7663 case Intrinsic::amdgcn_buffer_atomic_umax:
7664 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7665 break;
7666 case Intrinsic::amdgcn_buffer_atomic_and:
7667 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7668 break;
7669 case Intrinsic::amdgcn_buffer_atomic_or:
7670 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7671 break;
7672 case Intrinsic::amdgcn_buffer_atomic_xor:
7673 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7674 break;
7675 case Intrinsic::amdgcn_buffer_atomic_fadd:
7676 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7677 break;
7678 default:
7679 llvm_unreachable("unhandled atomic opcode")::llvm::llvm_unreachable_internal("unhandled atomic opcode", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7679)
;
7680 }
7681
7682 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7683 M->getMemOperand());
7684 }
7685 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7686 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7687 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7688 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7689 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7690 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7691 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7692 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7693 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7694 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7695 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7696 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7697 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7698 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7699 case Intrinsic::amdgcn_raw_buffer_atomic_add:
7700 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7701 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7702 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7703 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7704 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7705 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7706 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7707 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7708 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7709 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7710 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7711 case Intrinsic::amdgcn_raw_buffer_atomic_and:
7712 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7713 case Intrinsic::amdgcn_raw_buffer_atomic_or:
7714 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7715 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7716 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7717 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7718 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7719 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7720 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7721 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7722 return lowerStructBufferAtomicIntrin(Op, DAG,
7723 AMDGPUISD::BUFFER_ATOMIC_SWAP);
7724 case Intrinsic::amdgcn_struct_buffer_atomic_add:
7725 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7726 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7727 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7728 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7729 return lowerStructBufferAtomicIntrin(Op, DAG,
7730 AMDGPUISD::BUFFER_ATOMIC_SMIN);
7731 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7732 return lowerStructBufferAtomicIntrin(Op, DAG,
7733 AMDGPUISD::BUFFER_ATOMIC_UMIN);
7734 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7735 return lowerStructBufferAtomicIntrin(Op, DAG,
7736 AMDGPUISD::BUFFER_ATOMIC_SMAX);
7737 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7738 return lowerStructBufferAtomicIntrin(Op, DAG,
7739 AMDGPUISD::BUFFER_ATOMIC_UMAX);
7740 case Intrinsic::amdgcn_struct_buffer_atomic_and:
7741 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7742 case Intrinsic::amdgcn_struct_buffer_atomic_or:
7743 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7744 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7745 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7746 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7747 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7748 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7749 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7750
7751 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7752 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7753 unsigned IdxEn = getIdxEn(Op.getOperand(5));
7754 SDValue Ops[] = {
7755 Op.getOperand(0), // Chain
7756 Op.getOperand(2), // src
7757 Op.getOperand(3), // cmp
7758 Op.getOperand(4), // rsrc
7759 Op.getOperand(5), // vindex
7760 SDValue(), // voffset -- will be set by setBufferOffsets
7761 SDValue(), // soffset -- will be set by setBufferOffsets
7762 SDValue(), // offset -- will be set by setBufferOffsets
7763 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7764 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7765 };
7766 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7767
7768 EVT VT = Op.getValueType();
7769 auto *M = cast<MemSDNode>(Op);
7770 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7771
7772 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7773 Op->getVTList(), Ops, VT, M->getMemOperand());
7774 }
7775 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7776 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7777 SDValue Ops[] = {
7778 Op.getOperand(0), // Chain
7779 Op.getOperand(2), // src
7780 Op.getOperand(3), // cmp
7781 Op.getOperand(4), // rsrc
7782 DAG.getConstant(0, DL, MVT::i32), // vindex
7783 Offsets.first, // voffset
7784 Op.getOperand(6), // soffset
7785 Offsets.second, // offset
7786 Op.getOperand(7), // cachepolicy
7787 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7788 };
7789 EVT VT = Op.getValueType();
7790 auto *M = cast<MemSDNode>(Op);
7791 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7792
7793 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7794 Op->getVTList(), Ops, VT, M->getMemOperand());
7795 }
7796 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7797 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7798 SDValue Ops[] = {
7799 Op.getOperand(0), // Chain
7800 Op.getOperand(2), // src
7801 Op.getOperand(3), // cmp
7802 Op.getOperand(4), // rsrc
7803 Op.getOperand(5), // vindex
7804 Offsets.first, // voffset
7805 Op.getOperand(7), // soffset
7806 Offsets.second, // offset
7807 Op.getOperand(8), // cachepolicy
7808 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7809 };
7810 EVT VT = Op.getValueType();
7811 auto *M = cast<MemSDNode>(Op);
7812 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7813
7814 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7815 Op->getVTList(), Ops, VT, M->getMemOperand());
7816 }
7817 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7818 MemSDNode *M = cast<MemSDNode>(Op);
7819 SDValue NodePtr = M->getOperand(2);
7820 SDValue RayExtent = M->getOperand(3);
7821 SDValue RayOrigin = M->getOperand(4);
7822 SDValue RayDir = M->getOperand(5);
7823 SDValue RayInvDir = M->getOperand(6);
7824 SDValue TDescr = M->getOperand(7);
7825
7826 assert(NodePtr.getValueType() == MVT::i32 ||(static_cast <bool> (NodePtr.getValueType() == MVT::i32
|| NodePtr.getValueType() == MVT::i64) ? void (0) : __assert_fail
("NodePtr.getValueType() == MVT::i32 || NodePtr.getValueType() == MVT::i64"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 7827, __extension__
__PRETTY_FUNCTION__))
7827 NodePtr.getValueType() == MVT::i64)(static_cast <bool> (NodePtr.getValueType() == MVT::i32
|| NodePtr.getValueType() == MVT::i64) ? void (0) : __assert_fail
("NodePtr.getValueType() == MVT::i32 || NodePtr.getValueType() == MVT::i64"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 7827, __extension__
__PRETTY_FUNCTION__))
;
7828 assert(RayDir.getValueType() == MVT::v3f16 ||(static_cast <bool> (RayDir.getValueType() == MVT::v3f16
|| RayDir.getValueType() == MVT::v3f32) ? void (0) : __assert_fail
("RayDir.getValueType() == MVT::v3f16 || RayDir.getValueType() == MVT::v3f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 7829, __extension__
__PRETTY_FUNCTION__))
7829 RayDir.getValueType() == MVT::v3f32)(static_cast <bool> (RayDir.getValueType() == MVT::v3f16
|| RayDir.getValueType() == MVT::v3f32) ? void (0) : __assert_fail
("RayDir.getValueType() == MVT::v3f16 || RayDir.getValueType() == MVT::v3f32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 7829, __extension__
__PRETTY_FUNCTION__))
;
7830
7831 if (!Subtarget->hasGFX10_AEncoding()) {
7832 emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7833 return SDValue();
7834 }
7835
7836 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
7837 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7838 const bool Is64 = NodePtr.getValueType() == MVT::i64;
7839 const unsigned NumVDataDwords = 4;
7840 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7841 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
7842 const bool UseNSA =
7843 Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize();
7844 const unsigned BaseOpcodes[2][2] = {
7845 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7846 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7847 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7848 int Opcode;
7849 if (UseNSA) {
7850 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7851 IsGFX11Plus ? AMDGPU::MIMGEncGfx11NSA
7852 : AMDGPU::MIMGEncGfx10NSA,
7853 NumVDataDwords, NumVAddrDwords);
7854 } else {
7855 Opcode =
7856 AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7857 IsGFX11Plus ? AMDGPU::MIMGEncGfx11Default
7858 : AMDGPU::MIMGEncGfx10Default,
7859 NumVDataDwords, NumVAddrDwords);
7860 }
7861 assert(Opcode != -1)(static_cast <bool> (Opcode != -1) ? void (0) : __assert_fail
("Opcode != -1", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7861, __extension__ __PRETTY_FUNCTION__))
;
7862
7863 SmallVector<SDValue, 16> Ops;
7864
7865 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7866 SmallVector<SDValue, 3> Lanes;
7867 DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7868 if (Lanes[0].getValueSizeInBits() == 32) {
7869 for (unsigned I = 0; I < 3; ++I)
7870 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7871 } else {
7872 if (IsAligned) {
7873 Ops.push_back(
7874 DAG.getBitcast(MVT::i32,
7875 DAG.getBuildVector(MVT::v2f16, DL,
7876 { Lanes[0], Lanes[1] })));
7877 Ops.push_back(Lanes[2]);
7878 } else {
7879 SDValue Elt0 = Ops.pop_back_val();
7880 Ops.push_back(
7881 DAG.getBitcast(MVT::i32,
7882 DAG.getBuildVector(MVT::v2f16, DL,
7883 { Elt0, Lanes[0] })));
7884 Ops.push_back(
7885 DAG.getBitcast(MVT::i32,
7886 DAG.getBuildVector(MVT::v2f16, DL,
7887 { Lanes[1], Lanes[2] })));
7888 }
7889 }
7890 };
7891
7892 if (UseNSA && IsGFX11Plus) {
7893 Ops.push_back(NodePtr);
7894 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7895 Ops.push_back(RayOrigin);
7896 if (IsA16) {
7897 SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
7898 DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
7899 DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
7900 for (unsigned I = 0; I < 3; ++I) {
7901 MergedLanes.push_back(DAG.getBitcast(
7902 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
7903 {DirLanes[I], InvDirLanes[I]})));
7904 }
7905 Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
7906 } else {
7907 Ops.push_back(RayDir);
7908 Ops.push_back(RayInvDir);
7909 }
7910 } else {
7911 if (Is64)
7912 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
7913 2);
7914 else
7915 Ops.push_back(NodePtr);
7916
7917 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7918 packLanes(RayOrigin, true);
7919 packLanes(RayDir, true);
7920 packLanes(RayInvDir, false);
7921 }
7922
7923 if (!UseNSA) {
7924 // Build a single vector containing all the operands so far prepared.
7925 if (NumVAddrDwords > 12) {
7926 SDValue Undef = DAG.getUNDEF(MVT::i32);
7927 Ops.append(16 - Ops.size(), Undef);
7928 }
7929 assert(Ops.size() >= 8 && Ops.size() <= 12)(static_cast <bool> (Ops.size() >= 8 && Ops.
size() <= 12) ? void (0) : __assert_fail ("Ops.size() >= 8 && Ops.size() <= 12"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 7929, __extension__
__PRETTY_FUNCTION__))
;
7930 SDValue MergedOps = DAG.getBuildVector(
7931 MVT::getVectorVT(MVT::i32, Ops.size()), DL, Ops);
7932 Ops.clear();
7933 Ops.push_back(MergedOps);
7934 }
7935
7936 Ops.push_back(TDescr);
7937 if (IsA16)
7938 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7939 Ops.push_back(M->getChain());
7940
7941 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7942 MachineMemOperand *MemRef = M->getMemOperand();
7943 DAG.setNodeMemRefs(NewNode, {MemRef});
7944 return SDValue(NewNode, 0);
7945 }
7946 case Intrinsic::amdgcn_global_atomic_fmin:
7947 case Intrinsic::amdgcn_global_atomic_fmax:
7948 case Intrinsic::amdgcn_flat_atomic_fmin:
7949 case Intrinsic::amdgcn_flat_atomic_fmax: {
7950 MemSDNode *M = cast<MemSDNode>(Op);
7951 SDValue Ops[] = {
7952 M->getOperand(0), // Chain
7953 M->getOperand(2), // Ptr
7954 M->getOperand(3) // Value
7955 };
7956 unsigned Opcode = 0;
7957 switch (IntrID) {
7958 case Intrinsic::amdgcn_global_atomic_fmin:
7959 case Intrinsic::amdgcn_flat_atomic_fmin: {
7960 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7961 break;
7962 }
7963 case Intrinsic::amdgcn_global_atomic_fmax:
7964 case Intrinsic::amdgcn_flat_atomic_fmax: {
7965 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7966 break;
7967 }
7968 default:
7969 llvm_unreachable("unhandled atomic opcode")::llvm::llvm_unreachable_internal("unhandled atomic opcode", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 7969)
;
7970 }
7971 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7972 M->getVTList(), Ops, M->getMemoryVT(),
7973 M->getMemOperand());
7974 }
7975 default:
7976
7977 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7978 AMDGPU::getImageDimIntrinsicInfo(IntrID))
7979 return lowerImage(Op, ImageDimIntr, DAG, true);
7980
7981 return SDValue();
7982 }
7983}
7984
7985// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7986// dwordx4 if on SI and handle TFE loads.
7987SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7988 SDVTList VTList,
7989 ArrayRef<SDValue> Ops, EVT MemVT,
7990 MachineMemOperand *MMO,
7991 SelectionDAG &DAG) const {
7992 LLVMContext &C = *DAG.getContext();
7993 MachineFunction &MF = DAG.getMachineFunction();
7994 EVT VT = VTList.VTs[0];
7995
7996 assert(VTList.NumVTs == 2 || VTList.NumVTs == 3)(static_cast <bool> (VTList.NumVTs == 2 || VTList.NumVTs
== 3) ? void (0) : __assert_fail ("VTList.NumVTs == 2 || VTList.NumVTs == 3"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 7996, __extension__
__PRETTY_FUNCTION__))
;
7997 bool IsTFE = VTList.NumVTs == 3;
7998 if (IsTFE) {
7999 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
8000 unsigned NumOpDWords = NumValueDWords + 1;
8001 EVT OpDWordsVT = EVT::getVectorVT(C, MVT::i32, NumOpDWords);
8002 SDVTList OpDWordsVTList = DAG.getVTList(OpDWordsVT, VTList.VTs[2]);
8003 MachineMemOperand *OpDWordsMMO =
8004 MF.getMachineMemOperand(MMO, 0, NumOpDWords * 4);
8005 SDValue Op = getMemIntrinsicNode(Opcode, DL, OpDWordsVTList, Ops,
8006 OpDWordsVT, OpDWordsMMO, DAG);
8007 SDValue Status = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
8008 DAG.getVectorIdxConstant(NumValueDWords, DL));
8009 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
8010 SDValue ValueDWords =
8011 NumValueDWords == 1
8012 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op, ZeroIdx)
8013 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
8014 EVT::getVectorVT(C, MVT::i32, NumValueDWords), Op,
8015 ZeroIdx);
8016 SDValue Value = DAG.getNode(ISD::BITCAST, DL, VT, ValueDWords);
8017 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
8018 }
8019
8020 if (!Subtarget->hasDwordx3LoadStores() &&
8021 (VT == MVT::v3i32 || VT == MVT::v3f32)) {
8022 EVT WidenedVT = EVT::getVectorVT(C, VT.getVectorElementType(), 4);
8023 EVT WidenedMemVT = EVT::getVectorVT(C, MemVT.getVectorElementType(), 4);
8024 MachineMemOperand *WidenedMMO = MF.getMachineMemOperand(MMO, 0, 16);
8025 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
8026 SDValue Op = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
8027 WidenedMemVT, WidenedMMO);
8028 SDValue Value = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Op,
8029 DAG.getVectorIdxConstant(0, DL));
8030 return DAG.getMergeValues({Value, SDValue(Op.getNode(), 1)}, DL);
8031 }
8032
8033 return DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, MemVT, MMO);
8034}
8035
8036SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
8037 bool ImageStore) const {
8038 EVT StoreVT = VData.getValueType();
8039
8040 // No change for f16 and legal vector D16 types.
8041 if (!StoreVT.isVector())
8042 return VData;
8043
8044 SDLoc DL(VData);
8045 unsigned NumElements = StoreVT.getVectorNumElements();
8046
8047 if (Subtarget->hasUnpackedD16VMem()) {
8048 // We need to unpack the packed data to store.
8049 EVT IntStoreVT = StoreVT.changeTypeToInteger();
8050 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
8051
8052 EVT EquivStoreVT =
8053 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
8054 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
8055 return DAG.UnrollVectorOp(ZExt.getNode());
8056 }
8057
8058 // The sq block of gfx8.1 does not estimate register use correctly for d16
8059 // image store instructions. The data operand is computed as if it were not a
8060 // d16 image instruction.
8061 if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
8062 // Bitcast to i16
8063 EVT IntStoreVT = StoreVT.changeTypeToInteger();
8064 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
8065
8066 // Decompose into scalars
8067 SmallVector<SDValue, 4> Elts;
8068 DAG.ExtractVectorElements(IntVData, Elts);
8069
8070 // Group pairs of i16 into v2i16 and bitcast to i32
8071 SmallVector<SDValue, 4> PackedElts;
8072 for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
8073 SDValue Pair =
8074 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
8075 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
8076 PackedElts.push_back(IntPair);
8077 }
8078 if ((NumElements % 2) == 1) {
8079 // Handle v3i16
8080 unsigned I = Elts.size() / 2;
8081 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
8082 {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
8083 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
8084 PackedElts.push_back(IntPair);
8085 }
8086
8087 // Pad using UNDEF
8088 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
8089
8090 // Build final vector
8091 EVT VecVT =
8092 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
8093 return DAG.getBuildVector(VecVT, DL, PackedElts);
8094 }
8095
8096 if (NumElements == 3) {
8097 EVT IntStoreVT =
8098 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
8099 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
8100
8101 EVT WidenedStoreVT = EVT::getVectorVT(
8102 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
8103 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
8104 WidenedStoreVT.getStoreSizeInBits());
8105 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
8106 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
8107 }
8108
8109 assert(isTypeLegal(StoreVT))(static_cast <bool> (isTypeLegal(StoreVT)) ? void (0) :
__assert_fail ("isTypeLegal(StoreVT)", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8109, __extension__ __PRETTY_FUNCTION__))
;
8110 return VData;
8111}
8112
8113SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8114 SelectionDAG &DAG) const {
8115 SDLoc DL(Op);
8116 SDValue Chain = Op.getOperand(0);
8117 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8118 MachineFunction &MF = DAG.getMachineFunction();
8119
8120 switch (IntrinsicID) {
8121 case Intrinsic::amdgcn_exp_compr: {
8122 if (!Subtarget->hasCompressedExport()) {
8123 DiagnosticInfoUnsupported BadIntrin(
8124 DAG.getMachineFunction().getFunction(),
8125 "intrinsic not supported on subtarget", DL.getDebugLoc());
8126 DAG.getContext()->diagnose(BadIntrin);
8127 }
8128 SDValue Src0 = Op.getOperand(4);
8129 SDValue Src1 = Op.getOperand(5);
8130 // Hack around illegal type on SI by directly selecting it.
8131 if (isTypeLegal(Src0.getValueType()))
8132 return SDValue();
8133
8134 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
8135 SDValue Undef = DAG.getUNDEF(MVT::f32);
8136 const SDValue Ops[] = {
8137 Op.getOperand(2), // tgt
8138 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
8139 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
8140 Undef, // src2
8141 Undef, // src3
8142 Op.getOperand(7), // vm
8143 DAG.getTargetConstant(1, DL, MVT::i1), // compr
8144 Op.getOperand(3), // en
8145 Op.getOperand(0) // Chain
8146 };
8147
8148 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
8149 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
8150 }
8151 case Intrinsic::amdgcn_s_barrier: {
8152 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
8153 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
8154 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
8155 if (WGSize <= ST.getWavefrontSize())
8156 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
8157 Op.getOperand(0)), 0);
8158 }
8159 return SDValue();
8160 };
8161 case Intrinsic::amdgcn_tbuffer_store: {
8162 SDValue VData = Op.getOperand(2);
8163 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8164 if (IsD16)
8165 VData = handleD16VData(VData, DAG);
8166 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
8167 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
8168 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
8169 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
8170 unsigned IdxEn = getIdxEn(Op.getOperand(4));
8171 SDValue Ops[] = {
8172 Chain,
8173 VData, // vdata
8174 Op.getOperand(3), // rsrc
8175 Op.getOperand(4), // vindex
8176 Op.getOperand(5), // voffset
8177 Op.getOperand(6), // soffset
8178 Op.getOperand(7), // offset
8179 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8180 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8181 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8182 };
8183 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8184 AMDGPUISD::TBUFFER_STORE_FORMAT;
8185 MemSDNode *M = cast<MemSDNode>(Op);
8186 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8187 M->getMemoryVT(), M->getMemOperand());
8188 }
8189
8190 case Intrinsic::amdgcn_struct_tbuffer_store: {
8191 SDValue VData = Op.getOperand(2);
8192 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8193 if (IsD16)
8194 VData = handleD16VData(VData, DAG);
8195 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8196 SDValue Ops[] = {
8197 Chain,
8198 VData, // vdata
8199 Op.getOperand(3), // rsrc
8200 Op.getOperand(4), // vindex
8201 Offsets.first, // voffset
8202 Op.getOperand(6), // soffset
8203 Offsets.second, // offset
8204 Op.getOperand(7), // format
8205 Op.getOperand(8), // cachepolicy, swizzled buffer
8206 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8207 };
8208 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8209 AMDGPUISD::TBUFFER_STORE_FORMAT;
8210 MemSDNode *M = cast<MemSDNode>(Op);
8211 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8212 M->getMemoryVT(), M->getMemOperand());
8213 }
8214
8215 case Intrinsic::amdgcn_raw_tbuffer_store: {
8216 SDValue VData = Op.getOperand(2);
8217 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8218 if (IsD16)
8219 VData = handleD16VData(VData, DAG);
8220 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8221 SDValue Ops[] = {
8222 Chain,
8223 VData, // vdata
8224 Op.getOperand(3), // rsrc
8225 DAG.getConstant(0, DL, MVT::i32), // vindex
8226 Offsets.first, // voffset
8227 Op.getOperand(5), // soffset
8228 Offsets.second, // offset
8229 Op.getOperand(6), // format
8230 Op.getOperand(7), // cachepolicy, swizzled buffer
8231 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8232 };
8233 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8234 AMDGPUISD::TBUFFER_STORE_FORMAT;
8235 MemSDNode *M = cast<MemSDNode>(Op);
8236 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8237 M->getMemoryVT(), M->getMemOperand());
8238 }
8239
8240 case Intrinsic::amdgcn_buffer_store:
8241 case Intrinsic::amdgcn_buffer_store_format: {
8242 SDValue VData = Op.getOperand(2);
8243 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8244 if (IsD16)
8245 VData = handleD16VData(VData, DAG);
8246 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8247 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8248 unsigned IdxEn = getIdxEn(Op.getOperand(4));
8249 SDValue Ops[] = {
8250 Chain,
8251 VData,
8252 Op.getOperand(3), // rsrc
8253 Op.getOperand(4), // vindex
8254 SDValue(), // voffset -- will be set by setBufferOffsets
8255 SDValue(), // soffset -- will be set by setBufferOffsets
8256 SDValue(), // offset -- will be set by setBufferOffsets
8257 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8258 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8259 };
8260 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8261
8262 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8263 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8264 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8265 MemSDNode *M = cast<MemSDNode>(Op);
8266 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8267
8268 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8269 EVT VDataType = VData.getValueType().getScalarType();
8270 if (VDataType == MVT::i8 || VDataType == MVT::i16)
8271 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8272
8273 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8274 M->getMemoryVT(), M->getMemOperand());
8275 }
8276
8277 case Intrinsic::amdgcn_raw_buffer_store:
8278 case Intrinsic::amdgcn_raw_buffer_store_format: {
8279 const bool IsFormat =
8280 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8281
8282 SDValue VData = Op.getOperand(2);
8283 EVT VDataVT = VData.getValueType();
8284 EVT EltType = VDataVT.getScalarType();
8285 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8286 if (IsD16) {
8287 VData = handleD16VData(VData, DAG);
8288 VDataVT = VData.getValueType();
8289 }
8290
8291 if (!isTypeLegal(VDataVT)) {
8292 VData =
8293 DAG.getNode(ISD::BITCAST, DL,
8294 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8295 }
8296
8297 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8298 SDValue Ops[] = {
8299 Chain,
8300 VData,
8301 Op.getOperand(3), // rsrc
8302 DAG.getConstant(0, DL, MVT::i32), // vindex
8303 Offsets.first, // voffset
8304 Op.getOperand(5), // soffset
8305 Offsets.second, // offset
8306 Op.getOperand(6), // cachepolicy, swizzled buffer
8307 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8308 };
8309 unsigned Opc =
8310 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8311 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8312 MemSDNode *M = cast<MemSDNode>(Op);
8313 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8314
8315 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8316 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8317 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8318
8319 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8320 M->getMemoryVT(), M->getMemOperand());
8321 }
8322
8323 case Intrinsic::amdgcn_struct_buffer_store:
8324 case Intrinsic::amdgcn_struct_buffer_store_format: {
8325 const bool IsFormat =
8326 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8327
8328 SDValue VData = Op.getOperand(2);
8329 EVT VDataVT = VData.getValueType();
8330 EVT EltType = VDataVT.getScalarType();
8331 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8332
8333 if (IsD16) {
8334 VData = handleD16VData(VData, DAG);
8335 VDataVT = VData.getValueType();
8336 }
8337
8338 if (!isTypeLegal(VDataVT)) {
8339 VData =
8340 DAG.getNode(ISD::BITCAST, DL,
8341 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8342 }
8343
8344 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8345 SDValue Ops[] = {
8346 Chain,
8347 VData,
8348 Op.getOperand(3), // rsrc
8349 Op.getOperand(4), // vindex
8350 Offsets.first, // voffset
8351 Op.getOperand(6), // soffset
8352 Offsets.second, // offset
8353 Op.getOperand(7), // cachepolicy, swizzled buffer
8354 DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8355 };
8356 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8357 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8358 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8359 MemSDNode *M = cast<MemSDNode>(Op);
8360 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8361
8362 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8363 EVT VDataType = VData.getValueType().getScalarType();
8364 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8365 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8366
8367 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8368 M->getMemoryVT(), M->getMemOperand());
8369 }
8370 case Intrinsic::amdgcn_raw_buffer_load_lds:
8371 case Intrinsic::amdgcn_struct_buffer_load_lds: {
8372 unsigned Opc;
8373 bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds;
8374 unsigned OpOffset = HasVIndex ? 1 : 0;
8375 SDValue VOffset = Op.getOperand(5 + OpOffset);
8376 auto CVOffset = dyn_cast<ConstantSDNode>(VOffset);
8377 bool HasVOffset = !CVOffset || !CVOffset->isZero();
8378 unsigned Size = Op->getConstantOperandVal(4);
8379
8380 switch (Size) {
8381 default:
8382 return SDValue();
8383 case 1:
8384 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
8385 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
8386 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
8387 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
8388 break;
8389 case 2:
8390 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
8391 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
8392 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
8393 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
8394 break;
8395 case 4:
8396 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
8397 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
8398 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
8399 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
8400 break;
8401 }
8402
8403 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8404
8405 SmallVector<SDValue, 8> Ops;
8406
8407 if (HasVIndex && HasVOffset)
8408 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
8409 { Op.getOperand(5), // VIndex
8410 VOffset }));
8411 else if (HasVIndex)
8412 Ops.push_back(Op.getOperand(5));
8413 else if (HasVOffset)
8414 Ops.push_back(VOffset);
8415
8416 Ops.push_back(Op.getOperand(2)); // rsrc
8417 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
8418 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
8419 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
8420 Ops.push_back(
8421 DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
8422 Ops.push_back(
8423 DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8)); // swz
8424 Ops.push_back(M0Val.getValue(0)); // Chain
8425 Ops.push_back(M0Val.getValue(1)); // Glue
8426
8427 auto *M = cast<MemSDNode>(Op);
8428 MachineMemOperand *LoadMMO = M->getMemOperand();
8429 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8430 LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset);
8431 MachinePointerInfo StorePtrI = LoadPtrI;
8432 StorePtrI.V = nullptr;
8433 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8434
8435 auto F = LoadMMO->getFlags() &
8436 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8437 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8438 Size, LoadMMO->getBaseAlign());
8439
8440 MachineMemOperand *StoreMMO =
8441 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8442 sizeof(int32_t), LoadMMO->getBaseAlign());
8443
8444 auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
8445 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8446
8447 return SDValue(Load, 0);
8448 }
8449 case Intrinsic::amdgcn_global_load_lds: {
8450 unsigned Opc;
8451 unsigned Size = Op->getConstantOperandVal(4);
8452 switch (Size) {
8453 default:
8454 return SDValue();
8455 case 1:
8456 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
8457 break;
8458 case 2:
8459 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
8460 break;
8461 case 4:
8462 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
8463 break;
8464 }
8465
8466 auto *M = cast<MemSDNode>(Op);
8467 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8468
8469 SmallVector<SDValue, 6> Ops;
8470
8471 SDValue Addr = Op.getOperand(2); // Global ptr
8472 SDValue VOffset;
8473 // Try to split SAddr and VOffset. Global and LDS pointers share the same
8474 // immediate offset, so we cannot use a regular SelectGlobalSAddr().
8475 if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
8476 SDValue LHS = Addr.getOperand(0);
8477 SDValue RHS = Addr.getOperand(1);
8478
8479 if (LHS->isDivergent())
8480 std::swap(LHS, RHS);
8481
8482 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
8483 RHS.getOperand(0).getValueType() == MVT::i32) {
8484 // add (i64 sgpr), (zero_extend (i32 vgpr))
8485 Addr = LHS;
8486 VOffset = RHS.getOperand(0);
8487 }
8488 }
8489
8490 Ops.push_back(Addr);
8491 if (!Addr->isDivergent()) {
8492 Opc = AMDGPU::getGlobalSaddrOp(Opc);
8493 if (!VOffset)
8494 VOffset = SDValue(
8495 DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
8496 DAG.getTargetConstant(0, DL, MVT::i32)), 0);
8497 Ops.push_back(VOffset);
8498 }
8499
8500 Ops.push_back(Op.getOperand(5)); // Offset
8501 Ops.push_back(Op.getOperand(6)); // CPol
8502 Ops.push_back(M0Val.getValue(0)); // Chain
8503 Ops.push_back(M0Val.getValue(1)); // Glue
8504
8505 MachineMemOperand *LoadMMO = M->getMemOperand();
8506 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8507 LoadPtrI.Offset = Op->getConstantOperandVal(5);
8508 MachinePointerInfo StorePtrI = LoadPtrI;
8509 LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
8510 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8511 auto F = LoadMMO->getFlags() &
8512 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8513 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8514 Size, LoadMMO->getBaseAlign());
8515 MachineMemOperand *StoreMMO =
8516 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8517 sizeof(int32_t), Align(4));
8518
8519 auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8520 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8521
8522 return SDValue(Load, 0);
8523 }
8524 case Intrinsic::amdgcn_end_cf:
8525 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8526 Op->getOperand(2), Chain), 0);
8527
8528 default: {
8529 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8530 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8531 return lowerImage(Op, ImageDimIntr, DAG, true);
8532
8533 return Op;
8534 }
8535 }
8536}
8537
8538// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8539// offset (the offset that is included in bounds checking and swizzling, to be
8540// split between the instruction's voffset and immoffset fields) and soffset
8541// (the offset that is excluded from bounds checking and swizzling, to go in
8542// the instruction's soffset field). This function takes the first kind of
8543// offset and figures out how to split it between voffset and immoffset.
8544std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8545 SDValue Offset, SelectionDAG &DAG) const {
8546 SDLoc DL(Offset);
8547 const unsigned MaxImm = SIInstrInfo::getMaxMUBUFImmOffset();
8548 SDValue N0 = Offset;
8549 ConstantSDNode *C1 = nullptr;
8550
8551 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8552 N0 = SDValue();
8553 else if (DAG.isBaseWithConstantOffset(N0)) {
8554 C1 = cast<ConstantSDNode>(N0.getOperand(1));
8555 N0 = N0.getOperand(0);
8556 }
8557
8558 if (C1) {
8559 unsigned ImmOffset = C1->getZExtValue();
8560 // If the immediate value is too big for the immoffset field, put only bits
8561 // that would normally fit in the immoffset field. The remaining value that
8562 // is copied/added for the voffset field is a large power of 2, and it
8563 // stands more chance of being CSEd with the copy/add for another similar
8564 // load/store.
8565 // However, do not do that rounding down if that is a negative
8566 // number, as it appears to be illegal to have a negative offset in the
8567 // vgpr, even if adding the immediate offset makes it positive.
8568 unsigned Overflow = ImmOffset & ~MaxImm;
8569 ImmOffset -= Overflow;
8570 if ((int32_t)Overflow < 0) {
8571 Overflow += ImmOffset;
8572 ImmOffset = 0;
8573 }
8574 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8575 if (Overflow) {
8576 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8577 if (!N0)
8578 N0 = OverflowVal;
8579 else {
8580 SDValue Ops[] = { N0, OverflowVal };
8581 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8582 }
8583 }
8584 }
8585 if (!N0)
8586 N0 = DAG.getConstant(0, DL, MVT::i32);
8587 if (!C1)
8588 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8589 return {N0, SDValue(C1, 0)};
8590}
8591
8592// Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8593// three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8594// pointed to by Offsets.
8595void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8596 SelectionDAG &DAG, SDValue *Offsets,
8597 Align Alignment) const {
8598 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8599 SDLoc DL(CombinedOffset);
8600 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8601 uint32_t Imm = C->getZExtValue();
8602 uint32_t SOffset, ImmOffset;
8603 if (TII->splitMUBUFOffset(Imm, SOffset, ImmOffset, Alignment)) {
8604 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8605 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8606 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8607 return;
8608 }
8609 }
8610 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8611 SDValue N0 = CombinedOffset.getOperand(0);
8612 SDValue N1 = CombinedOffset.getOperand(1);
8613 uint32_t SOffset, ImmOffset;
8614 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8615 if (Offset >= 0 &&
8616 TII->splitMUBUFOffset(Offset, SOffset, ImmOffset, Alignment)) {
8617 Offsets[0] = N0;
8618 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8619 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8620 return;
8621 }
8622 }
8623 Offsets[0] = CombinedOffset;
8624 Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8625 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8626}
8627
8628// Handle 8 bit and 16 bit buffer loads
8629SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8630 EVT LoadVT, SDLoc DL,
8631 ArrayRef<SDValue> Ops,
8632 MemSDNode *M) const {
8633 EVT IntVT = LoadVT.changeTypeToInteger();
8634 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8635 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8636
8637 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8638 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8639 Ops, IntVT,
8640 M->getMemOperand());
8641 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8642 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8643
8644 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8645}
8646
8647// Handle 8 bit and 16 bit buffer stores
8648SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8649 EVT VDataType, SDLoc DL,
8650 SDValue Ops[],
8651 MemSDNode *M) const {
8652 if (VDataType == MVT::f16)
8653 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8654
8655 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8656 Ops[1] = BufferStoreExt;
8657 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8658 AMDGPUISD::BUFFER_STORE_SHORT;
8659 ArrayRef<SDValue> OpsRef = ArrayRef(&Ops[0], 9);
8660 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8661 M->getMemOperand());
8662}
8663
8664static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8665 ISD::LoadExtType ExtType, SDValue Op,
8666 const SDLoc &SL, EVT VT) {
8667 if (VT.bitsLT(Op.getValueType()))
8668 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8669
8670 switch (ExtType) {
8671 case ISD::SEXTLOAD:
8672 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8673 case ISD::ZEXTLOAD:
8674 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8675 case ISD::EXTLOAD:
8676 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8677 case ISD::NON_EXTLOAD:
8678 return Op;
8679 }
8680
8681 llvm_unreachable("invalid ext type")::llvm::llvm_unreachable_internal("invalid ext type", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8681)
;
8682}
8683
8684SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8685 SelectionDAG &DAG = DCI.DAG;
8686 if (Ld->getAlign() < Align(4) || Ld->isDivergent())
8687 return SDValue();
8688
8689 // FIXME: Constant loads should all be marked invariant.
8690 unsigned AS = Ld->getAddressSpace();
8691 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8692 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8693 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8694 return SDValue();
8695
8696 // Don't do this early, since it may interfere with adjacent load merging for
8697 // illegal types. We can avoid losing alignment information for exotic types
8698 // pre-legalize.
8699 EVT MemVT = Ld->getMemoryVT();
8700 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8701 MemVT.getSizeInBits() >= 32)
8702 return SDValue();
8703
8704 SDLoc SL(Ld);
8705
8706 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&(static_cast <bool> ((!MemVT.isVector() || Ld->getExtensionType
() == ISD::NON_EXTLOAD) && "unexpected vector extload"
) ? void (0) : __assert_fail ("(!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && \"unexpected vector extload\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8707, __extension__
__PRETTY_FUNCTION__))
8707 "unexpected vector extload")(static_cast <bool> ((!MemVT.isVector() || Ld->getExtensionType
() == ISD::NON_EXTLOAD) && "unexpected vector extload"
) ? void (0) : __assert_fail ("(!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && \"unexpected vector extload\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8707, __extension__
__PRETTY_FUNCTION__))
;
8708
8709 // TODO: Drop only high part of range.
8710 SDValue Ptr = Ld->getBasePtr();
8711 SDValue NewLoad = DAG.getLoad(
8712 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
8713 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
8714 Ld->getMemOperand()->getFlags(), Ld->getAAInfo(),
8715 nullptr); // Drop ranges
8716
8717 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8718 if (MemVT.isFloatingPoint()) {
8719 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&(static_cast <bool> (Ld->getExtensionType() == ISD::
NON_EXTLOAD && "unexpected fp extload") ? void (0) : __assert_fail
("Ld->getExtensionType() == ISD::NON_EXTLOAD && \"unexpected fp extload\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8720, __extension__
__PRETTY_FUNCTION__))
8720 "unexpected fp extload")(static_cast <bool> (Ld->getExtensionType() == ISD::
NON_EXTLOAD && "unexpected fp extload") ? void (0) : __assert_fail
("Ld->getExtensionType() == ISD::NON_EXTLOAD && \"unexpected fp extload\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8720, __extension__
__PRETTY_FUNCTION__))
;
8721 TruncVT = MemVT.changeTypeToInteger();
8722 }
8723
8724 SDValue Cvt = NewLoad;
8725 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8726 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8727 DAG.getValueType(TruncVT));
8728 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8729 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8730 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8731 } else {
8732 assert(Ld->getExtensionType() == ISD::EXTLOAD)(static_cast <bool> (Ld->getExtensionType() == ISD::
EXTLOAD) ? void (0) : __assert_fail ("Ld->getExtensionType() == ISD::EXTLOAD"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8732, __extension__
__PRETTY_FUNCTION__))
;
8733 }
8734
8735 EVT VT = Ld->getValueType(0);
8736 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8737
8738 DCI.AddToWorklist(Cvt.getNode());
8739
8740 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8741 // the appropriate extension from the 32-bit load.
8742 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8743 DCI.AddToWorklist(Cvt.getNode());
8744
8745 // Handle conversion back to floating point if necessary.
8746 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8747
8748 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8749}
8750
8751static bool addressMayBeAccessedAsPrivate(const MachineMemOperand *MMO,
8752 const SIMachineFunctionInfo &Info) {
8753 // TODO: Should check if the address can definitely not access stack.
8754 if (Info.isEntryFunction())
8755 return Info.hasFlatScratchInit();
8756 return true;
8757}
8758
8759SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8760 SDLoc DL(Op);
8761 LoadSDNode *Load = cast<LoadSDNode>(Op);
8762 ISD::LoadExtType ExtType = Load->getExtensionType();
8763 EVT MemVT = Load->getMemoryVT();
8764
8765 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8766 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8767 return SDValue();
8768
8769 // FIXME: Copied from PPC
8770 // First, load into 32 bits, then truncate to 1 bit.
8771
8772 SDValue Chain = Load->getChain();
8773 SDValue BasePtr = Load->getBasePtr();
8774 MachineMemOperand *MMO = Load->getMemOperand();
8775
8776 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8777
8778 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8779 BasePtr, RealMemVT, MMO);
8780
8781 if (!MemVT.isVector()) {
8782 SDValue Ops[] = {
8783 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8784 NewLD.getValue(1)
8785 };
8786
8787 return DAG.getMergeValues(Ops, DL);
8788 }
8789
8790 SmallVector<SDValue, 3> Elts;
8791 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8792 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8793 DAG.getConstant(I, DL, MVT::i32));
8794
8795 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8796 }
8797
8798 SDValue Ops[] = {
8799 DAG.getBuildVector(MemVT, DL, Elts),
8800 NewLD.getValue(1)
8801 };
8802
8803 return DAG.getMergeValues(Ops, DL);
8804 }
8805
8806 if (!MemVT.isVector())
8807 return SDValue();
8808
8809 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&(static_cast <bool> (Op.getValueType().getVectorElementType
() == MVT::i32 && "Custom lowering for non-i32 vectors hasn't been implemented."
) ? void (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8810, __extension__
__PRETTY_FUNCTION__))
8810 "Custom lowering for non-i32 vectors hasn't been implemented.")(static_cast <bool> (Op.getValueType().getVectorElementType
() == MVT::i32 && "Custom lowering for non-i32 vectors hasn't been implemented."
) ? void (0) : __assert_fail ("Op.getValueType().getVectorElementType() == MVT::i32 && \"Custom lowering for non-i32 vectors hasn't been implemented.\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8810, __extension__
__PRETTY_FUNCTION__))
;
8811
8812 Align Alignment = Load->getAlign();
8813 unsigned AS = Load->getAddressSpace();
8814 if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS &&
8815 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8816 return SplitVectorLoad(Op, DAG);
8817 }
8818
8819 MachineFunction &MF = DAG.getMachineFunction();
8820 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8821 // If there is a possibility that flat instruction access scratch memory
8822 // then we need to use the same legalization rules we use for private.
8823 if (AS == AMDGPUAS::FLAT_ADDRESS &&
8824 !Subtarget->hasMultiDwordFlatScratchAddressing())
8825 AS = addressMayBeAccessedAsPrivate(Load->getMemOperand(), *MFI) ?
8826 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8827
8828 unsigned NumElements = MemVT.getVectorNumElements();
8829
8830 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8831 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8832 if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) {
8833 if (MemVT.isPow2VectorType())
8834 return SDValue();
8835 return WidenOrSplitVectorLoad(Op, DAG);
8836 }
8837 // Non-uniform loads will be selected to MUBUF instructions, so they
8838 // have the same legalization requirements as global and private
8839 // loads.
8840 //
8841 }
8842
8843 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8844 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8845 AS == AMDGPUAS::GLOBAL_ADDRESS) {
8846 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8847 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8848 Alignment >= Align(4) && NumElements < 32) {
8849 if (MemVT.isPow2VectorType())
8850 return SDValue();
8851 return WidenOrSplitVectorLoad(Op, DAG);
8852 }
8853 // Non-uniform loads will be selected to MUBUF instructions, so they
8854 // have the same legalization requirements as global and private
8855 // loads.
8856 //
8857 }
8858 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8859 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8860 AS == AMDGPUAS::GLOBAL_ADDRESS ||
8861 AS == AMDGPUAS::FLAT_ADDRESS) {
8862 if (NumElements > 4)
8863 return SplitVectorLoad(Op, DAG);
8864 // v3 loads not supported on SI.
8865 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8866 return WidenOrSplitVectorLoad(Op, DAG);
8867
8868 // v3 and v4 loads are supported for private and global memory.
8869 return SDValue();
8870 }
8871 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8872 // Depending on the setting of the private_element_size field in the
8873 // resource descriptor, we can only make private accesses up to a certain
8874 // size.
8875 switch (Subtarget->getMaxPrivateElementSize()) {
8876 case 4: {
8877 SDValue Ops[2];
8878 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8879 return DAG.getMergeValues(Ops, DL);
8880 }
8881 case 8:
8882 if (NumElements > 2)
8883 return SplitVectorLoad(Op, DAG);
8884 return SDValue();
8885 case 16:
8886 // Same as global/flat
8887 if (NumElements > 4)
8888 return SplitVectorLoad(Op, DAG);
8889 // v3 loads not supported on SI.
8890 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8891 return WidenOrSplitVectorLoad(Op, DAG);
8892
8893 return SDValue();
8894 default:
8895 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 8895)
;
8896 }
8897 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8898 unsigned Fast = 0;
8899 auto Flags = Load->getMemOperand()->getFlags();
8900 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8901 Load->getAlign(), Flags, &Fast) &&
8902 Fast > 1)
8903 return SDValue();
8904
8905 if (MemVT.isVector())
8906 return SplitVectorLoad(Op, DAG);
8907 }
8908
8909 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8910 MemVT, *Load->getMemOperand())) {
8911 SDValue Ops[2];
8912 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8913 return DAG.getMergeValues(Ops, DL);
8914 }
8915
8916 return SDValue();
8917}
8918
8919SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8920 EVT VT = Op.getValueType();
8921 if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
8922 return splitTernaryVectorOp(Op, DAG);
8923
8924 assert(VT.getSizeInBits() == 64)(static_cast <bool> (VT.getSizeInBits() == 64) ? void (
0) : __assert_fail ("VT.getSizeInBits() == 64", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 8924, __extension__ __PRETTY_FUNCTION__))
;
8925
8926 SDLoc DL(Op);
8927 SDValue Cond = Op.getOperand(0);
8928
8929 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8930 SDValue One = DAG.getConstant(1, DL, MVT::i32);
8931
8932 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8933 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8934
8935 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8936 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8937
8938 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8939
8940 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8941 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8942
8943 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8944
8945 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8946 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8947}
8948
8949// Catch division cases where we can use shortcuts with rcp and rsq
8950// instructions.
8951SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8952 SelectionDAG &DAG) const {
8953 SDLoc SL(Op);
8954 SDValue LHS = Op.getOperand(0);
8955 SDValue RHS = Op.getOperand(1);
8956 EVT VT = Op.getValueType();
8957 const SDNodeFlags Flags = Op->getFlags();
8958
8959 bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8960
8961 // Without !fpmath accuracy information, we can't do more because we don't
8962 // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8963 if (!AllowInaccurateRcp)
8964 return SDValue();
8965
8966 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8967 if (CLHS->isExactlyValue(1.0)) {
8968 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8969 // the CI documentation has a worst case error of 1 ulp.
8970 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8971 // use it as long as we aren't trying to use denormals.
8972 //
8973 // v_rcp_f16 and v_rsq_f16 DO support denormals.
8974
8975 // 1.0 / sqrt(x) -> rsq(x)
8976
8977 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8978 // error seems really high at 2^29 ULP.
8979 if (RHS.getOpcode() == ISD::FSQRT)
8980 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8981
8982 // 1.0 / x -> rcp(x)
8983 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8984 }
8985
8986 // Same as for 1.0, but expand the sign out of the constant.
8987 if (CLHS->isExactlyValue(-1.0)) {
8988 // -1.0 / x -> rcp (fneg x)
8989 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8990 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8991 }
8992 }
8993
8994 // Turn into multiply by the reciprocal.
8995 // x / y -> x * (1.0 / y)
8996 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8997 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8998}
8999
9000SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
9001 SelectionDAG &DAG) const {
9002 SDLoc SL(Op);
9003 SDValue X = Op.getOperand(0);
9004 SDValue Y = Op.getOperand(1);
9005 EVT VT = Op.getValueType();
9006 const SDNodeFlags Flags = Op->getFlags();
9007
9008 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
9009 DAG.getTarget().Options.UnsafeFPMath;
9010 if (!AllowInaccurateDiv)
9011 return SDValue();
9012
9013 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
9014 SDValue One = DAG.getConstantFP(1.0, SL, VT);
9015
9016 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
9017 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
9018
9019 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
9020 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
9021 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
9022 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
9023 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
9024 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
9025}
9026
9027static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
9028 EVT VT, SDValue A, SDValue B, SDValue GlueChain,
9029 SDNodeFlags Flags) {
9030 if (GlueChain->getNumValues() <= 1) {
9031 return DAG.getNode(Opcode, SL, VT, A, B, Flags);
9032 }
9033
9034 assert(GlueChain->getNumValues() == 3)(static_cast <bool> (GlueChain->getNumValues() == 3)
? void (0) : __assert_fail ("GlueChain->getNumValues() == 3"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9034, __extension__
__PRETTY_FUNCTION__))
;
9035
9036 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
9037 switch (Opcode) {
9038 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9038)
;
9039 case ISD::FMUL:
9040 Opcode = AMDGPUISD::FMUL_W_CHAIN;
9041 break;
9042 }
9043
9044 return DAG.getNode(Opcode, SL, VTList,
9045 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
9046 Flags);
9047}
9048
9049static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
9050 EVT VT, SDValue A, SDValue B, SDValue C,
9051 SDValue GlueChain, SDNodeFlags Flags) {
9052 if (GlueChain->getNumValues() <= 1) {
9053 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
9054 }
9055
9056 assert(GlueChain->getNumValues() == 3)(static_cast <bool> (GlueChain->getNumValues() == 3)
? void (0) : __assert_fail ("GlueChain->getNumValues() == 3"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9056, __extension__
__PRETTY_FUNCTION__))
;
9057
9058 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
9059 switch (Opcode) {
9060 default: llvm_unreachable("no chain equivalent for opcode")::llvm::llvm_unreachable_internal("no chain equivalent for opcode"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9060)
;
9061 case ISD::FMA:
9062 Opcode = AMDGPUISD::FMA_W_CHAIN;
9063 break;
9064 }
9065
9066 return DAG.getNode(Opcode, SL, VTList,
9067 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
9068 Flags);
9069}
9070
9071SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
9072 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
9073 return FastLowered;
9074
9075 SDLoc SL(Op);
9076 SDValue Src0 = Op.getOperand(0);
9077 SDValue Src1 = Op.getOperand(1);
9078
9079 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
9080 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
9081
9082 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
9083 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
9084
9085 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
9086 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
9087
9088 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
9089}
9090
9091// Faster 2.5 ULP division that does not support denormals.
9092SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
9093 SDLoc SL(Op);
9094 SDValue LHS = Op.getOperand(1);
9095 SDValue RHS = Op.getOperand(2);
9096
9097 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
9098
9099 const APFloat K0Val(llvm::bit_cast<float>(0x6f800000));
9100 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
9101
9102 const APFloat K1Val(llvm::bit_cast<float>(0x2f800000));
9103 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
9104
9105 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
9106
9107 EVT SetCCVT =
9108 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
9109
9110 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
9111
9112 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
9113
9114 // TODO: Should this propagate fast-math-flags?
9115 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
9116
9117 // rcp does not support denormals.
9118 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
9119
9120 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
9121
9122 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
9123}
9124
9125// Returns immediate value for setting the F32 denorm mode when using the
9126// S_DENORM_MODE instruction.
9127static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
9128 const SDLoc &SL, const GCNSubtarget *ST) {
9129 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE")(static_cast <bool> (ST->hasDenormModeInst() &&
"Requires S_DENORM_MODE") ? void (0) : __assert_fail ("ST->hasDenormModeInst() && \"Requires S_DENORM_MODE\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9129, __extension__
__PRETTY_FUNCTION__))
;
9130 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
9131 ? FP_DENORM_FLUSH_NONE3
9132 : FP_DENORM_FLUSH_IN_FLUSH_OUT0;
9133
9134 int Mode = SPDenormMode | (DPDenormModeDefault << 2);
9135 return DAG.getTargetConstant(Mode, SL, MVT::i32);
9136}
9137
9138SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
9139 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
9140 return FastLowered;
9141
9142 // The selection matcher assumes anything with a chain selecting to a
9143 // mayRaiseFPException machine instruction. Since we're introducing a chain
9144 // here, we need to explicitly report nofpexcept for the regular fdiv
9145 // lowering.
9146 SDNodeFlags Flags = Op->getFlags();
9147 Flags.setNoFPExcept(true);
9148
9149 SDLoc SL(Op);
9150 SDValue LHS = Op.getOperand(0);
9151 SDValue RHS = Op.getOperand(1);
9152
9153 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
9154
9155 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
9156
9157 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
9158 {RHS, RHS, LHS}, Flags);
9159 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
9160 {LHS, RHS, LHS}, Flags);
9161
9162 // Denominator is scaled to not be denormal, so using rcp is ok.
9163 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
9164 DenominatorScaled, Flags);
9165 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
9166 DenominatorScaled, Flags);
9167
9168 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
9169 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
9170 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
9171 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
9172
9173 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
9174
9175 if (!HasFP32Denormals) {
9176 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
9177 // lowering. The chain dependence is insufficient, and we need glue. We do
9178 // not need the glue variants in a strictfp function.
9179
9180 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
9181
9182 SDNode *EnableDenorm;
9183 if (Subtarget->hasDenormModeInst()) {
9184 const SDValue EnableDenormValue =
9185 getSPDenormModeValue(FP_DENORM_FLUSH_NONE3, DAG, SL, Subtarget);
9186
9187 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
9188 DAG.getEntryNode(), EnableDenormValue).getNode();
9189 } else {
9190 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE3,
9191 SL, MVT::i32);
9192 EnableDenorm =
9193 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
9194 {EnableDenormValue, BitField, DAG.getEntryNode()});
9195 }
9196
9197 SDValue Ops[3] = {
9198 NegDivScale0,
9199 SDValue(EnableDenorm, 0),
9200 SDValue(EnableDenorm, 1)
9201 };
9202
9203 NegDivScale0 = DAG.getMergeValues(Ops, SL);
9204 }
9205
9206 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
9207 ApproxRcp, One, NegDivScale0, Flags);
9208
9209 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
9210 ApproxRcp, Fma0, Flags);
9211
9212 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
9213 Fma1, Fma1, Flags);
9214
9215 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
9216 NumeratorScaled, Mul, Flags);
9217
9218 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
9219 Fma2, Fma1, Mul, Fma2, Flags);
9220
9221 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
9222 NumeratorScaled, Fma3, Flags);
9223
9224 if (!HasFP32Denormals) {
9225 SDNode *DisableDenorm;
9226 if (Subtarget->hasDenormModeInst()) {
9227 const SDValue DisableDenormValue =
9228 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT0, DAG, SL, Subtarget);
9229
9230 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
9231 Fma4.getValue(1), DisableDenormValue,
9232 Fma4.getValue(2)).getNode();
9233 } else {
9234 const SDValue DisableDenormValue =
9235 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT0, SL, MVT::i32);
9236
9237 DisableDenorm = DAG.getMachineNode(
9238 AMDGPU::S_SETREG_B32, SL, MVT::Other,
9239 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
9240 }
9241
9242 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
9243 SDValue(DisableDenorm, 0), DAG.getRoot());
9244 DAG.setRoot(OutputChain);
9245 }
9246
9247 SDValue Scale = NumeratorScaled.getValue(1);
9248 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
9249 {Fma4, Fma1, Fma3, Scale}, Flags);
9250
9251 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
9252}
9253
9254SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
9255 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
9256 return FastLowered;
9257
9258 SDLoc SL(Op);
9259 SDValue X = Op.getOperand(0);
9260 SDValue Y = Op.getOperand(1);
9261
9262 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
9263
9264 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
9265
9266 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
9267
9268 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
9269
9270 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
9271
9272 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
9273
9274 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
9275
9276 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
9277
9278 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
9279
9280 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
9281 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
9282
9283 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
9284 NegDivScale0, Mul, DivScale1);
9285
9286 SDValue Scale;
9287
9288 if (!Subtarget->hasUsableDivScaleConditionOutput()) {
9289 // Workaround a hardware bug on SI where the condition output from div_scale
9290 // is not usable.
9291
9292 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
9293
9294 // Figure out if the scale to use for div_fmas.
9295 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
9296 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
9297 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
9298 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
9299
9300 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
9301 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
9302
9303 SDValue Scale0Hi
9304 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
9305 SDValue Scale1Hi
9306 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
9307
9308 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
9309 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
9310 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
9311 } else {
9312 Scale = DivScale1.getValue(1);
9313 }
9314
9315 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
9316 Fma4, Fma3, Mul, Scale);
9317
9318 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
9319}
9320
9321SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
9322 EVT VT = Op.getValueType();
9323
9324 if (VT == MVT::f32)
9325 return LowerFDIV32(Op, DAG);
9326
9327 if (VT == MVT::f64)
9328 return LowerFDIV64(Op, DAG);
9329
9330 if (VT == MVT::f16)
9331 return LowerFDIV16(Op, DAG);
9332
9333 llvm_unreachable("Unexpected type for fdiv")::llvm::llvm_unreachable_internal("Unexpected type for fdiv",
"llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9333)
;
9334}
9335
9336SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9337 SDLoc DL(Op);
9338 StoreSDNode *Store = cast<StoreSDNode>(Op);
9339 EVT VT = Store->getMemoryVT();
9340
9341 if (VT == MVT::i1) {
9342 return DAG.getTruncStore(Store->getChain(), DL,
9343 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9344 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9345 }
9346
9347 assert(VT.isVector() &&(static_cast <bool> (VT.isVector() && Store->
getValue().getValueType().getScalarType() == MVT::i32) ? void
(0) : __assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9348, __extension__
__PRETTY_FUNCTION__))
9348 Store->getValue().getValueType().getScalarType() == MVT::i32)(static_cast <bool> (VT.isVector() && Store->
getValue().getValueType().getScalarType() == MVT::i32) ? void
(0) : __assert_fail ("VT.isVector() && Store->getValue().getValueType().getScalarType() == MVT::i32"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9348, __extension__
__PRETTY_FUNCTION__))
;
9349
9350 unsigned AS = Store->getAddressSpace();
9351 if (Subtarget->hasLDSMisalignedBug() &&
9352 AS == AMDGPUAS::FLAT_ADDRESS &&
9353 Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9354 return SplitVectorStore(Op, DAG);
9355 }
9356
9357 MachineFunction &MF = DAG.getMachineFunction();
9358 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9359 // If there is a possibility that flat instruction access scratch memory
9360 // then we need to use the same legalization rules we use for private.
9361 if (AS == AMDGPUAS::FLAT_ADDRESS &&
9362 !Subtarget->hasMultiDwordFlatScratchAddressing())
9363 AS = addressMayBeAccessedAsPrivate(Store->getMemOperand(), *MFI) ?
9364 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9365
9366 unsigned NumElements = VT.getVectorNumElements();
9367 if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9368 AS == AMDGPUAS::FLAT_ADDRESS) {
9369 if (NumElements > 4)
9370 return SplitVectorStore(Op, DAG);
9371 // v3 stores not supported on SI.
9372 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9373 return SplitVectorStore(Op, DAG);
9374
9375 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9376 VT, *Store->getMemOperand()))
9377 return expandUnalignedStore(Store, DAG);
9378
9379 return SDValue();
9380 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9381 switch (Subtarget->getMaxPrivateElementSize()) {
9382 case 4:
9383 return scalarizeVectorStore(Store, DAG);
9384 case 8:
9385 if (NumElements > 2)
9386 return SplitVectorStore(Op, DAG);
9387 return SDValue();
9388 case 16:
9389 if (NumElements > 4 ||
9390 (NumElements == 3 && !Subtarget->enableFlatScratch()))
9391 return SplitVectorStore(Op, DAG);
9392 return SDValue();
9393 default:
9394 llvm_unreachable("unsupported private_element_size")::llvm::llvm_unreachable_internal("unsupported private_element_size"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9394)
;
9395 }
9396 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9397 unsigned Fast = 0;
9398 auto Flags = Store->getMemOperand()->getFlags();
9399 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9400 Store->getAlign(), Flags, &Fast) &&
9401 Fast > 1)
9402 return SDValue();
9403
9404 if (VT.isVector())
9405 return SplitVectorStore(Op, DAG);
9406
9407 return expandUnalignedStore(Store, DAG);
9408 }
9409
9410 // Probably an invalid store. If so we'll end up emitting a selection error.
9411 return SDValue();
9412}
9413
9414SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9415 SDLoc DL(Op);
9416 EVT VT = Op.getValueType();
9417 SDValue Arg = Op.getOperand(0);
9418 SDValue TrigVal;
9419
9420 // Propagate fast-math flags so that the multiply we introduce can be folded
9421 // if Arg is already the result of a multiply by constant.
9422 auto Flags = Op->getFlags();
9423
9424 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9425
9426 if (Subtarget->hasTrigReducedRange()) {
9427 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9428 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9429 } else {
9430 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9431 }
9432
9433 switch (Op.getOpcode()) {
9434 case ISD::FCOS:
9435 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9436 case ISD::FSIN:
9437 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9438 default:
9439 llvm_unreachable("Wrong trig opcode")::llvm::llvm_unreachable_internal("Wrong trig opcode", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 9439)
;
9440 }
9441}
9442
9443SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9444 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9445 assert(AtomicNode->isCompareAndSwap())(static_cast <bool> (AtomicNode->isCompareAndSwap())
? void (0) : __assert_fail ("AtomicNode->isCompareAndSwap()"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 9445, __extension__
__PRETTY_FUNCTION__))
;
9446 unsigned AS = AtomicNode->getAddressSpace();
9447
9448 // No custom lowering required for local address space
9449 if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9450 return Op;
9451
9452 // Non-local address space requires custom lowering for atomic compare
9453 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9454 SDLoc DL(Op);
9455 SDValue ChainIn = Op.getOperand(0);
9456 SDValue Addr = Op.getOperand(1);
9457 SDValue Old = Op.getOperand(2);
9458 SDValue New = Op.getOperand(3);
9459 EVT VT = Op.getValueType();
9460 MVT SimpleVT = VT.getSimpleVT();
9461 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9462
9463 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9464 SDValue Ops[] = { ChainIn, Addr, NewOld };
9465
9466 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9467 Ops, VT, AtomicNode->getMemOperand());
9468}
9469
9470//===----------------------------------------------------------------------===//
9471// Custom DAG optimizations
9472//===----------------------------------------------------------------------===//
9473
9474SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9475 DAGCombinerInfo &DCI) const {
9476 EVT VT = N->getValueType(0);
9477 EVT ScalarVT = VT.getScalarType();
9478 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9479 return SDValue();
9480
9481 SelectionDAG &DAG = DCI.DAG;
9482 SDLoc DL(N);
9483
9484 SDValue Src = N->getOperand(0);
9485 EVT SrcVT = Src.getValueType();
9486
9487 // TODO: We could try to match extracting the higher bytes, which would be
9488 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9489 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9490 // about in practice.
9491 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9492 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9493 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9494 DCI.AddToWorklist(Cvt.getNode());
9495
9496 // For the f16 case, fold to a cast to f32 and then cast back to f16.
9497 if (ScalarVT != MVT::f32) {
9498 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9499 DAG.getTargetConstant(0, DL, MVT::i32));
9500 }
9501 return Cvt;
9502 }
9503 }
9504
9505 return SDValue();
9506}
9507
9508SDValue SITargetLowering::performFCopySignCombine(SDNode *N,
9509 DAGCombinerInfo &DCI) const {
9510 SDValue MagnitudeOp = N->getOperand(0);
9511 SDValue SignOp = N->getOperand(1);
9512 SelectionDAG &DAG = DCI.DAG;
9513 SDLoc DL(N);
9514
9515 // f64 fcopysign is really an f32 copysign on the high bits, so replace the
9516 // lower half with a copy.
9517 // fcopysign f64:x, _:y -> x.lo32, (fcopysign (f32 x.hi32), _:y)
9518 if (MagnitudeOp.getValueType() == MVT::f64) {
9519 SDValue MagAsVector = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, MagnitudeOp);
9520 SDValue MagLo =
9521 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
9522 DAG.getConstant(0, DL, MVT::i32));
9523 SDValue MagHi =
9524 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
9525 DAG.getConstant(1, DL, MVT::i32));
9526
9527 SDValue HiOp =
9528 DAG.getNode(ISD::FCOPYSIGN, DL, MVT::f32, MagHi, SignOp);
9529
9530 SDValue Vector = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32, MagLo, HiOp);
9531
9532 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Vector);
9533 }
9534
9535 if (SignOp.getValueType() != MVT::f64)
9536 return SDValue();
9537
9538 // Reduce width of sign operand, we only need the highest bit.
9539 //
9540 // fcopysign f64:x, f64:y ->
9541 // fcopysign f64:x, (extract_vector_elt (bitcast f64:y to v2f32), 1)
9542 // TODO: In some cases it might make sense to go all the way to f16.
9543 SDValue SignAsVector = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, SignOp);
9544 SDValue SignAsF32 =
9545 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, SignAsVector,
9546 DAG.getConstant(1, DL, MVT::i32));
9547
9548 return DAG.getNode(ISD::FCOPYSIGN, DL, N->getValueType(0), N->getOperand(0),
9549 SignAsF32);
9550}
9551
9552// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9553
9554// This is a variant of
9555// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9556//
9557// The normal DAG combiner will do this, but only if the add has one use since
9558// that would increase the number of instructions.
9559//
9560// This prevents us from seeing a constant offset that can be folded into a
9561// memory instruction's addressing mode. If we know the resulting add offset of
9562// a pointer can be folded into an addressing offset, we can replace the pointer
9563// operand with the add of new constant offset. This eliminates one of the uses,
9564// and may allow the remaining use to also be simplified.
9565//
9566SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9567 unsigned AddrSpace,
9568 EVT MemVT,
9569 DAGCombinerInfo &DCI) const {
9570 SDValue N0 = N->getOperand(0);
9571 SDValue N1 = N->getOperand(1);
9572
9573 // We only do this to handle cases where it's profitable when there are
9574 // multiple uses of the add, so defer to the standard combine.
9575 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9576 N0->hasOneUse())
9577 return SDValue();
9578
9579 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9580 if (!CN1)
9581 return SDValue();
9582
9583 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9584 if (!CAdd)
9585 return SDValue();
9586
9587 // If the resulting offset is too large, we can't fold it into the addressing
9588 // mode offset.
9589 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9590 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9591
9592 AddrMode AM;
9593 AM.HasBaseReg = true;
9594 AM.BaseOffs = Offset.getSExtValue();
9595 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9596 return SDValue();
9597
9598 SelectionDAG &DAG = DCI.DAG;
9599 SDLoc SL(N);
9600 EVT VT = N->getValueType(0);
9601
9602 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9603 SDValue COffset = DAG.getConstant(Offset, SL, VT);
9604
9605 SDNodeFlags Flags;
9606 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9607 (N0.getOpcode() == ISD::OR ||
9608 N0->getFlags().hasNoUnsignedWrap()));
9609
9610 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9611}
9612
9613/// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9614/// by the chain and intrinsic ID. Theoretically we would also need to check the
9615/// specific intrinsic, but they all place the pointer operand first.
9616static unsigned getBasePtrIndex(const MemSDNode *N) {
9617 switch (N->getOpcode()) {
9618 case ISD::STORE:
9619 case ISD::INTRINSIC_W_CHAIN:
9620 case ISD::INTRINSIC_VOID:
9621 return 2;
9622 default:
9623 return 1;
9624 }
9625}
9626
9627SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9628 DAGCombinerInfo &DCI) const {
9629 SelectionDAG &DAG = DCI.DAG;
9630 SDLoc SL(N);
9631
9632 unsigned PtrIdx = getBasePtrIndex(N);
9633 SDValue Ptr = N->getOperand(PtrIdx);
9634
9635 // TODO: We could also do this for multiplies.
9636 if (Ptr.getOpcode() == ISD::SHL) {
9637 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
9638 N->getMemoryVT(), DCI);
9639 if (NewPtr) {
9640 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9641
9642 NewOps[PtrIdx] = NewPtr;
9643 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9644 }
9645 }
9646
9647 return SDValue();
9648}
9649
9650static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9651 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9652 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9653 (Opc == ISD::XOR && Val == 0);
9654}
9655
9656// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9657// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9658// integer combine opportunities since most 64-bit operations are decomposed
9659// this way. TODO: We won't want this for SALU especially if it is an inline
9660// immediate.
9661SDValue SITargetLowering::splitBinaryBitConstantOp(
9662 DAGCombinerInfo &DCI,
9663 const SDLoc &SL,
9664 unsigned Opc, SDValue LHS,
9665 const ConstantSDNode *CRHS) const {
9666 uint64_t Val = CRHS->getZExtValue();
9667 uint32_t ValLo = Lo_32(Val);
9668 uint32_t ValHi = Hi_32(Val);
9669 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9670
9671 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9672 bitOpWithConstantIsReducible(Opc, ValHi)) ||
9673 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9674 // If we need to materialize a 64-bit immediate, it will be split up later
9675 // anyway. Avoid creating the harder to understand 64-bit immediate
9676 // materialization.
9677 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9678 }
9679
9680 return SDValue();
9681}
9682
9683// Returns true if argument is a boolean value which is not serialized into
9684// memory or argument and does not require v_cndmask_b32 to be deserialized.
9685static bool isBoolSGPR(SDValue V) {
9686 if (V.getValueType() != MVT::i1)
9687 return false;
9688 switch (V.getOpcode()) {
9689 default:
9690 break;
9691 case ISD::SETCC:
9692 case AMDGPUISD::FP_CLASS:
9693 return true;
9694 case ISD::AND:
9695 case ISD::OR:
9696 case ISD::XOR:
9697 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9698 }
9699 return false;
9700}
9701
9702// If a constant has all zeroes or all ones within each byte return it.
9703// Otherwise return 0.
9704static uint32_t getConstantPermuteMask(uint32_t C) {
9705 // 0xff for any zero byte in the mask
9706 uint32_t ZeroByteMask = 0;
9707 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9708 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9709 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9710 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9711 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9712 if ((NonZeroByteMask & C) != NonZeroByteMask)
9713 return 0; // Partial bytes selected.
9714 return C;
9715}
9716
9717// Check if a node selects whole bytes from its operand 0 starting at a byte
9718// boundary while masking the rest. Returns select mask as in the v_perm_b32
9719// or -1 if not succeeded.
9720// Note byte select encoding:
9721// value 0-3 selects corresponding source byte;
9722// value 0xc selects zero;
9723// value 0xff selects 0xff.
9724static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9725 assert(V.getValueSizeInBits() == 32)(static_cast <bool> (V.getValueSizeInBits() == 32) ? void
(0) : __assert_fail ("V.getValueSizeInBits() == 32", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 9725, __extension__ __PRETTY_FUNCTION__))
;
9726
9727 if (V.getNumOperands() != 2)
9728 return ~0;
9729
9730 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9731 if (!N1)
9732 return ~0;
9733
9734 uint32_t C = N1->getZExtValue();
9735
9736 switch (V.getOpcode()) {
9737 default:
9738 break;
9739 case ISD::AND:
9740 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9741 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9742 }
9743 break;
9744
9745 case ISD::OR:
9746 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9747 return (0x03020100 & ~ConstMask) | ConstMask;
9748 }
9749 break;
9750
9751 case ISD::SHL:
9752 if (C % 8)
9753 return ~0;
9754
9755 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9756
9757 case ISD::SRL:
9758 if (C % 8)
9759 return ~0;
9760
9761 return uint32_t(0x0c0c0c0c03020100ull >> C);
9762 }
9763
9764 return ~0;
9765}
9766
9767SDValue SITargetLowering::performAndCombine(SDNode *N,
9768 DAGCombinerInfo &DCI) const {
9769 if (DCI.isBeforeLegalize())
9770 return SDValue();
9771
9772 SelectionDAG &DAG = DCI.DAG;
9773 EVT VT = N->getValueType(0);
9774 SDValue LHS = N->getOperand(0);
9775 SDValue RHS = N->getOperand(1);
9776
9777
9778 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9779 if (VT == MVT::i64 && CRHS) {
9780 if (SDValue Split
9781 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9782 return Split;
9783 }
9784
9785 if (CRHS && VT == MVT::i32) {
9786 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9787 // nb = number of trailing zeroes in mask
9788 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9789 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9790 uint64_t Mask = CRHS->getZExtValue();
9791 unsigned Bits = llvm::popcount(Mask);
9792 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9793 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9794 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9795 unsigned Shift = CShift->getZExtValue();
9796 unsigned NB = CRHS->getAPIntValue().countr_zero();
9797 unsigned Offset = NB + Shift;
9798 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9799 SDLoc SL(N);
9800 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9801 LHS->getOperand(0),
9802 DAG.getConstant(Offset, SL, MVT::i32),
9803 DAG.getConstant(Bits, SL, MVT::i32));
9804 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9805 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9806 DAG.getValueType(NarrowVT));
9807 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9808 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9809 return Shl;
9810 }
9811 }
9812 }
9813
9814 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9815 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9816 isa<ConstantSDNode>(LHS.getOperand(2))) {
9817 uint32_t Sel = getConstantPermuteMask(Mask);
9818 if (!Sel)
9819 return SDValue();
9820
9821 // Select 0xc for all zero bytes
9822 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9823 SDLoc DL(N);
9824 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9825 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9826 }
9827 }
9828
9829 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9830 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9831 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9832 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9833 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9834
9835 SDValue X = LHS.getOperand(0);
9836 SDValue Y = RHS.getOperand(0);
9837 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X ||
9838 !isTypeLegal(X.getValueType()))
9839 return SDValue();
9840
9841 if (LCC == ISD::SETO) {
9842 if (X != LHS.getOperand(1))
9843 return SDValue();
9844
9845 if (RCC == ISD::SETUNE) {
9846 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9847 if (!C1 || !C1->isInfinity() || C1->isNegative())
9848 return SDValue();
9849
9850 const uint32_t Mask = SIInstrFlags::N_NORMAL |
9851 SIInstrFlags::N_SUBNORMAL |
9852 SIInstrFlags::N_ZERO |
9853 SIInstrFlags::P_ZERO |
9854 SIInstrFlags::P_SUBNORMAL |
9855 SIInstrFlags::P_NORMAL;
9856
9857 static_assert(((~(SIInstrFlags::S_NAN |
9858 SIInstrFlags::Q_NAN |
9859 SIInstrFlags::N_INFINITY |
9860 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9861 "mask not equal");
9862
9863 SDLoc DL(N);
9864 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9865 X, DAG.getConstant(Mask, DL, MVT::i32));
9866 }
9867 }
9868 }
9869
9870 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9871 std::swap(LHS, RHS);
9872
9873 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9874 RHS.hasOneUse()) {
9875 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9876 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9877 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9878 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9879 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9880 (RHS.getOperand(0) == LHS.getOperand(0) &&
9881 LHS.getOperand(0) == LHS.getOperand(1))) {
9882 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9883 unsigned NewMask = LCC == ISD::SETO ?
9884 Mask->getZExtValue() & ~OrdMask :
9885 Mask->getZExtValue() & OrdMask;
9886
9887 SDLoc DL(N);
9888 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9889 DAG.getConstant(NewMask, DL, MVT::i32));
9890 }
9891 }
9892
9893 if (VT == MVT::i32 &&
9894 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9895 // and x, (sext cc from i1) => select cc, x, 0
9896 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9897 std::swap(LHS, RHS);
9898 if (isBoolSGPR(RHS.getOperand(0)))
9899 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9900 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9901 }
9902
9903 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9904 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9905 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9906 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9907 uint32_t LHSMask = getPermuteMask(DAG, LHS);
9908 uint32_t RHSMask = getPermuteMask(DAG, RHS);
9909 if (LHSMask != ~0u && RHSMask != ~0u) {
9910 // Canonicalize the expression in an attempt to have fewer unique masks
9911 // and therefore fewer registers used to hold the masks.
9912 if (LHSMask > RHSMask) {
9913 std::swap(LHSMask, RHSMask);
9914 std::swap(LHS, RHS);
9915 }
9916
9917 // Select 0xc for each lane used from source operand. Zero has 0xc mask
9918 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9919 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9920 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9921
9922 // Check of we need to combine values from two sources within a byte.
9923 if (!(LHSUsedLanes & RHSUsedLanes) &&
9924 // If we select high and lower word keep it for SDWA.
9925 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9926 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9927 // Each byte in each mask is either selector mask 0-3, or has higher
9928 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9929 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9930 // mask which is not 0xff wins. By anding both masks we have a correct
9931 // result except that 0x0c shall be corrected to give 0x0c only.
9932 uint32_t Mask = LHSMask & RHSMask;
9933 for (unsigned I = 0; I < 32; I += 8) {
9934 uint32_t ByteSel = 0xff << I;
9935 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9936 Mask &= (0x0c << I) & 0xffffffff;
9937 }
9938
9939 // Add 4 to each active LHS lane. It will not affect any existing 0xff
9940 // or 0x0c.
9941 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9942 SDLoc DL(N);
9943
9944 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9945 LHS.getOperand(0), RHS.getOperand(0),
9946 DAG.getConstant(Sel, DL, MVT::i32));
9947 }
9948 }
9949 }
9950
9951 return SDValue();
9952}
9953
9954SDValue SITargetLowering::performOrCombine(SDNode *N,
9955 DAGCombinerInfo &DCI) const {
9956 SelectionDAG &DAG = DCI.DAG;
9957 SDValue LHS = N->getOperand(0);
9958 SDValue RHS = N->getOperand(1);
9959
9960 EVT VT = N->getValueType(0);
9961 if (VT == MVT::i1) {
9962 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9963 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9964 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9965 SDValue Src = LHS.getOperand(0);
9966 if (Src != RHS.getOperand(0))
9967 return SDValue();
9968
9969 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9970 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9971 if (!CLHS || !CRHS)
9972 return SDValue();
9973
9974 // Only 10 bits are used.
9975 static const uint32_t MaxMask = 0x3ff;
9976
9977 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9978 SDLoc DL(N);
9979 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9980 Src, DAG.getConstant(NewMask, DL, MVT::i32));
9981 }
9982
9983 return SDValue();
9984 }
9985
9986 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9987 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9988 LHS.getOpcode() == AMDGPUISD::PERM &&
9989 isa<ConstantSDNode>(LHS.getOperand(2))) {
9990 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9991 if (!Sel)
9992 return SDValue();
9993
9994 Sel |= LHS.getConstantOperandVal(2);
9995 SDLoc DL(N);
9996 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9997 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9998 }
9999
10000 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
10001 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10002 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
10003 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
10004 uint32_t LHSMask = getPermuteMask(DAG, LHS);
10005 uint32_t RHSMask = getPermuteMask(DAG, RHS);
10006 if (LHSMask != ~0u && RHSMask != ~0u) {
10007 // Canonicalize the expression in an attempt to have fewer unique masks
10008 // and therefore fewer registers used to hold the masks.
10009 if (LHSMask > RHSMask) {
10010 std::swap(LHSMask, RHSMask);
10011 std::swap(LHS, RHS);
10012 }
10013
10014 // Select 0xc for each lane used from source operand. Zero has 0xc mask
10015 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
10016 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
10017 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
10018
10019 // Check of we need to combine values from two sources within a byte.
10020 if (!(LHSUsedLanes & RHSUsedLanes) &&
10021 // If we select high and lower word keep it for SDWA.
10022 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
10023 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
10024 // Kill zero bytes selected by other mask. Zero value is 0xc.
10025 LHSMask &= ~RHSUsedLanes;
10026 RHSMask &= ~LHSUsedLanes;
10027 // Add 4 to each active LHS lane
10028 LHSMask |= LHSUsedLanes & 0x04040404;
10029 // Combine masks
10030 uint32_t Sel = LHSMask | RHSMask;
10031 SDLoc DL(N);
10032
10033 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
10034 LHS.getOperand(0), RHS.getOperand(0),
10035 DAG.getConstant(Sel, DL, MVT::i32));
10036 }
10037 }
10038 }
10039
10040 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
10041 return SDValue();
10042
10043 // TODO: This could be a generic combine with a predicate for extracting the
10044 // high half of an integer being free.
10045
10046 // (or i64:x, (zero_extend i32:y)) ->
10047 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
10048 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
10049 RHS.getOpcode() != ISD::ZERO_EXTEND)
10050 std::swap(LHS, RHS);
10051
10052 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
10053 SDValue ExtSrc = RHS.getOperand(0);
10054 EVT SrcVT = ExtSrc.getValueType();
10055 if (SrcVT == MVT::i32) {
10056 SDLoc SL(N);
10057 SDValue LowLHS, HiBits;
10058 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
10059 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
10060
10061 DCI.AddToWorklist(LowOr.getNode());
10062 DCI.AddToWorklist(HiBits.getNode());
10063
10064 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
10065 LowOr, HiBits);
10066 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
10067 }
10068 }
10069
10070 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
10071 if (CRHS) {
10072 if (SDValue Split
10073 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
10074 N->getOperand(0), CRHS))
10075 return Split;
10076 }
10077
10078 return SDValue();
10079}
10080
10081SDValue SITargetLowering::performXorCombine(SDNode *N,
10082 DAGCombinerInfo &DCI) const {
10083 if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
10084 return RV;
10085
10086 SDValue LHS = N->getOperand(0);
10087 SDValue RHS = N->getOperand(1);
10088
10089 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
10090 SelectionDAG &DAG = DCI.DAG;
10091
10092 EVT VT = N->getValueType(0);
10093 if (CRHS && VT == MVT::i64) {
10094 if (SDValue Split
10095 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
10096 return Split;
10097 }
10098
10099 // Make sure to apply the 64-bit constant splitting fold before trying to fold
10100 // fneg-like xors into 64-bit select.
10101 if (LHS.getOpcode() == ISD::SELECT && VT == MVT::i32) {
10102 // This looks like an fneg, try to fold as a source modifier.
10103 if (CRHS && CRHS->getAPIntValue().isSignMask() &&
10104 shouldFoldFNegIntoSrc(N, LHS)) {
10105 // xor (select c, a, b), 0x80000000 ->
10106 // bitcast (select c, (fneg (bitcast a)), (fneg (bitcast b)))
10107 SDLoc DL(N);
10108 SDValue CastLHS =
10109 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(1));
10110 SDValue CastRHS =
10111 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(2));
10112 SDValue FNegLHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastLHS);
10113 SDValue FNegRHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastRHS);
10114 SDValue NewSelect = DAG.getNode(ISD::SELECT, DL, MVT::f32,
10115 LHS->getOperand(0), FNegLHS, FNegRHS);
10116 return DAG.getNode(ISD::BITCAST, DL, VT, NewSelect);
10117 }
10118 }
10119
10120 return SDValue();
10121}
10122
10123SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
10124 DAGCombinerInfo &DCI) const {
10125 if (!Subtarget->has16BitInsts() ||
10126 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10127 return SDValue();
10128
10129 EVT VT = N->getValueType(0);
10130 if (VT != MVT::i32)
10131 return SDValue();
10132
10133 SDValue Src = N->getOperand(0);
10134 if (Src.getValueType() != MVT::i16)
10135 return SDValue();
10136
10137 return SDValue();
10138}
10139
10140SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
10141 DAGCombinerInfo &DCI)
10142 const {
10143 SDValue Src = N->getOperand(0);
10144 auto *VTSign = cast<VTSDNode>(N->getOperand(1));
10145
10146 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
10147 VTSign->getVT() == MVT::i8) ||
10148 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
10149 VTSign->getVT() == MVT::i16)) &&
10150 Src.hasOneUse()) {
10151 auto *M = cast<MemSDNode>(Src);
10152 SDValue Ops[] = {
10153 Src.getOperand(0), // Chain
10154 Src.getOperand(1), // rsrc
10155 Src.getOperand(2), // vindex
10156 Src.getOperand(3), // voffset
10157 Src.getOperand(4), // soffset
10158 Src.getOperand(5), // offset
10159 Src.getOperand(6),
10160 Src.getOperand(7)
10161 };
10162 // replace with BUFFER_LOAD_BYTE/SHORT
10163 SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
10164 Src.getOperand(0).getValueType());
10165 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
10166 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
10167 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
10168 ResList,
10169 Ops, M->getMemoryVT(),
10170 M->getMemOperand());
10171 return DCI.DAG.getMergeValues({BufferLoadSignExt,
10172 BufferLoadSignExt.getValue(1)}, SDLoc(N));
10173 }
10174 return SDValue();
10175}
10176
10177SDValue SITargetLowering::performClassCombine(SDNode *N,
10178 DAGCombinerInfo &DCI) const {
10179 SelectionDAG &DAG = DCI.DAG;
10180 SDValue Mask = N->getOperand(1);
10181
10182 // fp_class x, 0 -> false
10183 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
10184 if (CMask->isZero())
10185 return DAG.getConstant(0, SDLoc(N), MVT::i1);
10186 }
10187
10188 if (N->getOperand(0).isUndef())
10189 return DAG.getUNDEF(MVT::i1);
10190
10191 return SDValue();
10192}
10193
10194SDValue SITargetLowering::performRcpCombine(SDNode *N,
10195 DAGCombinerInfo &DCI) const {
10196 EVT VT = N->getValueType(0);
10197 SDValue N0 = N->getOperand(0);
10198
10199 if (N0.isUndef()) {
10200 return DCI.DAG.getConstantFP(
10201 APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)), SDLoc(N),
10202 VT);
10203 }
10204
10205 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
10206 N0.getOpcode() == ISD::SINT_TO_FP)) {
10207 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
10208 N->getFlags());
10209 }
10210
10211 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
10212 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
10213 N0.getOperand(0), N->getFlags());
10214 }
10215
10216 return AMDGPUTargetLowering::performRcpCombine(N, DCI);
10217}
10218
10219bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
10220 unsigned MaxDepth) const {
10221 unsigned Opcode = Op.getOpcode();
10222 if (Opcode == ISD::FCANONICALIZE)
10223 return true;
10224
10225 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10226 auto F = CFP->getValueAPF();
10227 if (F.isNaN() && F.isSignaling())
10228 return false;
10229 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
10230 }
10231
10232 // If source is a result of another standard FP operation it is already in
10233 // canonical form.
10234 if (MaxDepth == 0)
10235 return false;
10236
10237 switch (Opcode) {
10238 // These will flush denorms if required.
10239 case ISD::FADD:
10240 case ISD::FSUB:
10241 case ISD::FMUL:
10242 case ISD::FCEIL:
10243 case ISD::FFLOOR:
10244 case ISD::FMA:
10245 case ISD::FMAD:
10246 case ISD::FSQRT:
10247 case ISD::FDIV:
10248 case ISD::FREM:
10249 case ISD::FP_ROUND:
10250 case ISD::FP_EXTEND:
10251 case AMDGPUISD::FMUL_LEGACY:
10252 case AMDGPUISD::FMAD_FTZ:
10253 case AMDGPUISD::RCP:
10254 case AMDGPUISD::RSQ:
10255 case AMDGPUISD::RSQ_CLAMP:
10256 case AMDGPUISD::RCP_LEGACY:
10257 case AMDGPUISD::RCP_IFLAG:
10258 case AMDGPUISD::DIV_SCALE:
10259 case AMDGPUISD::DIV_FMAS:
10260 case AMDGPUISD::DIV_FIXUP:
10261 case AMDGPUISD::FRACT:
10262 case AMDGPUISD::LDEXP:
10263 case AMDGPUISD::CVT_PKRTZ_F16_F32:
10264 case AMDGPUISD::CVT_F32_UBYTE0:
10265 case AMDGPUISD::CVT_F32_UBYTE1:
10266 case AMDGPUISD::CVT_F32_UBYTE2:
10267 case AMDGPUISD::CVT_F32_UBYTE3:
10268 return true;
10269
10270 // It can/will be lowered or combined as a bit operation.
10271 // Need to check their input recursively to handle.
10272 case ISD::FNEG:
10273 case ISD::FABS:
10274 case ISD::FCOPYSIGN:
10275 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10276
10277 case ISD::FSIN:
10278 case ISD::FCOS:
10279 case ISD::FSINCOS:
10280 return Op.getValueType().getScalarType() != MVT::f16;
10281
10282 case ISD::FMINNUM:
10283 case ISD::FMAXNUM:
10284 case ISD::FMINNUM_IEEE:
10285 case ISD::FMAXNUM_IEEE:
10286 case AMDGPUISD::CLAMP:
10287 case AMDGPUISD::FMED3:
10288 case AMDGPUISD::FMAX3:
10289 case AMDGPUISD::FMIN3: {
10290 // FIXME: Shouldn't treat the generic operations different based these.
10291 // However, we aren't really required to flush the result from
10292 // minnum/maxnum..
10293
10294 // snans will be quieted, so we only need to worry about denormals.
10295 if (Subtarget->supportsMinMaxDenormModes() ||
10296 denormalsEnabledForType(DAG, Op.getValueType()))
10297 return true;
10298
10299 // Flushing may be required.
10300 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
10301 // targets need to check their input recursively.
10302
10303 // FIXME: Does this apply with clamp? It's implemented with max.
10304 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
10305 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
10306 return false;
10307 }
10308
10309 return true;
10310 }
10311 case ISD::SELECT: {
10312 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
10313 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
10314 }
10315 case ISD::BUILD_VECTOR: {
10316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
10317 SDValue SrcOp = Op.getOperand(i);
10318 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
10319 return false;
10320 }
10321
10322 return true;
10323 }
10324 case ISD::EXTRACT_VECTOR_ELT:
10325 case ISD::EXTRACT_SUBVECTOR: {
10326 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10327 }
10328 case ISD::INSERT_VECTOR_ELT: {
10329 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
10330 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
10331 }
10332 case ISD::UNDEF:
10333 // Could be anything.
10334 return false;
10335
10336 case ISD::BITCAST:
10337 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10338 case ISD::TRUNCATE: {
10339 // Hack round the mess we make when legalizing extract_vector_elt
10340 if (Op.getValueType() == MVT::i16) {
10341 SDValue TruncSrc = Op.getOperand(0);
10342 if (TruncSrc.getValueType() == MVT::i32 &&
10343 TruncSrc.getOpcode() == ISD::BITCAST &&
10344 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
10345 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
10346 }
10347 }
10348 return false;
10349 }
10350 case ISD::INTRINSIC_WO_CHAIN: {
10351 unsigned IntrinsicID
10352 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10353 // TODO: Handle more intrinsics
10354 switch (IntrinsicID) {
10355 case Intrinsic::amdgcn_cvt_pkrtz:
10356 case Intrinsic::amdgcn_cubeid:
10357 case Intrinsic::amdgcn_frexp_mant:
10358 case Intrinsic::amdgcn_fdot2:
10359 case Intrinsic::amdgcn_rcp:
10360 case Intrinsic::amdgcn_rsq:
10361 case Intrinsic::amdgcn_rsq_clamp:
10362 case Intrinsic::amdgcn_rcp_legacy:
10363 case Intrinsic::amdgcn_rsq_legacy:
10364 case Intrinsic::amdgcn_trig_preop:
10365 return true;
10366 default:
10367 break;
10368 }
10369
10370 [[fallthrough]];
10371 }
10372 default:
10373 return denormalsEnabledForType(DAG, Op.getValueType()) &&
10374 DAG.isKnownNeverSNaN(Op);
10375 }
10376
10377 llvm_unreachable("invalid operation")::llvm::llvm_unreachable_internal("invalid operation", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 10377)
;
10378}
10379
10380bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
10381 unsigned MaxDepth) const {
10382 MachineRegisterInfo &MRI = MF.getRegInfo();
10383 MachineInstr *MI = MRI.getVRegDef(Reg);
10384 unsigned Opcode = MI->getOpcode();
10385
10386 if (Opcode == AMDGPU::G_FCANONICALIZE)
10387 return true;
10388
10389 std::optional<FPValueAndVReg> FCR;
10390 // Constant splat (can be padded with undef) or scalar constant.
10391 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
10392 if (FCR->Value.isSignaling())
10393 return false;
10394 return !FCR->Value.isDenormal() ||
10395 denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10396 }
10397
10398 if (MaxDepth == 0)
10399 return false;
10400
10401 switch (Opcode) {
10402 case AMDGPU::G_FADD:
10403 case AMDGPU::G_FSUB:
10404 case AMDGPU::G_FMUL:
10405 case AMDGPU::G_FCEIL:
10406 case AMDGPU::G_FFLOOR:
10407 case AMDGPU::G_FRINT:
10408 case AMDGPU::G_FNEARBYINT:
10409 case AMDGPU::G_INTRINSIC_FPTRUNC_ROUND:
10410 case AMDGPU::G_INTRINSIC_TRUNC:
10411 case AMDGPU::G_INTRINSIC_ROUNDEVEN:
10412 case AMDGPU::G_FMA:
10413 case AMDGPU::G_FMAD:
10414 case AMDGPU::G_FSQRT:
10415 case AMDGPU::G_FDIV:
10416 case AMDGPU::G_FREM:
10417 case AMDGPU::G_FPOW:
10418 case AMDGPU::G_FPEXT:
10419 case AMDGPU::G_FLOG:
10420 case AMDGPU::G_FLOG2:
10421 case AMDGPU::G_FLOG10:
10422 case AMDGPU::G_FPTRUNC:
10423 case AMDGPU::G_AMDGPU_RCP_IFLAG:
10424 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE0:
10425 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE1:
10426 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE2:
10427 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE3:
10428 return true;
10429 case AMDGPU::G_FNEG:
10430 case AMDGPU::G_FABS:
10431 case AMDGPU::G_FCOPYSIGN:
10432 return isCanonicalized(MI->getOperand(1).getReg(), MF, MaxDepth - 1);
10433 case AMDGPU::G_FMINNUM:
10434 case AMDGPU::G_FMAXNUM:
10435 case AMDGPU::G_FMINNUM_IEEE:
10436 case AMDGPU::G_FMAXNUM_IEEE: {
10437 if (Subtarget->supportsMinMaxDenormModes() ||
10438 denormalsEnabledForType(MRI.getType(Reg), MF))
10439 return true;
10440
10441 [[fallthrough]];
10442 }
10443 case AMDGPU::G_BUILD_VECTOR:
10444 for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10445 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10446 return false;
10447 return true;
10448 case AMDGPU::G_INTRINSIC:
10449 switch (MI->getIntrinsicID()) {
10450 case Intrinsic::amdgcn_fmul_legacy:
10451 case Intrinsic::amdgcn_fmad_ftz:
10452 case Intrinsic::amdgcn_sqrt:
10453 case Intrinsic::amdgcn_fmed3:
10454 case Intrinsic::amdgcn_sin:
10455 case Intrinsic::amdgcn_cos:
10456 case Intrinsic::amdgcn_log_clamp:
10457 case Intrinsic::amdgcn_rcp:
10458 case Intrinsic::amdgcn_rcp_legacy:
10459 case Intrinsic::amdgcn_rsq:
10460 case Intrinsic::amdgcn_rsq_clamp:
10461 case Intrinsic::amdgcn_rsq_legacy:
10462 case Intrinsic::amdgcn_div_scale:
10463 case Intrinsic::amdgcn_div_fmas:
10464 case Intrinsic::amdgcn_div_fixup:
10465 case Intrinsic::amdgcn_fract:
10466 case Intrinsic::amdgcn_ldexp:
10467 case Intrinsic::amdgcn_cvt_pkrtz:
10468 case Intrinsic::amdgcn_cubeid:
10469 case Intrinsic::amdgcn_cubema:
10470 case Intrinsic::amdgcn_cubesc:
10471 case Intrinsic::amdgcn_cubetc:
10472 case Intrinsic::amdgcn_frexp_mant:
10473 case Intrinsic::amdgcn_fdot2:
10474 case Intrinsic::amdgcn_trig_preop:
10475 return true;
10476 default:
10477 break;
10478 }
10479
10480 [[fallthrough]];
10481 default:
10482 return false;
10483 }
10484
10485 llvm_unreachable("invalid operation")::llvm::llvm_unreachable_internal("invalid operation", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 10485)
;
10486}
10487
10488// Constant fold canonicalize.
10489SDValue SITargetLowering::getCanonicalConstantFP(
10490 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10491 // Flush denormals to 0 if not enabled.
10492 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) {
10493 return DAG.getConstantFP(APFloat::getZero(C.getSemantics(),
10494 C.isNegative()), SL, VT);
10495 }
10496
10497 if (C.isNaN()) {
10498 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10499 if (C.isSignaling()) {
10500 // Quiet a signaling NaN.
10501 // FIXME: Is this supposed to preserve payload bits?
10502 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10503 }
10504
10505 // Make sure it is the canonical NaN bitpattern.
10506 //
10507 // TODO: Can we use -1 as the canonical NaN value since it's an inline
10508 // immediate?
10509 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10510 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10511 }
10512
10513 // Already canonical.
10514 return DAG.getConstantFP(C, SL, VT);
10515}
10516
10517static bool vectorEltWillFoldAway(SDValue Op) {
10518 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10519}
10520
10521SDValue SITargetLowering::performFCanonicalizeCombine(
10522 SDNode *N,
10523 DAGCombinerInfo &DCI) const {
10524 SelectionDAG &DAG = DCI.DAG;
10525 SDValue N0 = N->getOperand(0);
10526 EVT VT = N->getValueType(0);
10527
10528 // fcanonicalize undef -> qnan
10529 if (N0.isUndef()) {
10530 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10531 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10532 }
10533
10534 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10535 EVT VT = N->getValueType(0);
10536 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10537 }
10538
10539 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10540 // (fcanonicalize k)
10541 //
10542 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10543
10544 // TODO: This could be better with wider vectors that will be split to v2f16,
10545 // and to consider uses since there aren't that many packed operations.
10546 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10547 isTypeLegal(MVT::v2f16)) {
10548 SDLoc SL(N);
10549 SDValue NewElts[2];
10550 SDValue Lo = N0.getOperand(0);
10551 SDValue Hi = N0.getOperand(1);
10552 EVT EltVT = Lo.getValueType();
10553
10554 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10555 for (unsigned I = 0; I != 2; ++I) {
10556 SDValue Op = N0.getOperand(I);
10557 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10558 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10559 CFP->getValueAPF());
10560 } else if (Op.isUndef()) {
10561 // Handled below based on what the other operand is.
10562 NewElts[I] = Op;
10563 } else {
10564 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10565 }
10566 }
10567
10568 // If one half is undef, and one is constant, prefer a splat vector rather
10569 // than the normal qNaN. If it's a register, prefer 0.0 since that's
10570 // cheaper to use and may be free with a packed operation.
10571 if (NewElts[0].isUndef()) {
10572 if (isa<ConstantFPSDNode>(NewElts[1]))
10573 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10574 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10575 }
10576
10577 if (NewElts[1].isUndef()) {
10578 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10579 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10580 }
10581
10582 return DAG.getBuildVector(VT, SL, NewElts);
10583 }
10584 }
10585
10586 unsigned SrcOpc = N0.getOpcode();
10587
10588 // If it's free to do so, push canonicalizes further up the source, which may
10589 // find a canonical source.
10590 //
10591 // TODO: More opcodes. Note this is unsafe for the _ieee minnum/maxnum for
10592 // sNaNs.
10593 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10594 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10595 if (CRHS && N0.hasOneUse()) {
10596 SDLoc SL(N);
10597 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10598 N0.getOperand(0));
10599 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10600 DCI.AddToWorklist(Canon0.getNode());
10601
10602 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10603 }
10604 }
10605
10606 return isCanonicalized(DAG, N0) ? N0 : SDValue();
10607}
10608
10609static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10610 switch (Opc) {
10611 case ISD::FMAXNUM:
10612 case ISD::FMAXNUM_IEEE:
10613 return AMDGPUISD::FMAX3;
10614 case ISD::SMAX:
10615 return AMDGPUISD::SMAX3;
10616 case ISD::UMAX:
10617 return AMDGPUISD::UMAX3;
10618 case ISD::FMINNUM:
10619 case ISD::FMINNUM_IEEE:
10620 return AMDGPUISD::FMIN3;
10621 case ISD::SMIN:
10622 return AMDGPUISD::SMIN3;
10623 case ISD::UMIN:
10624 return AMDGPUISD::UMIN3;
10625 default:
10626 llvm_unreachable("Not a min/max opcode")::llvm::llvm_unreachable_internal("Not a min/max opcode", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 10626)
;
10627 }
10628}
10629
10630SDValue SITargetLowering::performIntMed3ImmCombine(SelectionDAG &DAG,
10631 const SDLoc &SL, SDValue Src,
10632 SDValue MinVal,
10633 SDValue MaxVal,
10634 bool Signed) const {
10635
10636 // med3 comes from
10637 // min(max(x, K0), K1), K0 < K1
10638 // max(min(x, K0), K1), K1 < K0
10639 //
10640 // "MinVal" and "MaxVal" respectively refer to the rhs of the
10641 // min/max op.
10642 ConstantSDNode *MinK = dyn_cast<ConstantSDNode>(MinVal);
10643 ConstantSDNode *MaxK = dyn_cast<ConstantSDNode>(MaxVal);
10644
10645 if (!MinK || !MaxK)
10646 return SDValue();
10647
10648 if (Signed) {
10649 if (MaxK->getAPIntValue().sge(MinK->getAPIntValue()))
10650 return SDValue();
10651 } else {
10652 if (MaxK->getAPIntValue().uge(MinK->getAPIntValue()))
10653 return SDValue();
10654 }
10655
10656 EVT VT = MinK->getValueType(0);
10657 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10658 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16()))
10659 return DAG.getNode(Med3Opc, SL, VT, Src, MaxVal, MinVal);
10660
10661 // Note: we could also extend to i32 and use i32 med3 if i16 med3 is
10662 // not available, but this is unlikely to be profitable as constants
10663 // will often need to be materialized & extended, especially on
10664 // pre-GFX10 where VOP3 instructions couldn't take literal operands.
10665 return SDValue();
10666}
10667
10668static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10669 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10670 return C;
10671
10672 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10673 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10674 return C;
10675 }
10676
10677 return nullptr;
10678}
10679
10680SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10681 const SDLoc &SL,
10682 SDValue Op0,
10683 SDValue Op1) const {
10684 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10685 if (!K1)
10686 return SDValue();
10687
10688 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10689 if (!K0)
10690 return SDValue();
10691
10692 // Ordered >= (although NaN inputs should have folded away by now).
10693 if (K0->getValueAPF() > K1->getValueAPF())
10694 return SDValue();
10695
10696 const MachineFunction &MF = DAG.getMachineFunction();
10697 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10698
10699 // TODO: Check IEEE bit enabled?
10700 EVT VT = Op0.getValueType();
10701 if (Info->getMode().DX10Clamp) {
10702 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10703 // hardware fmed3 behavior converting to a min.
10704 // FIXME: Should this be allowing -0.0?
10705 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10706 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10707 }
10708
10709 // med3 for f16 is only available on gfx9+, and not available for v2f16.
10710 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10711 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10712 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10713 // then give the other result, which is different from med3 with a NaN
10714 // input.
10715 SDValue Var = Op0.getOperand(0);
10716 if (!DAG.isKnownNeverSNaN(Var))
10717 return SDValue();
10718
10719 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10720
10721 if ((!K0->hasOneUse() ||
10722 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10723 (!K1->hasOneUse() ||
10724 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10725 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10726 Var, SDValue(K0, 0), SDValue(K1, 0));
10727 }
10728 }
10729
10730 return SDValue();
10731}
10732
10733SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10734 DAGCombinerInfo &DCI) const {
10735 SelectionDAG &DAG = DCI.DAG;
10736
10737 EVT VT = N->getValueType(0);
10738 unsigned Opc = N->getOpcode();
10739 SDValue Op0 = N->getOperand(0);
10740 SDValue Op1 = N->getOperand(1);
10741
10742 // Only do this if the inner op has one use since this will just increases
10743 // register pressure for no benefit.
10744
10745 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10746 !VT.isVector() &&
10747 (VT == MVT::i32 || VT == MVT::f32 ||
10748 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10749 // max(max(a, b), c) -> max3(a, b, c)
10750 // min(min(a, b), c) -> min3(a, b, c)
10751 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10752 SDLoc DL(N);
10753 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10754 DL,
10755 N->getValueType(0),
10756 Op0.getOperand(0),
10757 Op0.getOperand(1),
10758 Op1);
10759 }
10760
10761 // Try commuted.
10762 // max(a, max(b, c)) -> max3(a, b, c)
10763 // min(a, min(b, c)) -> min3(a, b, c)
10764 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10765 SDLoc DL(N);
10766 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10767 DL,
10768 N->getValueType(0),
10769 Op0,
10770 Op1.getOperand(0),
10771 Op1.getOperand(1));
10772 }
10773 }
10774
10775 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10776 // max(min(x, K0), K1), K1 < K0 -> med3(x, K1, K0)
10777 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10778 if (SDValue Med3 = performIntMed3ImmCombine(
10779 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), true))
10780 return Med3;
10781 }
10782 if (Opc == ISD::SMAX && Op0.getOpcode() == ISD::SMIN && Op0.hasOneUse()) {
10783 if (SDValue Med3 = performIntMed3ImmCombine(
10784 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, true))
10785 return Med3;
10786 }
10787
10788 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10789 if (SDValue Med3 = performIntMed3ImmCombine(
10790 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), false))
10791 return Med3;
10792 }
10793 if (Opc == ISD::UMAX && Op0.getOpcode() == ISD::UMIN && Op0.hasOneUse()) {
10794 if (SDValue Med3 = performIntMed3ImmCombine(
10795 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, false))
10796 return Med3;
10797 }
10798
10799 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10800 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10801 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10802 (Opc == AMDGPUISD::FMIN_LEGACY &&
10803 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10804 (VT == MVT::f32 || VT == MVT::f64 ||
10805 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10806 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10807 Op0.hasOneUse()) {
10808 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10809 return Res;
10810 }
10811
10812 return SDValue();
10813}
10814
10815static bool isClampZeroToOne(SDValue A, SDValue B) {
10816 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10817 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10818 // FIXME: Should this be allowing -0.0?
10819 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10820 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10821 }
10822 }
10823
10824 return false;
10825}
10826
10827// FIXME: Should only worry about snans for version with chain.
10828SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10829 DAGCombinerInfo &DCI) const {
10830 EVT VT = N->getValueType(0);
10831 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10832 // NaNs. With a NaN input, the order of the operands may change the result.
10833
10834 SelectionDAG &DAG = DCI.DAG;
10835 SDLoc SL(N);
10836
10837 SDValue Src0 = N->getOperand(0);
10838 SDValue Src1 = N->getOperand(1);
10839 SDValue Src2 = N->getOperand(2);
10840
10841 if (isClampZeroToOne(Src0, Src1)) {
10842 // const_a, const_b, x -> clamp is safe in all cases including signaling
10843 // nans.
10844 // FIXME: Should this be allowing -0.0?
10845 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10846 }
10847
10848 const MachineFunction &MF = DAG.getMachineFunction();
10849 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10850
10851 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10852 // handling no dx10-clamp?
10853 if (Info->getMode().DX10Clamp) {
10854 // If NaNs is clamped to 0, we are free to reorder the inputs.
10855
10856 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10857 std::swap(Src0, Src1);
10858
10859 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10860 std::swap(Src1, Src2);
10861
10862 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10863 std::swap(Src0, Src1);
10864
10865 if (isClampZeroToOne(Src1, Src2))
10866 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10867 }
10868
10869 return SDValue();
10870}
10871
10872SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10873 DAGCombinerInfo &DCI) const {
10874 SDValue Src0 = N->getOperand(0);
10875 SDValue Src1 = N->getOperand(1);
10876 if (Src0.isUndef() && Src1.isUndef())
10877 return DCI.DAG.getUNDEF(N->getValueType(0));
10878 return SDValue();
10879}
10880
10881// Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10882// expanded into a set of cmp/select instructions.
10883bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10884 unsigned NumElem,
10885 bool IsDivergentIdx,
10886 const GCNSubtarget *Subtarget) {
10887 if (UseDivergentRegisterIndexing)
10888 return false;
10889
10890 unsigned VecSize = EltSize * NumElem;
10891
10892 // Sub-dword vectors of size 2 dword or less have better implementation.
10893 if (VecSize <= 64 && EltSize < 32)
10894 return false;
10895
10896 // Always expand the rest of sub-dword instructions, otherwise it will be
10897 // lowered via memory.
10898 if (EltSize < 32)
10899 return true;
10900
10901 // Always do this if var-idx is divergent, otherwise it will become a loop.
10902 if (IsDivergentIdx)
10903 return true;
10904
10905 // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10906 unsigned NumInsts = NumElem /* Number of compares */ +
10907 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10908
10909 // On some architectures (GFX9) movrel is not available and it's better
10910 // to expand.
10911 if (!Subtarget->hasMovrel())
10912 return NumInsts <= 16;
10913
10914 // If movrel is available, use it instead of expanding for vector of 8
10915 // elements.
10916 return NumInsts <= 15;
10917}
10918
10919bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const {
10920 SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10921 if (isa<ConstantSDNode>(Idx))
10922 return false;
10923
10924 SDValue Vec = N->getOperand(0);
10925 EVT VecVT = Vec.getValueType();
10926 EVT EltVT = VecVT.getVectorElementType();
10927 unsigned EltSize = EltVT.getSizeInBits();
10928 unsigned NumElem = VecVT.getVectorNumElements();
10929
10930 return SITargetLowering::shouldExpandVectorDynExt(
10931 EltSize, NumElem, Idx->isDivergent(), getSubtarget());
10932}
10933
10934SDValue SITargetLowering::performExtractVectorEltCombine(
10935 SDNode *N, DAGCombinerInfo &DCI) const {
10936 SDValue Vec = N->getOperand(0);
10937 SelectionDAG &DAG = DCI.DAG;
10938
10939 EVT VecVT = Vec.getValueType();
10940 EVT VecEltVT = VecVT.getVectorElementType();
10941 EVT ResVT = N->getValueType(0);
10942
10943 unsigned VecSize = VecVT.getSizeInBits();
10944 unsigned VecEltSize = VecEltVT.getSizeInBits();
10945
10946 if ((Vec.getOpcode() == ISD::FNEG ||
10947 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10948 SDLoc SL(N);
10949 SDValue Idx = N->getOperand(1);
10950 SDValue Elt =
10951 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec.getOperand(0), Idx);
10952 return DAG.getNode(Vec.getOpcode(), SL, ResVT, Elt);
10953 }
10954
10955 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10956 // =>
10957 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10958 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10959 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10960 if (Vec.hasOneUse() && DCI.isBeforeLegalize() && VecEltVT == ResVT) {
10961 SDLoc SL(N);
10962 SDValue Idx = N->getOperand(1);
10963 unsigned Opc = Vec.getOpcode();
10964
10965 switch(Opc) {
10966 default:
10967 break;
10968 // TODO: Support other binary operations.
10969 case ISD::FADD:
10970 case ISD::FSUB:
10971 case ISD::FMUL:
10972 case ISD::ADD:
10973 case ISD::UMIN:
10974 case ISD::UMAX:
10975 case ISD::SMIN:
10976 case ISD::SMAX:
10977 case ISD::FMAXNUM:
10978 case ISD::FMINNUM:
10979 case ISD::FMAXNUM_IEEE:
10980 case ISD::FMINNUM_IEEE: {
10981 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
10982 Vec.getOperand(0), Idx);
10983 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
10984 Vec.getOperand(1), Idx);
10985
10986 DCI.AddToWorklist(Elt0.getNode());
10987 DCI.AddToWorklist(Elt1.getNode());
10988 return DAG.getNode(Opc, SL, ResVT, Elt0, Elt1, Vec->getFlags());
10989 }
10990 }
10991 }
10992
10993 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10994 if (shouldExpandVectorDynExt(N)) {
10995 SDLoc SL(N);
10996 SDValue Idx = N->getOperand(1);
10997 SDValue V;
10998 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10999 SDValue IC = DAG.getVectorIdxConstant(I, SL);
11000 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec, IC);
11001 if (I == 0)
11002 V = Elt;
11003 else
11004 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
11005 }
11006 return V;
11007 }
11008
11009 if (!DCI.isBeforeLegalize())
11010 return SDValue();
11011
11012 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
11013 // elements. This exposes more load reduction opportunities by replacing
11014 // multiple small extract_vector_elements with a single 32-bit extract.
11015 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11016 if (isa<MemSDNode>(Vec) && VecEltSize <= 16 && VecEltVT.isByteSized() &&
11017 VecSize > 32 && VecSize % 32 == 0 && Idx) {
11018 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
11019
11020 unsigned BitIndex = Idx->getZExtValue() * VecEltSize;
11021 unsigned EltIdx = BitIndex / 32;
11022 unsigned LeftoverBitIdx = BitIndex % 32;
11023 SDLoc SL(N);
11024
11025 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
11026 DCI.AddToWorklist(Cast.getNode());
11027
11028 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
11029 DAG.getConstant(EltIdx, SL, MVT::i32));
11030 DCI.AddToWorklist(Elt.getNode());
11031 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
11032 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
11033 DCI.AddToWorklist(Srl.getNode());
11034
11035 EVT VecEltAsIntVT = VecEltVT.changeTypeToInteger();
11036 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VecEltAsIntVT, Srl);
11037 DCI.AddToWorklist(Trunc.getNode());
11038
11039 if (VecEltVT == ResVT) {
11040 return DAG.getNode(ISD::BITCAST, SL, VecEltVT, Trunc);
11041 }
11042
11043 assert(ResVT.isScalarInteger())(static_cast <bool> (ResVT.isScalarInteger()) ? void (0
) : __assert_fail ("ResVT.isScalarInteger()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11043, __extension__ __PRETTY_FUNCTION__))
;
11044 return DAG.getAnyExtOrTrunc(Trunc, SL, ResVT);
11045 }
11046
11047 return SDValue();
11048}
11049
11050SDValue
11051SITargetLowering::performInsertVectorEltCombine(SDNode *N,
11052 DAGCombinerInfo &DCI) const {
11053 SDValue Vec = N->getOperand(0);
11054 SDValue Idx = N->getOperand(2);
11055 EVT VecVT = Vec.getValueType();
11056 EVT EltVT = VecVT.getVectorElementType();
11057
11058 // INSERT_VECTOR_ELT (<n x e>, var-idx)
11059 // => BUILD_VECTOR n x select (e, const-idx)
11060 if (!shouldExpandVectorDynExt(N))
11061 return SDValue();
11062
11063 SelectionDAG &DAG = DCI.DAG;
11064 SDLoc SL(N);
11065 SDValue Ins = N->getOperand(1);
11066 EVT IdxVT = Idx.getValueType();
11067
11068 SmallVector<SDValue, 16> Ops;
11069 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
11070 SDValue IC = DAG.getConstant(I, SL, IdxVT);
11071 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
11072 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
11073 Ops.push_back(V);
11074 }
11075
11076 return DAG.getBuildVector(VecVT, SL, Ops);
11077}
11078
11079unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
11080 const SDNode *N0,
11081 const SDNode *N1) const {
11082 EVT VT = N0->getValueType(0);
11083
11084 // Only do this if we are not trying to support denormals. v_mad_f32 does not
11085 // support denormals ever.
11086 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
11087 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
11088 getSubtarget()->hasMadF16())) &&
11089 isOperationLegal(ISD::FMAD, VT))
11090 return ISD::FMAD;
11091
11092 const TargetOptions &Options = DAG.getTarget().Options;
11093 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11094 (N0->getFlags().hasAllowContract() &&
11095 N1->getFlags().hasAllowContract())) &&
11096 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
11097 return ISD::FMA;
11098 }
11099
11100 return 0;
11101}
11102
11103// For a reassociatable opcode perform:
11104// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
11105SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
11106 SelectionDAG &DAG) const {
11107 EVT VT = N->getValueType(0);
11108 if (VT != MVT::i32 && VT != MVT::i64)
11109 return SDValue();
11110
11111 if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
11112 return SDValue();
11113
11114 unsigned Opc = N->getOpcode();
11115 SDValue Op0 = N->getOperand(0);
11116 SDValue Op1 = N->getOperand(1);
11117
11118 if (!(Op0->isDivergent() ^ Op1->isDivergent()))
11119 return SDValue();
11120
11121 if (Op0->isDivergent())
11122 std::swap(Op0, Op1);
11123
11124 if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
11125 return SDValue();
11126
11127 SDValue Op2 = Op1.getOperand(1);
11128 Op1 = Op1.getOperand(0);
11129 if (!(Op1->isDivergent() ^ Op2->isDivergent()))
11130 return SDValue();
11131
11132 if (Op1->isDivergent())
11133 std::swap(Op1, Op2);
11134
11135 SDLoc SL(N);
11136 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
11137 return DAG.getNode(Opc, SL, VT, Add1, Op2);
11138}
11139
11140static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
11141 EVT VT,
11142 SDValue N0, SDValue N1, SDValue N2,
11143 bool Signed) {
11144 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
11145 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
11146 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
11147 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
11148}
11149
11150// Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
11151// multiplies, if any.
11152//
11153// Full 64-bit multiplies that feed into an addition are lowered here instead
11154// of using the generic expansion. The generic expansion ends up with
11155// a tree of ADD nodes that prevents us from using the "add" part of the
11156// MAD instruction. The expansion produced here results in a chain of ADDs
11157// instead of a tree.
11158SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
11159 DAGCombinerInfo &DCI) const {
11160 assert(N->getOpcode() == ISD::ADD)(static_cast <bool> (N->getOpcode() == ISD::ADD) ? void
(0) : __assert_fail ("N->getOpcode() == ISD::ADD", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11160, __extension__ __PRETTY_FUNCTION__))
;
11161
11162 SelectionDAG &DAG = DCI.DAG;
11163 EVT VT = N->getValueType(0);
11164 SDLoc SL(N);
11165 SDValue LHS = N->getOperand(0);
11166 SDValue RHS = N->getOperand(1);
11167
11168 if (VT.isVector())
11169 return SDValue();
11170
11171 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
11172 // result in scalar registers for uniform values.
11173 if (!N->isDivergent() && Subtarget->hasSMulHi())
11174 return SDValue();
11175
11176 unsigned NumBits = VT.getScalarSizeInBits();
11177 if (NumBits <= 32 || NumBits > 64)
11178 return SDValue();
11179
11180 if (LHS.getOpcode() != ISD::MUL) {
11181 assert(RHS.getOpcode() == ISD::MUL)(static_cast <bool> (RHS.getOpcode() == ISD::MUL) ? void
(0) : __assert_fail ("RHS.getOpcode() == ISD::MUL", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11181, __extension__ __PRETTY_FUNCTION__))
;
11182 std::swap(LHS, RHS);
11183 }
11184
11185 // Avoid the fold if it would unduly increase the number of multiplies due to
11186 // multiple uses, except on hardware with full-rate multiply-add (which is
11187 // part of full-rate 64-bit ops).
11188 if (!Subtarget->hasFullRate64Ops()) {
11189 unsigned NumUsers = 0;
11190 for (SDNode *Use : LHS->uses()) {
11191 // There is a use that does not feed into addition, so the multiply can't
11192 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
11193 if (Use->getOpcode() != ISD::ADD)
11194 return SDValue();
11195
11196 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
11197 // MUL + 3xADD + 3xADDC over 3xMAD.
11198 ++NumUsers;
11199 if (NumUsers >= 3)
11200 return SDValue();
11201 }
11202 }
11203
11204 SDValue MulLHS = LHS.getOperand(0);
11205 SDValue MulRHS = LHS.getOperand(1);
11206 SDValue AddRHS = RHS;
11207
11208 // Always check whether operands are small unsigned values, since that
11209 // knowledge is useful in more cases. Check for small signed values only if
11210 // doing so can unlock a shorter code sequence.
11211 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
11212 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
11213
11214 bool MulSignedLo = false;
11215 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
11216 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
11217 numBitsSigned(MulRHS, DAG) <= 32;
11218 }
11219
11220 // The operands and final result all have the same number of bits. If
11221 // operands need to be extended, they can be extended with garbage. The
11222 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
11223 // truncated away in the end.
11224 if (VT != MVT::i64) {
11225 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
11226 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
11227 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
11228 }
11229
11230 // The basic code generated is conceptually straightforward. Pseudo code:
11231 //
11232 // accum = mad_64_32 lhs.lo, rhs.lo, accum
11233 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
11234 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
11235 //
11236 // The second and third lines are optional, depending on whether the factors
11237 // are {sign,zero}-extended or not.
11238 //
11239 // The actual DAG is noisier than the pseudo code, but only due to
11240 // instructions that disassemble values into low and high parts, and
11241 // assemble the final result.
11242 SDValue One = DAG.getConstant(1, SL, MVT::i32);
11243
11244 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
11245 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
11246 SDValue Accum =
11247 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
11248
11249 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
11250 SDValue AccumLo, AccumHi;
11251 std::tie(AccumLo, AccumHi) = DAG.SplitScalar(Accum, SL, MVT::i32, MVT::i32);
11252
11253 if (!MulLHSUnsigned32) {
11254 auto MulLHSHi =
11255 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
11256 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
11257 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
11258 }
11259
11260 if (!MulRHSUnsigned32) {
11261 auto MulRHSHi =
11262 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
11263 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
11264 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
11265 }
11266
11267 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
11268 Accum = DAG.getBitcast(MVT::i64, Accum);
11269 }
11270
11271 if (VT != MVT::i64)
11272 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
11273 return Accum;
11274}
11275
11276SDValue SITargetLowering::performAddCombine(SDNode *N,
11277 DAGCombinerInfo &DCI) const {
11278 SelectionDAG &DAG = DCI.DAG;
11279 EVT VT = N->getValueType(0);
11280 SDLoc SL(N);
11281 SDValue LHS = N->getOperand(0);
11282 SDValue RHS = N->getOperand(1);
11283
11284 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
11285 if (Subtarget->hasMad64_32()) {
11286 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
11287 return Folded;
11288 }
11289
11290 return SDValue();
11291 }
11292
11293 if (SDValue V = reassociateScalarOps(N, DAG)) {
11294 return V;
11295 }
11296
11297 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
11298 return SDValue();
11299
11300 // add x, zext (setcc) => uaddo_carry x, 0, setcc
11301 // add x, sext (setcc) => usubo_carry x, 0, setcc
11302 unsigned Opc = LHS.getOpcode();
11303 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
11304 Opc == ISD::ANY_EXTEND || Opc == ISD::UADDO_CARRY)
11305 std::swap(RHS, LHS);
11306
11307 Opc = RHS.getOpcode();
11308 switch (Opc) {
11309 default: break;
11310 case ISD::ZERO_EXTEND:
11311 case ISD::SIGN_EXTEND:
11312 case ISD::ANY_EXTEND: {
11313 auto Cond = RHS.getOperand(0);
11314 // If this won't be a real VOPC output, we would still need to insert an
11315 // extra instruction anyway.
11316 if (!isBoolSGPR(Cond))
11317 break;
11318 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
11319 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
11320 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::USUBO_CARRY : ISD::UADDO_CARRY;
11321 return DAG.getNode(Opc, SL, VTList, Args);
11322 }
11323 case ISD::UADDO_CARRY: {
11324 // add x, (uaddo_carry y, 0, cc) => uaddo_carry x, y, cc
11325 if (!isNullConstant(RHS.getOperand(1)))
11326 break;
11327 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
11328 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), RHS->getVTList(), Args);
11329 }
11330 }
11331 return SDValue();
11332}
11333
11334SDValue SITargetLowering::performSubCombine(SDNode *N,
11335 DAGCombinerInfo &DCI) const {
11336 SelectionDAG &DAG = DCI.DAG;
11337 EVT VT = N->getValueType(0);
11338
11339 if (VT != MVT::i32)
11340 return SDValue();
11341
11342 SDLoc SL(N);
11343 SDValue LHS = N->getOperand(0);
11344 SDValue RHS = N->getOperand(1);
11345
11346 // sub x, zext (setcc) => usubo_carry x, 0, setcc
11347 // sub x, sext (setcc) => uaddo_carry x, 0, setcc
11348 unsigned Opc = RHS.getOpcode();
11349 switch (Opc) {
11350 default: break;
11351 case ISD::ZERO_EXTEND:
11352 case ISD::SIGN_EXTEND:
11353 case ISD::ANY_EXTEND: {
11354 auto Cond = RHS.getOperand(0);
11355 // If this won't be a real VOPC output, we would still need to insert an
11356 // extra instruction anyway.
11357 if (!isBoolSGPR(Cond))
11358 break;
11359 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
11360 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
11361 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
11362 return DAG.getNode(Opc, SL, VTList, Args);
11363 }
11364 }
11365
11366 if (LHS.getOpcode() == ISD::USUBO_CARRY) {
11367 // sub (usubo_carry x, 0, cc), y => usubo_carry x, y, cc
11368 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
11369 if (!C || !C->isZero())
11370 return SDValue();
11371 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
11372 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), LHS->getVTList(), Args);
11373 }
11374 return SDValue();
11375}
11376
11377SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
11378 DAGCombinerInfo &DCI) const {
11379
11380 if (N->getValueType(0) != MVT::i32)
11381 return SDValue();
11382
11383 if (!isNullConstant(N->getOperand(1)))
11384 return SDValue();
11385
11386 SelectionDAG &DAG = DCI.DAG;
11387 SDValue LHS = N->getOperand(0);
11388
11389 // uaddo_carry (add x, y), 0, cc => uaddo_carry x, y, cc
11390 // usubo_carry (sub x, y), 0, cc => usubo_carry x, y, cc
11391 unsigned LHSOpc = LHS.getOpcode();
11392 unsigned Opc = N->getOpcode();
11393 if ((LHSOpc == ISD::ADD && Opc == ISD::UADDO_CARRY) ||
11394 (LHSOpc == ISD::SUB && Opc == ISD::USUBO_CARRY)) {
11395 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
11396 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
11397 }
11398 return SDValue();
11399}
11400
11401SDValue SITargetLowering::performFAddCombine(SDNode *N,
11402 DAGCombinerInfo &DCI) const {
11403 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11404 return SDValue();
11405
11406 SelectionDAG &DAG = DCI.DAG;
11407 EVT VT = N->getValueType(0);
11408
11409 SDLoc SL(N);
11410 SDValue LHS = N->getOperand(0);
11411 SDValue RHS = N->getOperand(1);
11412
11413 // These should really be instruction patterns, but writing patterns with
11414 // source modifiers is a pain.
11415
11416 // fadd (fadd (a, a), b) -> mad 2.0, a, b
11417 if (LHS.getOpcode() == ISD::FADD) {
11418 SDValue A = LHS.getOperand(0);
11419 if (A == LHS.getOperand(1)) {
11420 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11421 if (FusedOp != 0) {
11422 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11423 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
11424 }
11425 }
11426 }
11427
11428 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
11429 if (RHS.getOpcode() == ISD::FADD) {
11430 SDValue A = RHS.getOperand(0);
11431 if (A == RHS.getOperand(1)) {
11432 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11433 if (FusedOp != 0) {
11434 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11435 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
11436 }
11437 }
11438 }
11439
11440 return SDValue();
11441}
11442
11443SDValue SITargetLowering::performFSubCombine(SDNode *N,
11444 DAGCombinerInfo &DCI) const {
11445 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11446 return SDValue();
11447
11448 SelectionDAG &DAG = DCI.DAG;
11449 SDLoc SL(N);
11450 EVT VT = N->getValueType(0);
11451 assert(!VT.isVector())(static_cast <bool> (!VT.isVector()) ? void (0) : __assert_fail
("!VT.isVector()", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11451, __extension__ __PRETTY_FUNCTION__))
;
11452
11453 // Try to get the fneg to fold into the source modifier. This undoes generic
11454 // DAG combines and folds them into the mad.
11455 //
11456 // Only do this if we are not trying to support denormals. v_mad_f32 does
11457 // not support denormals ever.
11458 SDValue LHS = N->getOperand(0);
11459 SDValue RHS = N->getOperand(1);
11460 if (LHS.getOpcode() == ISD::FADD) {
11461 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
11462 SDValue A = LHS.getOperand(0);
11463 if (A == LHS.getOperand(1)) {
11464 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11465 if (FusedOp != 0){
11466 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11467 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
11468
11469 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
11470 }
11471 }
11472 }
11473
11474 if (RHS.getOpcode() == ISD::FADD) {
11475 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
11476
11477 SDValue A = RHS.getOperand(0);
11478 if (A == RHS.getOperand(1)) {
11479 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11480 if (FusedOp != 0){
11481 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
11482 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
11483 }
11484 }
11485 }
11486
11487 return SDValue();
11488}
11489
11490SDValue SITargetLowering::performFMACombine(SDNode *N,
11491 DAGCombinerInfo &DCI) const {
11492 SelectionDAG &DAG = DCI.DAG;
11493 EVT VT = N->getValueType(0);
11494 SDLoc SL(N);
11495
11496 if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
11497 return SDValue();
11498
11499 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
11500 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
11501 SDValue Op1 = N->getOperand(0);
11502 SDValue Op2 = N->getOperand(1);
11503 SDValue FMA = N->getOperand(2);
11504
11505 if (FMA.getOpcode() != ISD::FMA ||
11506 Op1.getOpcode() != ISD::FP_EXTEND ||
11507 Op2.getOpcode() != ISD::FP_EXTEND)
11508 return SDValue();
11509
11510 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
11511 // regardless of the denorm mode setting. Therefore,
11512 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
11513 const TargetOptions &Options = DAG.getTarget().Options;
11514 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11515 (N->getFlags().hasAllowContract() &&
11516 FMA->getFlags().hasAllowContract())) {
11517 Op1 = Op1.getOperand(0);
11518 Op2 = Op2.getOperand(0);
11519 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11520 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11521 return SDValue();
11522
11523 SDValue Vec1 = Op1.getOperand(0);
11524 SDValue Idx1 = Op1.getOperand(1);
11525 SDValue Vec2 = Op2.getOperand(0);
11526
11527 SDValue FMAOp1 = FMA.getOperand(0);
11528 SDValue FMAOp2 = FMA.getOperand(1);
11529 SDValue FMAAcc = FMA.getOperand(2);
11530
11531 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
11532 FMAOp2.getOpcode() != ISD::FP_EXTEND)
11533 return SDValue();
11534
11535 FMAOp1 = FMAOp1.getOperand(0);
11536 FMAOp2 = FMAOp2.getOperand(0);
11537 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11538 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11539 return SDValue();
11540
11541 SDValue Vec3 = FMAOp1.getOperand(0);
11542 SDValue Vec4 = FMAOp2.getOperand(0);
11543 SDValue Idx2 = FMAOp1.getOperand(1);
11544
11545 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11546 // Idx1 and Idx2 cannot be the same.
11547 Idx1 == Idx2)
11548 return SDValue();
11549
11550 if (Vec1 == Vec2 || Vec3 == Vec4)
11551 return SDValue();
11552
11553 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11554 return SDValue();
11555
11556 if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11557 (Vec1 == Vec4 && Vec2 == Vec3)) {
11558 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11559 DAG.getTargetConstant(0, SL, MVT::i1));
11560 }
11561 }
11562 return SDValue();
11563}
11564
11565SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11566 DAGCombinerInfo &DCI) const {
11567 SelectionDAG &DAG = DCI.DAG;
11568 SDLoc SL(N);
11569
11570 SDValue LHS = N->getOperand(0);
11571 SDValue RHS = N->getOperand(1);
11572 EVT VT = LHS.getValueType();
11573 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11574
11575 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11576 if (!CRHS) {
11577 CRHS = dyn_cast<ConstantSDNode>(LHS);
11578 if (CRHS) {
11579 std::swap(LHS, RHS);
11580 CC = getSetCCSwappedOperands(CC);
11581 }
11582 }
11583
11584 if (CRHS) {
11585 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11586 isBoolSGPR(LHS.getOperand(0))) {
11587 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11588 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11589 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
11590 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
11591 if ((CRHS->isAllOnes() &&
11592 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11593 (CRHS->isZero() &&
11594 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11595 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11596 DAG.getConstant(-1, SL, MVT::i1));
11597 if ((CRHS->isAllOnes() &&
11598 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11599 (CRHS->isZero() &&
11600 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11601 return LHS.getOperand(0);
11602 }
11603
11604 const APInt &CRHSVal = CRHS->getAPIntValue();
11605 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11606 LHS.getOpcode() == ISD::SELECT &&
11607 isa<ConstantSDNode>(LHS.getOperand(1)) &&
11608 isa<ConstantSDNode>(LHS.getOperand(2)) &&
11609 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11610 isBoolSGPR(LHS.getOperand(0))) {
11611 // Given CT != FT:
11612 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11613 // setcc (select cc, CT, CF), CF, ne => cc
11614 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11615 // setcc (select cc, CT, CF), CT, eq => cc
11616 const APInt &CT = LHS.getConstantOperandAPInt(1);
11617 const APInt &CF = LHS.getConstantOperandAPInt(2);
11618
11619 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11620 (CT == CRHSVal && CC == ISD::SETNE))
11621 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11622 DAG.getConstant(-1, SL, MVT::i1));
11623 if ((CF == CRHSVal && CC == ISD::SETNE) ||
11624 (CT == CRHSVal && CC == ISD::SETEQ))
11625 return LHS.getOperand(0);
11626 }
11627 }
11628
11629 if (VT != MVT::f32 && VT != MVT::f64 &&
11630 (!Subtarget->has16BitInsts() || VT != MVT::f16))
11631 return SDValue();
11632
11633 // Match isinf/isfinite pattern
11634 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11635 // (fcmp one (fabs x), inf) -> (fp_class x,
11636 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11637 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11638 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11639 if (!CRHS)
11640 return SDValue();
11641
11642 const APFloat &APF = CRHS->getValueAPF();
11643 if (APF.isInfinity() && !APF.isNegative()) {
11644 const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11645 SIInstrFlags::N_INFINITY;
11646 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11647 SIInstrFlags::P_ZERO |
11648 SIInstrFlags::N_NORMAL |
11649 SIInstrFlags::P_NORMAL |
11650 SIInstrFlags::N_SUBNORMAL |
11651 SIInstrFlags::P_SUBNORMAL;
11652 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11653 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11654 DAG.getConstant(Mask, SL, MVT::i32));
11655 }
11656 }
11657
11658 return SDValue();
11659}
11660
11661SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11662 DAGCombinerInfo &DCI) const {
11663 SelectionDAG &DAG = DCI.DAG;
11664 SDLoc SL(N);
11665 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11666
11667 SDValue Src = N->getOperand(0);
11668 SDValue Shift = N->getOperand(0);
11669
11670 // TODO: Extend type shouldn't matter (assuming legal types).
11671 if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11672 Shift = Shift.getOperand(0);
11673
11674 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11675 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x
11676 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11677 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11678 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11679 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
11680 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11681 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11682 SDLoc(Shift.getOperand(0)), MVT::i32);
11683
11684 unsigned ShiftOffset = 8 * Offset;
11685 if (Shift.getOpcode() == ISD::SHL)
11686 ShiftOffset -= C->getZExtValue();
11687 else
11688 ShiftOffset += C->getZExtValue();
11689
11690 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11691 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11692 MVT::f32, Shifted);
11693 }
11694 }
11695 }
11696
11697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11698 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11699 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11700 // We simplified Src. If this node is not dead, visit it again so it is
11701 // folded properly.
11702 if (N->getOpcode() != ISD::DELETED_NODE)
11703 DCI.AddToWorklist(N);
11704 return SDValue(N, 0);
11705 }
11706
11707 // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11708 if (SDValue DemandedSrc =
11709 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11710 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11711
11712 return SDValue();
11713}
11714
11715SDValue SITargetLowering::performClampCombine(SDNode *N,
11716 DAGCombinerInfo &DCI) const {
11717 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11718 if (!CSrc)
11719 return SDValue();
11720
11721 const MachineFunction &MF = DCI.DAG.getMachineFunction();
11722 const APFloat &F = CSrc->getValueAPF();
11723 APFloat Zero = APFloat::getZero(F.getSemantics());
11724 if (F < Zero ||
11725 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11726 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11727 }
11728
11729 APFloat One(F.getSemantics(), "1.0");
11730 if (F > One)
11731 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11732
11733 return SDValue(CSrc, 0);
11734}
11735
11736
11737SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11738 DAGCombinerInfo &DCI) const {
11739 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11740 return SDValue();
11741 switch (N->getOpcode()) {
11742 case ISD::ADD:
11743 return performAddCombine(N, DCI);
11744 case ISD::SUB:
11745 return performSubCombine(N, DCI);
11746 case ISD::UADDO_CARRY:
11747 case ISD::USUBO_CARRY:
11748 return performAddCarrySubCarryCombine(N, DCI);
11749 case ISD::FADD:
11750 return performFAddCombine(N, DCI);
11751 case ISD::FSUB:
11752 return performFSubCombine(N, DCI);
11753 case ISD::SETCC:
11754 return performSetCCCombine(N, DCI);
11755 case ISD::FMAXNUM:
11756 case ISD::FMINNUM:
11757 case ISD::FMAXNUM_IEEE:
11758 case ISD::FMINNUM_IEEE:
11759 case ISD::SMAX:
11760 case ISD::SMIN:
11761 case ISD::UMAX:
11762 case ISD::UMIN:
11763 case AMDGPUISD::FMIN_LEGACY:
11764 case AMDGPUISD::FMAX_LEGACY:
11765 return performMinMaxCombine(N, DCI);
11766 case ISD::FMA:
11767 return performFMACombine(N, DCI);
11768 case ISD::AND:
11769 return performAndCombine(N, DCI);
11770 case ISD::OR:
11771 return performOrCombine(N, DCI);
11772 case ISD::XOR:
11773 return performXorCombine(N, DCI);
11774 case ISD::ZERO_EXTEND:
11775 return performZeroExtendCombine(N, DCI);
11776 case ISD::SIGN_EXTEND_INREG:
11777 return performSignExtendInRegCombine(N , DCI);
11778 case AMDGPUISD::FP_CLASS:
11779 return performClassCombine(N, DCI);
11780 case ISD::FCANONICALIZE:
11781 return performFCanonicalizeCombine(N, DCI);
11782 case AMDGPUISD::RCP:
11783 return performRcpCombine(N, DCI);
11784 case AMDGPUISD::FRACT:
11785 case AMDGPUISD::RSQ:
11786 case AMDGPUISD::RCP_LEGACY:
11787 case AMDGPUISD::RCP_IFLAG:
11788 case AMDGPUISD::RSQ_CLAMP:
11789 case AMDGPUISD::LDEXP: {
11790 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11791 SDValue Src = N->getOperand(0);
11792 if (Src.isUndef())
11793 return Src;
11794 break;
11795 }
11796 case ISD::SINT_TO_FP:
11797 case ISD::UINT_TO_FP:
11798 return performUCharToFloatCombine(N, DCI);
11799 case ISD::FCOPYSIGN:
11800 return performFCopySignCombine(N, DCI);
11801 case AMDGPUISD::CVT_F32_UBYTE0:
11802 case AMDGPUISD::CVT_F32_UBYTE1:
11803 case AMDGPUISD::CVT_F32_UBYTE2:
11804 case AMDGPUISD::CVT_F32_UBYTE3:
11805 return performCvtF32UByteNCombine(N, DCI);
11806 case AMDGPUISD::FMED3:
11807 return performFMed3Combine(N, DCI);
11808 case AMDGPUISD::CVT_PKRTZ_F16_F32:
11809 return performCvtPkRTZCombine(N, DCI);
11810 case AMDGPUISD::CLAMP:
11811 return performClampCombine(N, DCI);
11812 case ISD::SCALAR_TO_VECTOR: {
11813 SelectionDAG &DAG = DCI.DAG;
11814 EVT VT = N->getValueType(0);
11815
11816 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11817 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11818 SDLoc SL(N);
11819 SDValue Src = N->getOperand(0);
11820 EVT EltVT = Src.getValueType();
11821 if (EltVT == MVT::f16)
11822 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11823
11824 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11825 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11826 }
11827
11828 break;
11829 }
11830 case ISD::EXTRACT_VECTOR_ELT:
11831 return performExtractVectorEltCombine(N, DCI);
11832 case ISD::INSERT_VECTOR_ELT:
11833 return performInsertVectorEltCombine(N, DCI);
11834 case ISD::LOAD: {
11835 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11836 return Widended;
11837 [[fallthrough]];
11838 }
11839 default: {
11840 if (!DCI.isBeforeLegalize()) {
11841 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11842 return performMemSDNodeCombine(MemNode, DCI);
11843 }
11844
11845 break;
11846 }
11847 }
11848
11849 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11850}
11851
11852/// Helper function for adjustWritemask
11853static unsigned SubIdx2Lane(unsigned Idx) {
11854 switch (Idx) {
11855 default: return ~0u;
11856 case AMDGPU::sub0: return 0;
11857 case AMDGPU::sub1: return 1;
11858 case AMDGPU::sub2: return 2;
11859 case AMDGPU::sub3: return 3;
11860 case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11861 }
11862}
11863
11864/// Adjust the writemask of MIMG instructions
11865SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11866 SelectionDAG &DAG) const {
11867 unsigned Opcode = Node->getMachineOpcode();
11868
11869 // Subtract 1 because the vdata output is not a MachineSDNode operand.
11870 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11871 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
6
Assuming 'D16Idx' is < 0
11872 return Node; // not implemented for D16
11873
11874 SDNode *Users[5] = { nullptr };
7
Initializing to a null pointer value
11875 unsigned Lane = 0;
8
'Lane' initialized to 0
11876 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11877 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11878 unsigned NewDmask = 0;
11879 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11880 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11881 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
9
Assuming 'TFEIdx' is >= 0
10
Assuming the condition is true
11882 Node->getConstantOperandVal(LWEIdx))
11883 ? true
11884 : false;
11885 unsigned TFCLane = 0;
11886 bool HasChain = Node->getNumValues() > 1;
11
Assuming the condition is false
11887
11888 if (OldDmask == 0) {
12
Assuming 'OldDmask' is not equal to 0
13
Taking false branch
11889 // These are folded out, but on the chance it happens don't assert.
11890 return Node;
11891 }
11892
11893 unsigned OldBitsSet = llvm::popcount(OldDmask);
11894 // Work out which is the TFE/LWE lane if that is enabled.
11895 if (UsesTFC
13.1
'UsesTFC' is true
) {
14
Taking true branch
11896 TFCLane = OldBitsSet;
11897 }
11898
11899 // Try to figure out the used register components
11900 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
15
Loop condition is false. Execution continues on line 11941
11901 I != E; ++I) {
11902
11903 // Don't look at users of the chain.
11904 if (I.getUse().getResNo() != 0)
11905 continue;
11906
11907 // Abort if we can't understand the usage
11908 if (!I->isMachineOpcode() ||
11909 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11910 return Node;
11911
11912 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11913 // Note that subregs are packed, i.e. Lane==0 is the first bit set
11914 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11915 // set, etc.
11916 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11917 if (Lane == ~0u)
11918 return Node;
11919
11920 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11921 if (UsesTFC && Lane == TFCLane) {
11922 Users[Lane] = *I;
11923 } else {
11924 // Set which texture component corresponds to the lane.
11925 unsigned Comp;
11926 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11927 Comp = llvm::countr_zero(Dmask);
11928 Dmask &= ~(1 << Comp);
11929 }
11930
11931 // Abort if we have more than one user per component.
11932 if (Users[Lane])
11933 return Node;
11934
11935 Users[Lane] = *I;
11936 NewDmask |= 1 << Comp;
11937 }
11938 }
11939
11940 // Don't allow 0 dmask, as hardware assumes one channel enabled.
11941 bool NoChannels = !NewDmask;
11942 if (NoChannels
15.1
'NoChannels' is true
) {
16
Taking true branch
11943 if (!UsesTFC
16.1
'UsesTFC' is true
) {
17
Taking false branch
11944 // No uses of the result and not using TFC. Then do nothing.
11945 return Node;
11946 }
11947 // If the original dmask has one channel - then nothing to do
11948 if (OldBitsSet == 1)
18
Assuming 'OldBitsSet' is not equal to 1
19
Taking false branch
11949 return Node;
11950 // Use an arbitrary dmask - required for the instruction to work
11951 NewDmask = 1;
11952 }
11953 // Abort if there's no change
11954 if (NewDmask == OldDmask)
20
Assuming 'NewDmask' is not equal to 'OldDmask'
21
Taking false branch
11955 return Node;
11956
11957 unsigned BitsSet = llvm::popcount(NewDmask);
11958
11959 // Check for TFE or LWE - increase the number of channels by one to account
11960 // for the extra return value
11961 // This will need adjustment for D16 if this is also included in
11962 // adjustWriteMask (this function) but at present D16 are excluded.
11963 unsigned NewChannels = BitsSet + UsesTFC;
11964
11965 int NewOpcode =
11966 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11967 assert(NewOpcode != -1 &&(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 11969, __extension__
__PRETTY_FUNCTION__))
22
Assuming the condition is true
23
Assuming the condition is true
24
'?' condition is true
11968 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 11969, __extension__
__PRETTY_FUNCTION__))
11969 "failed to find equivalent MIMG op")(static_cast <bool> (NewOpcode != -1 && NewOpcode
!= static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op") ? void (0) : __assert_fail
("NewOpcode != -1 && NewOpcode != static_cast<int>(Node->getMachineOpcode()) && \"failed to find equivalent MIMG op\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 11969, __extension__
__PRETTY_FUNCTION__))
;
11970
11971 // Adjust the writemask in the node
11972 SmallVector<SDValue, 12> Ops;
11973 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11974 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11975 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11976
11977 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11978
11979 MVT ResultVT = NewChannels == 1 ?
25
Assuming 'NewChannels' is equal to 1
26
'?' condition is true
11980 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11981 NewChannels == 5 ? 8 : NewChannels);
11982 SDVTList NewVTList = HasChain
26.1
'HasChain' is false
?
27
'?' condition is false
11983 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11984
11985
11986 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11987 NewVTList, Ops);
11988
11989 if (HasChain
27.1
'HasChain' is false
) {
28
Taking false branch
11990 // Update chain.
11991 DAG.setNodeMemRefs(NewNode, Node->memoperands());
11992 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11993 }
11994
11995 if (NewChannels
28.1
'NewChannels' is equal to 1
== 1) {
29
Taking true branch
11996 assert(Node->hasNUsesOfValue(1, 0))(static_cast <bool> (Node->hasNUsesOfValue(1, 0)) ? void
(0) : __assert_fail ("Node->hasNUsesOfValue(1, 0)", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 11996, __extension__ __PRETTY_FUNCTION__))
;
30
Assuming the condition is true
31
'?' condition is true
11997 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11998 SDLoc(Node), Users[Lane]->getValueType(0),
32
Called C++ object pointer is null
11999 SDValue(NewNode, 0));
12000 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
12001 return nullptr;
12002 }
12003
12004 // Update the users of the node with the new indices
12005 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
12006 SDNode *User = Users[i];
12007 if (!User) {
12008 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
12009 // Users[0] is still nullptr because channel 0 doesn't really have a use.
12010 if (i || !NoChannels)
12011 continue;
12012 } else {
12013 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
12014 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
12015 }
12016
12017 switch (Idx) {
12018 default: break;
12019 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
12020 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
12021 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
12022 case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
12023 }
12024 }
12025
12026 DAG.RemoveDeadNode(Node);
12027 return nullptr;
12028}
12029
12030static bool isFrameIndexOp(SDValue Op) {
12031 if (Op.getOpcode() == ISD::AssertZext)
12032 Op = Op.getOperand(0);
12033
12034 return isa<FrameIndexSDNode>(Op);
12035}
12036
12037/// Legalize target independent instructions (e.g. INSERT_SUBREG)
12038/// with frame index operands.
12039/// LLVM assumes that inputs are to these instructions are registers.
12040SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
12041 SelectionDAG &DAG) const {
12042 if (Node->getOpcode() == ISD::CopyToReg) {
12043 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
12044 SDValue SrcVal = Node->getOperand(2);
12045
12046 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
12047 // to try understanding copies to physical registers.
12048 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
12049 SDLoc SL(Node);
12050 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12051 SDValue VReg = DAG.getRegister(
12052 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
12053
12054 SDNode *Glued = Node->getGluedNode();
12055 SDValue ToVReg
12056 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
12057 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
12058 SDValue ToResultReg
12059 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
12060 VReg, ToVReg.getValue(1));
12061 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
12062 DAG.RemoveDeadNode(Node);
12063 return ToResultReg.getNode();
12064 }
12065 }
12066
12067 SmallVector<SDValue, 8> Ops;
12068 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
12069 if (!isFrameIndexOp(Node->getOperand(i))) {
12070 Ops.push_back(Node->getOperand(i));
12071 continue;
12072 }
12073
12074 SDLoc DL(Node);
12075 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
12076 Node->getOperand(i).getValueType(),
12077 Node->getOperand(i)), 0));
12078 }
12079
12080 return DAG.UpdateNodeOperands(Node, Ops);
12081}
12082
12083/// Fold the instructions after selecting them.
12084/// Returns null if users were already updated.
12085SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
12086 SelectionDAG &DAG) const {
12087 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12088 unsigned Opcode = Node->getMachineOpcode();
12089
12090 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
1
Assuming the condition is true
2
Assuming the condition is true
4
Taking true branch
12091 !TII->isGather4(Opcode) &&
3
Assuming the condition is true
12092 AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::dmask)) {
12093 return adjustWritemask(Node, DAG);
5
Calling 'SITargetLowering::adjustWritemask'
12094 }
12095
12096 if (Opcode == AMDGPU::INSERT_SUBREG ||
12097 Opcode == AMDGPU::REG_SEQUENCE) {
12098 legalizeTargetIndependentNode(Node, DAG);
12099 return Node;
12100 }
12101
12102 switch (Opcode) {
12103 case AMDGPU::V_DIV_SCALE_F32_e64:
12104 case AMDGPU::V_DIV_SCALE_F64_e64: {
12105 // Satisfy the operand register constraint when one of the inputs is
12106 // undefined. Ordinarily each undef value will have its own implicit_def of
12107 // a vreg, so force these to use a single register.
12108 SDValue Src0 = Node->getOperand(1);
12109 SDValue Src1 = Node->getOperand(3);
12110 SDValue Src2 = Node->getOperand(5);
12111
12112 if ((Src0.isMachineOpcode() &&
12113 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
12114 (Src0 == Src1 || Src0 == Src2))
12115 break;
12116
12117 MVT VT = Src0.getValueType().getSimpleVT();
12118 const TargetRegisterClass *RC =
12119 getRegClassFor(VT, Src0.getNode()->isDivergent());
12120
12121 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12122 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
12123
12124 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
12125 UndefReg, Src0, SDValue());
12126
12127 // src0 must be the same register as src1 or src2, even if the value is
12128 // undefined, so make sure we don't violate this constraint.
12129 if (Src0.isMachineOpcode() &&
12130 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
12131 if (Src1.isMachineOpcode() &&
12132 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
12133 Src0 = Src1;
12134 else if (Src2.isMachineOpcode() &&
12135 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
12136 Src0 = Src2;
12137 else {
12138 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)(static_cast <bool> (Src1.getMachineOpcode() == AMDGPU::
IMPLICIT_DEF) ? void (0) : __assert_fail ("Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 12138, __extension__
__PRETTY_FUNCTION__))
;
12139 Src0 = UndefReg;
12140 Src1 = UndefReg;
12141 }
12142 } else
12143 break;
12144
12145 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
12146 Ops[1] = Src0;
12147 Ops[3] = Src1;
12148 Ops[5] = Src2;
12149 Ops.push_back(ImpDef.getValue(1));
12150 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
12151 }
12152 default:
12153 break;
12154 }
12155
12156 return Node;
12157}
12158
12159// Any MIMG instructions that use tfe or lwe require an initialization of the
12160// result register that will be written in the case of a memory access failure.
12161// The required code is also added to tie this init code to the result of the
12162// img instruction.
12163void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
12164 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12165 const SIRegisterInfo &TRI = TII->getRegisterInfo();
12166 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
12167 MachineBasicBlock &MBB = *MI.getParent();
12168
12169 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
12170 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
12171 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
12172
12173 if (!TFE && !LWE) // intersect_ray
12174 return;
12175
12176 unsigned TFEVal = TFE ? TFE->getImm() : 0;
12177 unsigned LWEVal = LWE->getImm();
12178 unsigned D16Val = D16 ? D16->getImm() : 0;
12179
12180 if (!TFEVal && !LWEVal)
12181 return;
12182
12183 // At least one of TFE or LWE are non-zero
12184 // We have to insert a suitable initialization of the result value and
12185 // tie this to the dest of the image instruction.
12186
12187 const DebugLoc &DL = MI.getDebugLoc();
12188
12189 int DstIdx =
12190 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
12191
12192 // Calculate which dword we have to initialize to 0.
12193 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
12194
12195 // check that dmask operand is found.
12196 assert(MO_Dmask && "Expected dmask operand in instruction")(static_cast <bool> (MO_Dmask && "Expected dmask operand in instruction"
) ? void (0) : __assert_fail ("MO_Dmask && \"Expected dmask operand in instruction\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 12196, __extension__
__PRETTY_FUNCTION__))
;
12197
12198 unsigned dmask = MO_Dmask->getImm();
12199 // Determine the number of active lanes taking into account the
12200 // Gather4 special case
12201 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : llvm::popcount(dmask);
12202
12203 bool Packed = !Subtarget->hasUnpackedD16VMem();
12204
12205 unsigned InitIdx =
12206 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
12207
12208 // Abandon attempt if the dst size isn't large enough
12209 // - this is in fact an error but this is picked up elsewhere and
12210 // reported correctly.
12211 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
12212 if (DstSize < InitIdx)
12213 return;
12214
12215 // Create a register for the initialization value.
12216 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
12217 unsigned NewDst = 0; // Final initialized value will be in here
12218
12219 // If PRTStrictNull feature is enabled (the default) then initialize
12220 // all the result registers to 0, otherwise just the error indication
12221 // register (VGPRn+1)
12222 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
12223 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
12224
12225 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
12226 for (; SizeLeft; SizeLeft--, CurrIdx++) {
12227 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
12228 // Initialize dword
12229 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
12230 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
12231 .addImm(0);
12232 // Insert into the super-reg
12233 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
12234 .addReg(PrevDst)
12235 .addReg(SubReg)
12236 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
12237
12238 PrevDst = NewDst;
12239 }
12240
12241 // Add as an implicit operand
12242 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
12243
12244 // Tie the just added implicit operand to the dst
12245 MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
12246}
12247
12248/// Assign the register class depending on the number of
12249/// bits set in the writemask
12250void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12251 SDNode *Node) const {
12252 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12253
12254 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
12255
12256 if (TII->isVOP3(MI.getOpcode())) {
12257 // Make sure constant bus requirements are respected.
12258 TII->legalizeOperandsVOP3(MRI, MI);
12259
12260 // Prefer VGPRs over AGPRs in mAI instructions where possible.
12261 // This saves a chain-copy of registers and better balance register
12262 // use between vgpr and agpr as agpr tuples tend to be big.
12263 if (!MI.getDesc().operands().empty()) {
12264 unsigned Opc = MI.getOpcode();
12265 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12266 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
12267 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
12268 if (I == -1)
12269 break;
12270 MachineOperand &Op = MI.getOperand(I);
12271 if (!Op.isReg() || !Op.getReg().isVirtual())
12272 continue;
12273 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
12274 if (!TRI->hasAGPRs(RC))
12275 continue;
12276 auto *Src = MRI.getUniqueVRegDef(Op.getReg());
12277 if (!Src || !Src->isCopy() ||
12278 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
12279 continue;
12280 auto *NewRC = TRI->getEquivalentVGPRClass(RC);
12281 // All uses of agpr64 and agpr32 can also accept vgpr except for
12282 // v_accvgpr_read, but we do not produce agpr reads during selection,
12283 // so no use checks are needed.
12284 MRI.setRegClass(Op.getReg(), NewRC);
12285 }
12286
12287 // Resolve the rest of AV operands to AGPRs.
12288 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
12289 if (Src2->isReg() && Src2->getReg().isVirtual()) {
12290 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
12291 if (TRI->isVectorSuperClass(RC)) {
12292 auto *NewRC = TRI->getEquivalentAGPRClass(RC);
12293 MRI.setRegClass(Src2->getReg(), NewRC);
12294 if (Src2->isTied())
12295 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
12296 }
12297 }
12298 }
12299 }
12300
12301 return;
12302 }
12303
12304 if (TII->isMIMG(MI)) {
12305 if (!MI.mayStore())
12306 AddIMGInit(MI);
12307 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
12308 }
12309}
12310
12311static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
12312 uint64_t Val) {
12313 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
12314 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
12315}
12316
12317MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
12318 const SDLoc &DL,
12319 SDValue Ptr) const {
12320 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12321
12322 // Build the half of the subregister with the constants before building the
12323 // full 128-bit register. If we are building multiple resource descriptors,
12324 // this will allow CSEing of the 2-component register.
12325 const SDValue Ops0[] = {
12326 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
12327 buildSMovImm32(DAG, DL, 0),
12328 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
12329 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
12330 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
12331 };
12332
12333 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
12334 MVT::v2i32, Ops0), 0);
12335
12336 // Combine the constants and the pointer.
12337 const SDValue Ops1[] = {
12338 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
12339 Ptr,
12340 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
12341 SubRegHi,
12342 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
12343 };
12344
12345 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
12346}
12347
12348/// Return a resource descriptor with the 'Add TID' bit enabled
12349/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
12350/// of the resource descriptor) to create an offset, which is added to
12351/// the resource pointer.
12352MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
12353 SDValue Ptr, uint32_t RsrcDword1,
12354 uint64_t RsrcDword2And3) const {
12355 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
12356 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
12357 if (RsrcDword1) {
12358 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
12359 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
12360 0);
12361 }
12362
12363 SDValue DataLo = buildSMovImm32(DAG, DL,
12364 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)0xFFFFFFFFUL);
12365 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
12366
12367 const SDValue Ops[] = {
12368 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
12369 PtrLo,
12370 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
12371 PtrHi,
12372 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
12373 DataLo,
12374 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
12375 DataHi,
12376 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
12377 };
12378
12379 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
12380}
12381
12382//===----------------------------------------------------------------------===//
12383// SI Inline Assembly Support
12384//===----------------------------------------------------------------------===//
12385
12386std::pair<unsigned, const TargetRegisterClass *>
12387SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
12388 StringRef Constraint,
12389 MVT VT) const {
12390 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
12391
12392 const TargetRegisterClass *RC = nullptr;
12393 if (Constraint.size() == 1) {
12394 const unsigned BitWidth = VT.getSizeInBits();
12395 switch (Constraint[0]) {
12396 default:
12397 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12398 case 's':
12399 case 'r':
12400 switch (BitWidth) {
12401 case 16:
12402 RC = &AMDGPU::SReg_32RegClass;
12403 break;
12404 case 64:
12405 RC = &AMDGPU::SGPR_64RegClass;
12406 break;
12407 default:
12408 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
12409 if (!RC)
12410 return std::pair(0U, nullptr);
12411 break;
12412 }
12413 break;
12414 case 'v':
12415 switch (BitWidth) {
12416 case 16:
12417 RC = &AMDGPU::VGPR_32RegClass;
12418 break;
12419 default:
12420 RC = TRI->getVGPRClassForBitWidth(BitWidth);
12421 if (!RC)
12422 return std::pair(0U, nullptr);
12423 break;
12424 }
12425 break;
12426 case 'a':
12427 if (!Subtarget->hasMAIInsts())
12428 break;
12429 switch (BitWidth) {
12430 case 16:
12431 RC = &AMDGPU::AGPR_32RegClass;
12432 break;
12433 default:
12434 RC = TRI->getAGPRClassForBitWidth(BitWidth);
12435 if (!RC)
12436 return std::pair(0U, nullptr);
12437 break;
12438 }
12439 break;
12440 }
12441 // We actually support i128, i16 and f16 as inline parameters
12442 // even if they are not reported as legal
12443 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
12444 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
12445 return std::pair(0U, RC);
12446 }
12447
12448 if (Constraint.startswith("{") && Constraint.endswith("}")) {
12449 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
12450 if (RegName.consume_front("v")) {
12451 RC = &AMDGPU::VGPR_32RegClass;
12452 } else if (RegName.consume_front("s")) {
12453 RC = &AMDGPU::SGPR_32RegClass;
12454 } else if (RegName.consume_front("a")) {
12455 RC = &AMDGPU::AGPR_32RegClass;
12456 }
12457
12458 if (RC) {
12459 uint32_t Idx;
12460 if (RegName.consume_front("[")) {
12461 uint32_t End;
12462 bool Failed = RegName.consumeInteger(10, Idx);
12463 Failed |= !RegName.consume_front(":");
12464 Failed |= RegName.consumeInteger(10, End);
12465 Failed |= !RegName.consume_back("]");
12466 if (!Failed) {
12467 uint32_t Width = (End - Idx + 1) * 32;
12468 MCRegister Reg = RC->getRegister(Idx);
12469 if (SIRegisterInfo::isVGPRClass(RC))
12470 RC = TRI->getVGPRClassForBitWidth(Width);
12471 else if (SIRegisterInfo::isSGPRClass(RC))
12472 RC = TRI->getSGPRClassForBitWidth(Width);
12473 else if (SIRegisterInfo::isAGPRClass(RC))
12474 RC = TRI->getAGPRClassForBitWidth(Width);
12475 if (RC) {
12476 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
12477 return std::pair(Reg, RC);
12478 }
12479 }
12480 } else {
12481 bool Failed = RegName.getAsInteger(10, Idx);
12482 if (!Failed && Idx < RC->getNumRegs())
12483 return std::pair(RC->getRegister(Idx), RC);
12484 }
12485 }
12486 }
12487
12488 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12489 if (Ret.first)
12490 Ret.second = TRI->getPhysRegBaseClass(Ret.first);
12491
12492 return Ret;
12493}
12494
12495static bool isImmConstraint(StringRef Constraint) {
12496 if (Constraint.size() == 1) {
12497 switch (Constraint[0]) {
12498 default: break;
12499 case 'I':
12500 case 'J':
12501 case 'A':
12502 case 'B':
12503 case 'C':
12504 return true;
12505 }
12506 } else if (Constraint == "DA" ||
12507 Constraint == "DB") {
12508 return true;
12509 }
12510 return false;
12511}
12512
12513SITargetLowering::ConstraintType
12514SITargetLowering::getConstraintType(StringRef Constraint) const {
12515 if (Constraint.size() == 1) {
12516 switch (Constraint[0]) {
12517 default: break;
12518 case 's':
12519 case 'v':
12520 case 'a':
12521 return C_RegisterClass;
12522 }
12523 }
12524 if (isImmConstraint(Constraint)) {
12525 return C_Other;
12526 }
12527 return TargetLowering::getConstraintType(Constraint);
12528}
12529
12530static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
12531 if (!AMDGPU::isInlinableIntLiteral(Val)) {
12532 Val = Val & maskTrailingOnes<uint64_t>(Size);
12533 }
12534 return Val;
12535}
12536
12537void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12538 std::string &Constraint,
12539 std::vector<SDValue> &Ops,
12540 SelectionDAG &DAG) const {
12541 if (isImmConstraint(Constraint)) {
12542 uint64_t Val;
12543 if (getAsmOperandConstVal(Op, Val) &&
12544 checkAsmConstraintVal(Op, Constraint, Val)) {
12545 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
12546 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
12547 }
12548 } else {
12549 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12550 }
12551}
12552
12553bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12554 unsigned Size = Op.getScalarValueSizeInBits();
12555 if (Size > 64)
12556 return false;
12557
12558 if (Size == 16 && !Subtarget->has16BitInsts())
12559 return false;
12560
12561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12562 Val = C->getSExtValue();
12563 return true;
12564 }
12565 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12566 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12567 return true;
12568 }
12569 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12570 if (Size != 16 || Op.getNumOperands() != 2)
12571 return false;
12572 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12573 return false;
12574 if (ConstantSDNode *C = V->getConstantSplatNode()) {
12575 Val = C->getSExtValue();
12576 return true;
12577 }
12578 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12579 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12580 return true;
12581 }
12582 }
12583
12584 return false;
12585}
12586
12587bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12588 const std::string &Constraint,
12589 uint64_t Val) const {
12590 if (Constraint.size() == 1) {
12591 switch (Constraint[0]) {
12592 case 'I':
12593 return AMDGPU::isInlinableIntLiteral(Val);
12594 case 'J':
12595 return isInt<16>(Val);
12596 case 'A':
12597 return checkAsmConstraintValA(Op, Val);
12598 case 'B':
12599 return isInt<32>(Val);
12600 case 'C':
12601 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12602 AMDGPU::isInlinableIntLiteral(Val);
12603 default:
12604 break;
12605 }
12606 } else if (Constraint.size() == 2) {
12607 if (Constraint == "DA") {
12608 int64_t HiBits = static_cast<int32_t>(Val >> 32);
12609 int64_t LoBits = static_cast<int32_t>(Val);
12610 return checkAsmConstraintValA(Op, HiBits, 32) &&
12611 checkAsmConstraintValA(Op, LoBits, 32);
12612 }
12613 if (Constraint == "DB") {
12614 return true;
12615 }
12616 }
12617 llvm_unreachable("Invalid asm constraint")::llvm::llvm_unreachable_internal("Invalid asm constraint", "llvm/lib/Target/AMDGPU/SIISelLowering.cpp"
, 12617)
;
12618}
12619
12620bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12621 uint64_t Val,
12622 unsigned MaxSize) const {
12623 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12624 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12625 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12626 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12627 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12628 return true;
12629 }
12630 return false;
12631}
12632
12633static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12634 switch (UnalignedClassID) {
12635 case AMDGPU::VReg_64RegClassID:
12636 return AMDGPU::VReg_64_Align2RegClassID;
12637 case AMDGPU::VReg_96RegClassID:
12638 return AMDGPU::VReg_96_Align2RegClassID;
12639 case AMDGPU::VReg_128RegClassID:
12640 return AMDGPU::VReg_128_Align2RegClassID;
12641 case AMDGPU::VReg_160RegClassID:
12642 return AMDGPU::VReg_160_Align2RegClassID;
12643 case AMDGPU::VReg_192RegClassID:
12644 return AMDGPU::VReg_192_Align2RegClassID;
12645 case AMDGPU::VReg_224RegClassID:
12646 return AMDGPU::VReg_224_Align2RegClassID;
12647 case AMDGPU::VReg_256RegClassID:
12648 return AMDGPU::VReg_256_Align2RegClassID;
12649 case AMDGPU::VReg_288RegClassID:
12650 return AMDGPU::VReg_288_Align2RegClassID;
12651 case AMDGPU::VReg_320RegClassID:
12652 return AMDGPU::VReg_320_Align2RegClassID;
12653 case AMDGPU::VReg_352RegClassID:
12654 return AMDGPU::VReg_352_Align2RegClassID;
12655 case AMDGPU::VReg_384RegClassID:
12656 return AMDGPU::VReg_384_Align2RegClassID;
12657 case AMDGPU::VReg_512RegClassID:
12658 return AMDGPU::VReg_512_Align2RegClassID;
12659 case AMDGPU::VReg_1024RegClassID:
12660 return AMDGPU::VReg_1024_Align2RegClassID;
12661 case AMDGPU::AReg_64RegClassID:
12662 return AMDGPU::AReg_64_Align2RegClassID;
12663 case AMDGPU::AReg_96RegClassID:
12664 return AMDGPU::AReg_96_Align2RegClassID;
12665 case AMDGPU::AReg_128RegClassID:
12666 return AMDGPU::AReg_128_Align2RegClassID;
12667 case AMDGPU::AReg_160RegClassID:
12668 return AMDGPU::AReg_160_Align2RegClassID;
12669 case AMDGPU::AReg_192RegClassID:
12670 return AMDGPU::AReg_192_Align2RegClassID;
12671 case AMDGPU::AReg_256RegClassID:
12672 return AMDGPU::AReg_256_Align2RegClassID;
12673 case AMDGPU::AReg_512RegClassID:
12674 return AMDGPU::AReg_512_Align2RegClassID;
12675 case AMDGPU::AReg_1024RegClassID:
12676 return AMDGPU::AReg_1024_Align2RegClassID;
12677 default:
12678 return -1;
12679 }
12680}
12681
12682// Figure out which registers should be reserved for stack access. Only after
12683// the function is legalized do we know all of the non-spill stack objects or if
12684// calls are present.
12685void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12686 MachineRegisterInfo &MRI = MF.getRegInfo();
12687 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12688 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12689 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12690 const SIInstrInfo *TII = ST.getInstrInfo();
12691
12692 if (Info->isEntryFunction()) {
12693 // Callable functions have fixed registers used for stack access.
12694 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12695 }
12696
12697 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),(static_cast <bool> (!TRI->isSubRegister(Info->getScratchRSrcReg
(), Info->getStackPtrOffsetReg())) ? void (0) : __assert_fail
("!TRI->isSubRegister(Info->getScratchRSrcReg(), Info->getStackPtrOffsetReg())"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 12698, __extension__
__PRETTY_FUNCTION__))
12698 Info->getStackPtrOffsetReg()))(static_cast <bool> (!TRI->isSubRegister(Info->getScratchRSrcReg
(), Info->getStackPtrOffsetReg())) ? void (0) : __assert_fail
("!TRI->isSubRegister(Info->getScratchRSrcReg(), Info->getStackPtrOffsetReg())"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 12698, __extension__
__PRETTY_FUNCTION__))
;
12699 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12700 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12701
12702 // We need to worry about replacing the default register with itself in case
12703 // of MIR testcases missing the MFI.
12704 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12705 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12706
12707 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12708 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12709
12710 Info->limitOccupancy(MF);
12711
12712 if (ST.isWave32() && !MF.empty()) {
12713 for (auto &MBB : MF) {
12714 for (auto &MI : MBB) {
12715 TII->fixImplicitOperands(MI);
12716 }
12717 }
12718 }
12719
12720 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12721 // classes if required. Ideally the register class constraints would differ
12722 // per-subtarget, but there's no easy way to achieve that right now. This is
12723 // not a problem for VGPRs because the correctly aligned VGPR class is implied
12724 // from using them as the register class for legal types.
12725 if (ST.needsAlignedVGPRs()) {
12726 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12727 const Register Reg = Register::index2VirtReg(I);
12728 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12729 if (!RC)
12730 continue;
12731 int NewClassID = getAlignedAGPRClassID(RC->getID());
12732 if (NewClassID != -1)
12733 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12734 }
12735 }
12736
12737 TargetLoweringBase::finalizeLowering(MF);
12738}
12739
12740void SITargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12741 KnownBits &Known,
12742 const APInt &DemandedElts,
12743 const SelectionDAG &DAG,
12744 unsigned Depth) const {
12745 Known.resetAll();
12746 unsigned Opc = Op.getOpcode();
12747 switch (Opc) {
12748 case ISD::INTRINSIC_WO_CHAIN: {
12749 unsigned IID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12750 switch (IID) {
12751 case Intrinsic::amdgcn_mbcnt_lo:
12752 case Intrinsic::amdgcn_mbcnt_hi: {
12753 const GCNSubtarget &ST =
12754 DAG.getMachineFunction().getSubtarget<GCNSubtarget>();
12755 // These return at most the (wavefront size - 1) + src1
12756 // As long as src1 is an immediate we can calc known bits
12757 KnownBits Src1Known = DAG.computeKnownBits(Op.getOperand(2), Depth + 1);
12758 unsigned Src1ValBits = Src1Known.countMaxActiveBits();
12759 unsigned MaxActiveBits = std::max(Src1ValBits, ST.getWavefrontSizeLog2());
12760 // Cater for potential carry
12761 MaxActiveBits += Src1ValBits ? 1 : 0;
12762 unsigned Size = Op.getValueType().getSizeInBits();
12763 if (MaxActiveBits < Size)
12764 Known.Zero.setHighBits(Size - MaxActiveBits);
12765 return;
12766 }
12767 }
12768 break;
12769 }
12770 }
12771 return AMDGPUTargetLowering::computeKnownBitsForTargetNode(
12772 Op, Known, DemandedElts, DAG, Depth);
12773}
12774
12775void SITargetLowering::computeKnownBitsForFrameIndex(
12776 const int FI, KnownBits &Known, const MachineFunction &MF) const {
12777 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12778
12779 // Set the high bits to zero based on the maximum allowed scratch size per
12780 // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12781 // calculation won't overflow, so assume the sign bit is never set.
12782 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12783}
12784
12785static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12786 KnownBits &Known, unsigned Dim) {
12787 unsigned MaxValue =
12788 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12789 Known.Zero.setHighBits(llvm::countl_zero(MaxValue));
12790}
12791
12792void SITargetLowering::computeKnownBitsForTargetInstr(
12793 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12794 const MachineRegisterInfo &MRI, unsigned Depth) const {
12795 const MachineInstr *MI = MRI.getVRegDef(R);
12796 switch (MI->getOpcode()) {
12797 case AMDGPU::G_INTRINSIC: {
12798 switch (MI->getIntrinsicID()) {
12799 case Intrinsic::amdgcn_workitem_id_x:
12800 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12801 break;
12802 case Intrinsic::amdgcn_workitem_id_y:
12803 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12804 break;
12805 case Intrinsic::amdgcn_workitem_id_z:
12806 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12807 break;
12808 case Intrinsic::amdgcn_mbcnt_lo:
12809 case Intrinsic::amdgcn_mbcnt_hi: {
12810 // These return at most the wavefront size - 1.
12811 unsigned Size = MRI.getType(R).getSizeInBits();
12812 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12813 break;
12814 }
12815 case Intrinsic::amdgcn_groupstaticsize: {
12816 // We can report everything over the maximum size as 0. We can't report
12817 // based on the actual size because we don't know if it's accurate or not
12818 // at any given point.
12819 Known.Zero.setHighBits(
12820 llvm::countl_zero(getSubtarget()->getAddressableLocalMemorySize()));
12821 break;
12822 }
12823 }
12824 break;
12825 }
12826 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12827 Known.Zero.setHighBits(24);
12828 break;
12829 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12830 Known.Zero.setHighBits(16);
12831 break;
12832 }
12833}
12834
12835Align SITargetLowering::computeKnownAlignForTargetInstr(
12836 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12837 unsigned Depth) const {
12838 const MachineInstr *MI = MRI.getVRegDef(R);
12839 switch (MI->getOpcode()) {
12840 case AMDGPU::G_INTRINSIC:
12841 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12842 // FIXME: Can this move to generic code? What about the case where the call
12843 // site specifies a lower alignment?
12844 Intrinsic::ID IID = MI->getIntrinsicID();
12845 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12846 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12847 if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12848 return *RetAlign;
12849 return Align(1);
12850 }
12851 default:
12852 return Align(1);
12853 }
12854}
12855
12856Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12857 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12858 const Align CacheLineAlign = Align(64);
12859
12860 // Pre-GFX10 target did not benefit from loop alignment
12861 if (!ML || DisableLoopAlignment || !getSubtarget()->hasInstPrefetch() ||
12862 getSubtarget()->hasInstFwdPrefetchBug())
12863 return PrefAlign;
12864
12865 // On GFX10 I$ is 4 x 64 bytes cache lines.
12866 // By default prefetcher keeps one cache line behind and reads two ahead.
12867 // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12868 // behind and one ahead.
12869 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12870 // If loop fits 64 bytes it always spans no more than two cache lines and
12871 // does not need an alignment.
12872 // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12873 // Else if loop is less or equal 192 bytes we need two lines behind.
12874
12875 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12876 const MachineBasicBlock *Header = ML->getHeader();
12877 if (Header->getAlignment() != PrefAlign)
12878 return Header->getAlignment(); // Already processed.
12879
12880 unsigned LoopSize = 0;
12881 for (const MachineBasicBlock *MBB : ML->blocks()) {
12882 // If inner loop block is aligned assume in average half of the alignment
12883 // size to be added as nops.
12884 if (MBB != Header)
12885 LoopSize += MBB->getAlignment().value() / 2;
12886
12887 for (const MachineInstr &MI : *MBB) {
12888 LoopSize += TII->getInstSizeInBytes(MI);
12889 if (LoopSize > 192)
12890 return PrefAlign;
12891 }
12892 }
12893
12894 if (LoopSize <= 64)
12895 return PrefAlign;
12896
12897 if (LoopSize <= 128)
12898 return CacheLineAlign;
12899
12900 // If any of parent loops is surrounded by prefetch instructions do not
12901 // insert new for inner loop, which would reset parent's settings.
12902 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12903 if (MachineBasicBlock *Exit = P->getExitBlock()) {
12904 auto I = Exit->getFirstNonDebugInstr();
12905 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12906 return CacheLineAlign;
12907 }
12908 }
12909
12910 MachineBasicBlock *Pre = ML->getLoopPreheader();
12911 MachineBasicBlock *Exit = ML->getExitBlock();
12912
12913 if (Pre && Exit) {
12914 auto PreTerm = Pre->getFirstTerminator();
12915 if (PreTerm == Pre->begin() ||
12916 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12917 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12918 .addImm(1); // prefetch 2 lines behind PC
12919
12920 auto ExitHead = Exit->getFirstNonDebugInstr();
12921 if (ExitHead == Exit->end() ||
12922 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12923 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12924 .addImm(2); // prefetch 1 line behind PC
12925 }
12926
12927 return CacheLineAlign;
12928}
12929
12930LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__))
12931static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12932 assert(N->getOpcode() == ISD::CopyFromReg)(static_cast <bool> (N->getOpcode() == ISD::CopyFromReg
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::CopyFromReg"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 12932, __extension__
__PRETTY_FUNCTION__))
;
12933 do {
12934 // Follow the chain until we find an INLINEASM node.
12935 N = N->getOperand(0).getNode();
12936 if (N->getOpcode() == ISD::INLINEASM ||
12937 N->getOpcode() == ISD::INLINEASM_BR)
12938 return true;
12939 } while (N->getOpcode() == ISD::CopyFromReg);
12940 return false;
12941}
12942
12943bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode *N,
12944 FunctionLoweringInfo *FLI,
12945 UniformityInfo *UA) const {
12946 switch (N->getOpcode()) {
12947 case ISD::CopyFromReg: {
12948 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12949 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12950 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12951 Register Reg = R->getReg();
12952
12953 // FIXME: Why does this need to consider isLiveIn?
12954 if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12955 return !TRI->isSGPRReg(MRI, Reg);
12956
12957 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12958 return UA->isDivergent(V);
12959
12960 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N))(static_cast <bool> (Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm
(N)) ? void (0) : __assert_fail ("Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)"
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 12960, __extension__
__PRETTY_FUNCTION__))
;
12961 return !TRI->isSGPRReg(MRI, Reg);
12962 }
12963 case ISD::LOAD: {
12964 const LoadSDNode *L = cast<LoadSDNode>(N);
12965 unsigned AS = L->getAddressSpace();
12966 // A flat load may access private memory.
12967 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12968 }
12969 case ISD::CALLSEQ_END:
12970 return true;
12971 case ISD::INTRINSIC_WO_CHAIN:
12972 return AMDGPU::isIntrinsicSourceOfDivergence(
12973 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12974 case ISD::INTRINSIC_W_CHAIN:
12975 return AMDGPU::isIntrinsicSourceOfDivergence(
12976 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12977 case AMDGPUISD::ATOMIC_CMP_SWAP:
12978 case AMDGPUISD::ATOMIC_LOAD_FMIN:
12979 case AMDGPUISD::ATOMIC_LOAD_FMAX:
12980 case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12981 case AMDGPUISD::BUFFER_ATOMIC_ADD:
12982 case AMDGPUISD::BUFFER_ATOMIC_SUB:
12983 case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12984 case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12985 case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12986 case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12987 case AMDGPUISD::BUFFER_ATOMIC_AND:
12988 case AMDGPUISD::BUFFER_ATOMIC_OR:
12989 case AMDGPUISD::BUFFER_ATOMIC_XOR:
12990 case AMDGPUISD::BUFFER_ATOMIC_INC:
12991 case AMDGPUISD::BUFFER_ATOMIC_DEC:
12992 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12993 case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12994 case AMDGPUISD::BUFFER_ATOMIC_FADD:
12995 case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12996 case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12997 // Target-specific read-modify-write atomics are sources of divergence.
12998 return true;
12999 default:
13000 if (auto *A = dyn_cast<AtomicSDNode>(N)) {
13001 // Generic read-modify-write atomics are sources of divergence.
13002 return A->readMem() && A->writeMem();
13003 }
13004 return false;
13005 }
13006}
13007
13008bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
13009 EVT VT) const {
13010 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
13011 case MVT::f32:
13012 return hasFP32Denormals(DAG.getMachineFunction());
13013 case MVT::f64:
13014 case MVT::f16:
13015 return hasFP64FP16Denormals(DAG.getMachineFunction());
13016 default:
13017 return false;
13018 }
13019}
13020
13021bool SITargetLowering::denormalsEnabledForType(LLT Ty,
13022 MachineFunction &MF) const {
13023 switch (Ty.getScalarSizeInBits()) {
13024 case 32:
13025 return hasFP32Denormals(MF);
13026 case 64:
13027 case 16:
13028 return hasFP64FP16Denormals(MF);
13029 default:
13030 return false;
13031 }
13032}
13033
13034bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
13035 const SelectionDAG &DAG,
13036 bool SNaN,
13037 unsigned Depth) const {
13038 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
13039 const MachineFunction &MF = DAG.getMachineFunction();
13040 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
13041
13042 if (Info->getMode().DX10Clamp)
13043 return true; // Clamped to 0.
13044 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
13045 }
13046
13047 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
13048 SNaN, Depth);
13049}
13050
13051// Global FP atomic instructions have a hardcoded FP mode and do not support
13052// FP32 denormals, and only support v2f16 denormals.
13053static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
13054 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
13055 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
13056 if (&Flt == &APFloat::IEEEsingle())
13057 return DenormMode == DenormalMode::getPreserveSign();
13058 return DenormMode == DenormalMode::getIEEE();
13059}
13060
13061// The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
13062// floating point atomic instructions. May generate more efficient code,
13063// but may not respect rounding and denormal modes, and may give incorrect
13064// results for certain memory destinations.
13065bool unsafeFPAtomicsDisabled(Function *F) {
13066 return F->getFnAttribute("amdgpu-unsafe-fp-atomics").getValueAsString() !=
13067 "true";
13068}
13069
13070TargetLowering::AtomicExpansionKind
13071SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
13072 unsigned AS = RMW->getPointerAddressSpace();
13073 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
13074 return AtomicExpansionKind::NotAtomic;
13075
13076 auto SSID = RMW->getSyncScopeID();
13077
13078 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
13079 OptimizationRemarkEmitter ORE(RMW->getFunction());
13080 LLVMContext &Ctx = RMW->getFunction()->getContext();
13081 SmallVector<StringRef> SSNs;
13082 Ctx.getSyncScopeNames(SSNs);
13083 auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
13084 ? "system"
13085 : SSNs[RMW->getSyncScopeID()];
13086 ORE.emit([&]() {
13087 return OptimizationRemark(DEBUG_TYPE"si-lower", "Passed", RMW)
13088 << "Hardware instruction generated for atomic "
13089 << RMW->getOperationName(RMW->getOperation())
13090 << " operation at memory scope " << MemScope
13091 << " due to an unsafe request.";
13092 });
13093 return Kind;
13094 };
13095
13096 bool HasSystemScope =
13097 SSID == SyncScope::System ||
13098 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as");
13099
13100 switch (RMW->getOperation()) {
13101 case AtomicRMWInst::FAdd: {
13102 Type *Ty = RMW->getType();
13103
13104 if (Ty->isHalfTy())
13105 return AtomicExpansionKind::CmpXChg;
13106
13107 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
13108 return AtomicExpansionKind::CmpXChg;
13109
13110 if (AMDGPU::isFlatGlobalAddrSpace(AS) &&
13111 Subtarget->hasAtomicFaddNoRtnInsts()) {
13112 if (Subtarget->hasGFX940Insts())
13113 return AtomicExpansionKind::None;
13114
13115 if (unsafeFPAtomicsDisabled(RMW->getFunction()))
13116 return AtomicExpansionKind::CmpXChg;
13117
13118 // Always expand system scope fp atomics.
13119 if (HasSystemScope)
13120 return AtomicExpansionKind::CmpXChg;
13121
13122 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Ty->isFloatTy()) {
13123 // global atomic fadd f32 no-rtn: gfx908, gfx90a, gfx940, gfx11+.
13124 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
13125 return ReportUnsafeHWInst(AtomicExpansionKind::None);
13126 // global atomic fadd f32 rtn: gfx90a, gfx940, gfx11+.
13127 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
13128 return ReportUnsafeHWInst(AtomicExpansionKind::None);
13129 }
13130
13131 // flat atomic fadd f32: gfx940, gfx11+.
13132 if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy() &&
13133 Subtarget->hasFlatAtomicFaddF32Inst())
13134 return ReportUnsafeHWInst(AtomicExpansionKind::None);
13135
13136 // global and flat atomic fadd f64: gfx90a, gfx940.
13137 if (Ty->isDoubleTy() && Subtarget->hasGFX90AInsts())
13138 return ReportUnsafeHWInst(AtomicExpansionKind::None);
13139
13140 // If it is in flat address space, and the type is float, we will try to
13141 // expand it, if the target supports global and lds atomic fadd. The
13142 // reason we need that is, in the expansion, we emit the check of address
13143 // space. If it is in global address space, we emit the global atomic
13144 // fadd; if it is in shared address space, we emit the LDS atomic fadd.
13145 if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy() &&
13146 Subtarget->hasLDSFPAtomicAdd()) {
13147 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
13148 return AtomicExpansionKind::Expand;
13149 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
13150 return AtomicExpansionKind::Expand;
13151 }
13152
13153 return AtomicExpansionKind::CmpXChg;
13154 }
13155
13156 // DS FP atomics do respect the denormal mode, but the rounding mode is
13157 // fixed to round-to-nearest-even.
13158 // The only exception is DS_ADD_F64 which never flushes regardless of mode.
13159 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
13160 if (!Ty->isDoubleTy())
13161 return AtomicExpansionKind::None;
13162
13163 if (fpModeMatchesGlobalFPAtomicMode(RMW))
13164 return AtomicExpansionKind::None;
13165
13166 return RMW->getFunction()
13167 ->getFnAttribute("amdgpu-unsafe-fp-atomics")
13168 .getValueAsString() == "true"
13169 ? ReportUnsafeHWInst(AtomicExpansionKind::None)
13170 : AtomicExpansionKind::CmpXChg;
13171 }
13172
13173 return AtomicExpansionKind::CmpXChg;
13174 }
13175 case AtomicRMWInst::FMin:
13176 case AtomicRMWInst::FMax:
13177 case AtomicRMWInst::Min:
13178 case AtomicRMWInst::Max:
13179 case AtomicRMWInst::UMin:
13180 case AtomicRMWInst::UMax: {
13181 if (AMDGPU::isFlatGlobalAddrSpace(AS)) {
13182 if (RMW->getType()->isFloatTy() &&
13183 unsafeFPAtomicsDisabled(RMW->getFunction()))
13184 return AtomicExpansionKind::CmpXChg;
13185
13186 // Always expand system scope min/max atomics.
13187 if (HasSystemScope)
13188 return AtomicExpansionKind::CmpXChg;
13189 }
13190 break;
13191 }
13192 default:
13193 break;
13194 }
13195
13196 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
13197}
13198
13199TargetLowering::AtomicExpansionKind
13200SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13201 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
13202 ? AtomicExpansionKind::NotAtomic
13203 : AtomicExpansionKind::None;
13204}
13205
13206TargetLowering::AtomicExpansionKind
13207SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13208 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
13209 ? AtomicExpansionKind::NotAtomic
13210 : AtomicExpansionKind::None;
13211}
13212
13213TargetLowering::AtomicExpansionKind
13214SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
13215 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
13216 ? AtomicExpansionKind::NotAtomic
13217 : AtomicExpansionKind::None;
13218}
13219
13220const TargetRegisterClass *
13221SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
13222 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
13223 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
13224 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
13225 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
13226 : &AMDGPU::SReg_32RegClass;
13227 if (!TRI->isSGPRClass(RC) && !isDivergent)
13228 return TRI->getEquivalentSGPRClass(RC);
13229 else if (TRI->isSGPRClass(RC) && isDivergent)
13230 return TRI->getEquivalentVGPRClass(RC);
13231
13232 return RC;
13233}
13234
13235// FIXME: This is a workaround for DivergenceAnalysis not understanding always
13236// uniform values (as produced by the mask results of control flow intrinsics)
13237// used outside of divergent blocks. The phi users need to also be treated as
13238// always uniform.
13239//
13240// FIXME: DA is no longer in-use. Does this still apply to UniformityAnalysis?
13241static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
13242 unsigned WaveSize) {
13243 // FIXME: We assume we never cast the mask results of a control flow
13244 // intrinsic.
13245 // Early exit if the type won't be consistent as a compile time hack.
13246 IntegerType *IT = dyn_cast<IntegerType>(V->getType());
13247 if (!IT || IT->getBitWidth() != WaveSize)
13248 return false;
13249
13250 if (!isa<Instruction>(V))
13251 return false;
13252 if (!Visited.insert(V).second)
13253 return false;
13254 bool Result = false;
13255 for (const auto *U : V->users()) {
13256 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
13257 if (V == U->getOperand(1)) {
13258 switch (Intrinsic->getIntrinsicID()) {
13259 default:
13260 Result = false;
13261 break;
13262 case Intrinsic::amdgcn_if_break:
13263 case Intrinsic::amdgcn_if:
13264 case Intrinsic::amdgcn_else:
13265 Result = true;
13266 break;
13267 }
13268 }
13269 if (V == U->getOperand(0)) {
13270 switch (Intrinsic->getIntrinsicID()) {
13271 default:
13272 Result = false;
13273 break;
13274 case Intrinsic::amdgcn_end_cf:
13275 case Intrinsic::amdgcn_loop:
13276 Result = true;
13277 break;
13278 }
13279 }
13280 } else {
13281 Result = hasCFUser(U, Visited, WaveSize);
13282 }
13283 if (Result)
13284 break;
13285 }
13286 return Result;
13287}
13288
13289bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
13290 const Value *V) const {
13291 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
13292 if (CI->isInlineAsm()) {
13293 // FIXME: This cannot give a correct answer. This should only trigger in
13294 // the case where inline asm returns mixed SGPR and VGPR results, used
13295 // outside the defining block. We don't have a specific result to
13296 // consider, so this assumes if any value is SGPR, the overall register
13297 // also needs to be SGPR.
13298 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
13299 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
13300 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
13301 for (auto &TC : TargetConstraints) {
13302 if (TC.Type == InlineAsm::isOutput) {
13303 ComputeConstraintToUse(TC, SDValue());
13304 const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
13305 SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
13306 if (RC && SIRI->isSGPRClass(RC))
13307 return true;
13308 }
13309 }
13310 }
13311 }
13312 SmallPtrSet<const Value *, 16> Visited;
13313 return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
13314}
13315
13316bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
13317 SDNode::use_iterator I = N->use_begin(), E = N->use_end();
13318 for (; I != E; ++I) {
13319 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
13320 if (getBasePtrIndex(M) == I.getOperandNo())
13321 return true;
13322 }
13323 }
13324 return false;
13325}
13326
13327bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
13328 SDValue N1) const {
13329 if (!N0.hasOneUse())
13330 return false;
13331 // Take care of the opportunity to keep N0 uniform
13332 if (N0->isDivergent() || !N1->isDivergent())
13333 return true;
13334 // Check if we have a good chance to form the memory access pattern with the
13335 // base and offset
13336 return (DAG.isBaseWithConstantOffset(N0) &&
13337 hasMemSDNodeUser(*N0->use_begin()));
13338}
13339
13340MachineMemOperand::Flags
13341SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
13342 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
13343 if (I.getMetadata("amdgpu.noclobber"))
13344 return MONoClobber;
13345 return MachineMemOperand::MONone;
13346}
13347
13348bool SITargetLowering::checkForPhysRegDependency(
13349 SDNode *Def, SDNode *User, unsigned Op, const TargetRegisterInfo *TRI,
13350 const TargetInstrInfo *TII, unsigned &PhysReg, int &Cost) const {
13351 if (User->getOpcode() != ISD::CopyToReg)
13352 return false;
13353 if (!Def->isMachineOpcode())
13354 return false;
13355 MachineSDNode *MDef = dyn_cast<MachineSDNode>(Def);
13356 if (!MDef)
13357 return false;
13358
13359 unsigned ResNo = User->getOperand(Op).getResNo();
13360 if (User->getOperand(Op)->getValueType(ResNo) != MVT::i1)
13361 return false;
13362 const MCInstrDesc &II = TII->get(MDef->getMachineOpcode());
13363 if (II.isCompare() && II.hasImplicitDefOfPhysReg(AMDGPU::SCC)) {
13364 PhysReg = AMDGPU::SCC;
13365 const TargetRegisterClass *RC =
13366 TRI->getMinimalPhysRegClass(PhysReg, Def->getSimpleValueType(ResNo));
13367 Cost = RC->getCopyCost();
13368 return true;
13369 }
13370 return false;
13371}
13372
13373void SITargetLowering::emitExpandAtomicRMW(AtomicRMWInst *AI) const {
13374 assert(Subtarget->hasAtomicFaddInsts() &&(static_cast <bool> (Subtarget->hasAtomicFaddInsts()
&& "target should have atomic fadd instructions") ? void
(0) : __assert_fail ("Subtarget->hasAtomicFaddInsts() && \"target should have atomic fadd instructions\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13375, __extension__
__PRETTY_FUNCTION__))
13375 "target should have atomic fadd instructions")(static_cast <bool> (Subtarget->hasAtomicFaddInsts()
&& "target should have atomic fadd instructions") ? void
(0) : __assert_fail ("Subtarget->hasAtomicFaddInsts() && \"target should have atomic fadd instructions\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13375, __extension__
__PRETTY_FUNCTION__))
;
13376 assert(AI->getType()->isFloatTy() &&(static_cast <bool> (AI->getType()->isFloatTy() &&
AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS &&
"generic atomicrmw expansion only supports FP32 operand in flat "
"address space") ? void (0) : __assert_fail ("AI->getType()->isFloatTy() && AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS && \"generic atomicrmw expansion only supports FP32 operand in flat \" \"address space\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13379, __extension__
__PRETTY_FUNCTION__))
13377 AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS &&(static_cast <bool> (AI->getType()->isFloatTy() &&
AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS &&
"generic atomicrmw expansion only supports FP32 operand in flat "
"address space") ? void (0) : __assert_fail ("AI->getType()->isFloatTy() && AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS && \"generic atomicrmw expansion only supports FP32 operand in flat \" \"address space\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13379, __extension__
__PRETTY_FUNCTION__))
13378 "generic atomicrmw expansion only supports FP32 operand in flat "(static_cast <bool> (AI->getType()->isFloatTy() &&
AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS &&
"generic atomicrmw expansion only supports FP32 operand in flat "
"address space") ? void (0) : __assert_fail ("AI->getType()->isFloatTy() && AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS && \"generic atomicrmw expansion only supports FP32 operand in flat \" \"address space\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13379, __extension__
__PRETTY_FUNCTION__))
13379 "address space")(static_cast <bool> (AI->getType()->isFloatTy() &&
AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS &&
"generic atomicrmw expansion only supports FP32 operand in flat "
"address space") ? void (0) : __assert_fail ("AI->getType()->isFloatTy() && AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS && \"generic atomicrmw expansion only supports FP32 operand in flat \" \"address space\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13379, __extension__
__PRETTY_FUNCTION__))
;
13380 assert(AI->getOperation() == AtomicRMWInst::FAdd &&(static_cast <bool> (AI->getOperation() == AtomicRMWInst
::FAdd && "only fadd is supported for now") ? void (0
) : __assert_fail ("AI->getOperation() == AtomicRMWInst::FAdd && \"only fadd is supported for now\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13381, __extension__
__PRETTY_FUNCTION__))
13381 "only fadd is supported for now")(static_cast <bool> (AI->getOperation() == AtomicRMWInst
::FAdd && "only fadd is supported for now") ? void (0
) : __assert_fail ("AI->getOperation() == AtomicRMWInst::FAdd && \"only fadd is supported for now\""
, "llvm/lib/Target/AMDGPU/SIISelLowering.cpp", 13381, __extension__
__PRETTY_FUNCTION__))
;
13382
13383 // Given: atomicrmw fadd ptr %addr, float %val ordering
13384 //
13385 // With this expansion we produce the following code:
13386 // [...]
13387 // br label %atomicrmw.check.shared
13388 //
13389 // atomicrmw.check.shared:
13390 // %is.shared = call i1 @llvm.amdgcn.is.shared(ptr %addr)
13391 // br i1 %is.shared, label %atomicrmw.shared, label %atomicrmw.check.private
13392 //
13393 // atomicrmw.shared:
13394 // %cast.shared = addrspacecast ptr %addr to ptr addrspace(3)
13395 // %loaded.shared = atomicrmw fadd ptr addrspace(3) %cast.shared,
13396 // float %val ordering
13397 // br label %atomicrmw.phi
13398 //
13399 // atomicrmw.check.private:
13400 // %is.private = call i1 @llvm.amdgcn.is.private(ptr %int8ptr)
13401 // br i1 %is.private, label %atomicrmw.private, label %atomicrmw.global
13402 //
13403 // atomicrmw.private:
13404 // %cast.private = addrspacecast ptr %addr to ptr addrspace(5)
13405 // %loaded.private = load float, ptr addrspace(5) %cast.private
13406 // %val.new = fadd float %loaded.private, %val
13407 // store float %val.new, ptr addrspace(5) %cast.private
13408 // br label %atomicrmw.phi
13409 //
13410 // atomicrmw.global:
13411 // %cast.global = addrspacecast ptr %addr to ptr addrspace(1)
13412 // %loaded.global = atomicrmw fadd ptr addrspace(1) %cast.global,
13413 // float %val ordering
13414 // br label %atomicrmw.phi
13415 //
13416 // atomicrmw.phi:
13417 // %loaded.phi = phi float [ %loaded.shared, %atomicrmw.shared ],
13418 // [ %loaded.private, %atomicrmw.private ],
13419 // [ %loaded.global, %atomicrmw.global ]
13420 // br label %atomicrmw.end
13421 //
13422 // atomicrmw.end:
13423 // [...]
13424
13425 IRBuilder<> Builder(AI);
13426 LLVMContext &Ctx = Builder.getContext();
13427
13428 BasicBlock *BB = Builder.GetInsertBlock();
13429 Function *F = BB->getParent();
13430 BasicBlock *ExitBB =
13431 BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
13432 BasicBlock *CheckSharedBB =
13433 BasicBlock::Create(Ctx, "atomicrmw.check.shared", F, ExitBB);
13434 BasicBlock *SharedBB = BasicBlock::Create(Ctx, "atomicrmw.shared", F, ExitBB);
13435 BasicBlock *CheckPrivateBB =
13436 BasicBlock::Create(Ctx, "atomicrmw.check.private", F, ExitBB);
13437 BasicBlock *PrivateBB =
13438 BasicBlock::Create(Ctx, "atomicrmw.private", F, ExitBB);
13439 BasicBlock *GlobalBB = BasicBlock::Create(Ctx, "atomicrmw.global", F, ExitBB);
13440 BasicBlock *PhiBB = BasicBlock::Create(Ctx, "atomicrmw.phi", F, ExitBB);
13441
13442 Value *Val = AI->getValOperand();
13443 Type *ValTy = Val->getType();
13444 Value *Addr = AI->getPointerOperand();
13445 PointerType *PtrTy = cast<PointerType>(Addr->getType());
13446
13447 auto CreateNewAtomicRMW = [AI](IRBuilder<> &Builder, Value *Addr,
13448 Value *Val) -> Value * {
13449 AtomicRMWInst *OldVal =
13450 Builder.CreateAtomicRMW(AI->getOperation(), Addr, Val, AI->getAlign(),
13451 AI->getOrdering(), AI->getSyncScopeID());
13452 SmallVector<std::pair<unsigned, MDNode *>> MDs;
13453 AI->getAllMetadata(MDs);
13454 for (auto &P : MDs)
13455 OldVal->setMetadata(P.first, P.second);
13456 return OldVal;
13457 };
13458
13459 std::prev(BB->end())->eraseFromParent();
13460 Builder.SetInsertPoint(BB);
13461 Builder.CreateBr(CheckSharedBB);
13462
13463 Builder.SetInsertPoint(CheckSharedBB);
13464 CallInst *IsShared = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_shared, {},
13465 {Addr}, nullptr, "is.shared");
13466 Builder.CreateCondBr(IsShared, SharedBB, CheckPrivateBB);
13467
13468 Builder.SetInsertPoint(SharedBB);
13469 Value *CastToLocal = Builder.CreateAddrSpaceCast(
13470 Addr,
13471 PointerType::getWithSamePointeeType(PtrTy, AMDGPUAS::LOCAL_ADDRESS));
13472 Value *LoadedShared = CreateNewAtomicRMW(Builder, CastToLocal, Val);
13473 Builder.CreateBr(PhiBB);
13474
13475 Builder.SetInsertPoint(CheckPrivateBB);
13476 CallInst *IsPrivate = Builder.CreateIntrinsic(
13477 Intrinsic::amdgcn_is_private, {}, {Addr}, nullptr, "is.private");
13478 Builder.CreateCondBr(IsPrivate, PrivateBB, GlobalBB);
13479
13480 Builder.SetInsertPoint(PrivateBB);
13481 Value *CastToPrivate = Builder.CreateAddrSpaceCast(
13482 Addr,
13483 PointerType::getWithSamePointeeType(PtrTy, AMDGPUAS::PRIVATE_ADDRESS));
13484 Value *LoadedPrivate =
13485 Builder.CreateLoad(ValTy, CastToPrivate, "loaded.private");
13486 Value *NewVal = Builder.CreateFAdd(LoadedPrivate, Val, "val.new");
13487 Builder.CreateStore(NewVal, CastToPrivate);
13488 Builder.CreateBr(PhiBB);
13489
13490 Builder.SetInsertPoint(GlobalBB);
13491 Value *CastToGlobal = Builder.CreateAddrSpaceCast(
13492 Addr,
13493 PointerType::getWithSamePointeeType(PtrTy, AMDGPUAS::GLOBAL_ADDRESS));
13494 Value *LoadedGlobal = CreateNewAtomicRMW(Builder, CastToGlobal, Val);
13495 Builder.CreateBr(PhiBB);
13496
13497 Builder.SetInsertPoint(PhiBB);
13498 PHINode *Loaded = Builder.CreatePHI(ValTy, 3, "loaded.phi");
13499 Loaded->addIncoming(LoadedShared, SharedBB);
13500 Loaded->addIncoming(LoadedPrivate, PrivateBB);
13501 Loaded->addIncoming(LoadedGlobal, GlobalBB);
13502 Builder.CreateBr(ExitBB);
13503
13504 AI->replaceAllUsesWith(Loaded);
13505 AI->eraseFromParent();
13506}
13507
13508LoadInst *
13509SITargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
13510 IRBuilder<> Builder(AI);
13511 auto Order = AI->getOrdering();
13512
13513 // The optimization removes store aspect of the atomicrmw. Therefore, cache
13514 // must be flushed if the atomic ordering had a release semantics. This is
13515 // not necessary a fence, a release fence just coincides to do that flush.
13516 // Avoid replacing of an atomicrmw with a release semantics.
13517 if (isReleaseOrStronger(Order))
13518 return nullptr;
13519
13520 LoadInst *LI = Builder.CreateAlignedLoad(
13521 AI->getType(), AI->getPointerOperand(), AI->getAlign());
13522 LI->setAtomic(Order, AI->getSyncScopeID());
13523 LI->copyMetadata(*AI);
13524 LI->takeName(AI);
13525 AI->replaceAllUsesWith(LI);
13526 AI->eraseFromParent();
13527 return LI;
13528}