Bug Summary

File:lib/Target/AMDGPU/SIISelLowering.cpp
Warning:line 3969, column 5
Value stored to 'BR' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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