Bug Summary

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