[obj2yaml] - Fix BB after r373315.
[llvm-complete.git] / lib / Target / AMDGPU / AMDGPUISelLowering.cpp
blob65fa2720b5153a1470e8aea146c45ec5c4718837
1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This is the parent TargetLowering class for hardware code gen
11 /// targets.
13 //===----------------------------------------------------------------------===//
15 #define AMDGPU_LOG2E_F 1.44269504088896340735992468100189214f
16 #define AMDGPU_LN2_F 0.693147180559945309417232121458176568f
17 #define AMDGPU_LN10_F 2.30258509299404568401799145468436421f
19 #include "AMDGPUISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUCallLowering.h"
22 #include "AMDGPUFrameLowering.h"
23 #include "AMDGPURegisterInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "AMDGPUTargetMachine.h"
26 #include "Utils/AMDGPUBaseInfo.h"
27 #include "R600MachineFunctionInfo.h"
28 #include "SIInstrInfo.h"
29 #include "SIMachineFunctionInfo.h"
30 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/CallingConvLower.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DiagnosticInfo.h"
39 #include "llvm/Support/KnownBits.h"
40 using namespace llvm;
42 #include "AMDGPUGenCallingConv.inc"
44 // Find a larger type to do a load / store of a vector with.
45 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
46 unsigned StoreSize = VT.getStoreSizeInBits();
47 if (StoreSize <= 32)
48 return EVT::getIntegerVT(Ctx, StoreSize);
50 assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
51 return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
54 unsigned AMDGPUTargetLowering::numBitsUnsigned(SDValue Op, SelectionDAG &DAG) {
55 EVT VT = Op.getValueType();
56 KnownBits Known = DAG.computeKnownBits(Op);
57 return VT.getSizeInBits() - Known.countMinLeadingZeros();
60 unsigned AMDGPUTargetLowering::numBitsSigned(SDValue Op, SelectionDAG &DAG) {
61 EVT VT = Op.getValueType();
63 // In order for this to be a signed 24-bit value, bit 23, must
64 // be a sign bit.
65 return VT.getSizeInBits() - DAG.ComputeNumSignBits(Op);
68 AMDGPUTargetLowering::AMDGPUTargetLowering(const TargetMachine &TM,
69 const AMDGPUSubtarget &STI)
70 : TargetLowering(TM), Subtarget(&STI) {
71 // Lower floating point store/load to integer store/load to reduce the number
72 // of patterns in tablegen.
73 setOperationAction(ISD::LOAD, MVT::f32, Promote);
74 AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
76 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
77 AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
79 setOperationAction(ISD::LOAD, MVT::v3f32, Promote);
80 AddPromotedToType(ISD::LOAD, MVT::v3f32, MVT::v3i32);
82 setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
83 AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
85 setOperationAction(ISD::LOAD, MVT::v5f32, Promote);
86 AddPromotedToType(ISD::LOAD, MVT::v5f32, MVT::v5i32);
88 setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
89 AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
91 setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
92 AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
94 setOperationAction(ISD::LOAD, MVT::v32f32, Promote);
95 AddPromotedToType(ISD::LOAD, MVT::v32f32, MVT::v32i32);
97 setOperationAction(ISD::LOAD, MVT::i64, Promote);
98 AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
100 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
101 AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
103 setOperationAction(ISD::LOAD, MVT::f64, Promote);
104 AddPromotedToType(ISD::LOAD, MVT::f64, MVT::v2i32);
106 setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
107 AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v4i32);
109 // There are no 64-bit extloads. These should be done as a 32-bit extload and
110 // an extension to 64-bit.
111 for (MVT VT : MVT::integer_valuetypes()) {
112 setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
113 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
114 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
117 for (MVT VT : MVT::integer_valuetypes()) {
118 if (VT == MVT::i64)
119 continue;
121 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
122 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
123 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
124 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
126 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
128 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
129 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
131 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
132 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
133 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
134 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
137 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
138 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
140 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
141 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
143 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
144 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
145 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
146 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
147 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v3i16, Expand);
148 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v3i16, Expand);
149 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v3i16, Expand);
150 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
152 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
155 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
156 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
157 setLoadExtAction(ISD::EXTLOAD, MVT::v3f32, MVT::v3f16, Expand);
158 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
159 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
160 setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Expand);
161 setLoadExtAction(ISD::EXTLOAD, MVT::v32f32, MVT::v32f16, Expand);
163 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
164 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
165 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Expand);
166 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f32, Expand);
168 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
169 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
170 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
171 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
173 setOperationAction(ISD::STORE, MVT::f32, Promote);
174 AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
176 setOperationAction(ISD::STORE, MVT::v2f32, Promote);
177 AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
179 setOperationAction(ISD::STORE, MVT::v3f32, Promote);
180 AddPromotedToType(ISD::STORE, MVT::v3f32, MVT::v3i32);
182 setOperationAction(ISD::STORE, MVT::v4f32, Promote);
183 AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
185 setOperationAction(ISD::STORE, MVT::v5f32, Promote);
186 AddPromotedToType(ISD::STORE, MVT::v5f32, MVT::v5i32);
188 setOperationAction(ISD::STORE, MVT::v8f32, Promote);
189 AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
191 setOperationAction(ISD::STORE, MVT::v16f32, Promote);
192 AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
194 setOperationAction(ISD::STORE, MVT::v32f32, Promote);
195 AddPromotedToType(ISD::STORE, MVT::v32f32, MVT::v32i32);
197 setOperationAction(ISD::STORE, MVT::i64, Promote);
198 AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
200 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
201 AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
203 setOperationAction(ISD::STORE, MVT::f64, Promote);
204 AddPromotedToType(ISD::STORE, MVT::f64, MVT::v2i32);
206 setOperationAction(ISD::STORE, MVT::v2f64, Promote);
207 AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v4i32);
209 setTruncStoreAction(MVT::i64, MVT::i1, Expand);
210 setTruncStoreAction(MVT::i64, MVT::i8, Expand);
211 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
212 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
214 setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
215 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Expand);
216 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Expand);
217 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
219 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
220 setTruncStoreAction(MVT::v2f32, MVT::v2f16, Expand);
221 setTruncStoreAction(MVT::v3f32, MVT::v3f16, Expand);
222 setTruncStoreAction(MVT::v4f32, MVT::v4f16, Expand);
223 setTruncStoreAction(MVT::v8f32, MVT::v8f16, Expand);
224 setTruncStoreAction(MVT::v16f32, MVT::v16f16, Expand);
225 setTruncStoreAction(MVT::v32f32, MVT::v32f16, Expand);
227 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
228 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
230 setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
231 setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
233 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Expand);
234 setTruncStoreAction(MVT::v4f64, MVT::v4f16, Expand);
236 setTruncStoreAction(MVT::v8f64, MVT::v8f32, Expand);
237 setTruncStoreAction(MVT::v8f64, MVT::v8f16, Expand);
240 setOperationAction(ISD::Constant, MVT::i32, Legal);
241 setOperationAction(ISD::Constant, MVT::i64, Legal);
242 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
243 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
245 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
246 setOperationAction(ISD::BRIND, MVT::Other, Expand);
248 // This is totally unsupported, just custom lower to produce an error.
249 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
251 // Library functions. These default to Expand, but we have instructions
252 // for them.
253 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
254 setOperationAction(ISD::FEXP2, MVT::f32, Legal);
255 setOperationAction(ISD::FPOW, MVT::f32, Legal);
256 setOperationAction(ISD::FLOG2, MVT::f32, Legal);
257 setOperationAction(ISD::FABS, MVT::f32, Legal);
258 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
259 setOperationAction(ISD::FRINT, MVT::f32, Legal);
260 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
261 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
262 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
264 setOperationAction(ISD::FROUND, MVT::f32, Custom);
265 setOperationAction(ISD::FROUND, MVT::f64, Custom);
267 setOperationAction(ISD::FLOG, MVT::f32, Custom);
268 setOperationAction(ISD::FLOG10, MVT::f32, Custom);
269 setOperationAction(ISD::FEXP, MVT::f32, Custom);
272 setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
273 setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
275 setOperationAction(ISD::FREM, MVT::f32, Custom);
276 setOperationAction(ISD::FREM, MVT::f64, Custom);
278 // Expand to fneg + fadd.
279 setOperationAction(ISD::FSUB, MVT::f64, Expand);
281 setOperationAction(ISD::CONCAT_VECTORS, MVT::v3i32, Custom);
282 setOperationAction(ISD::CONCAT_VECTORS, MVT::v3f32, Custom);
283 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
284 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
285 setOperationAction(ISD::CONCAT_VECTORS, MVT::v5i32, Custom);
286 setOperationAction(ISD::CONCAT_VECTORS, MVT::v5f32, Custom);
287 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
288 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
289 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
290 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
291 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v3f32, Custom);
292 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v3i32, Custom);
293 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
294 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
295 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v5f32, Custom);
296 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v5i32, Custom);
297 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
298 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
299 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16f32, Custom);
300 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16i32, Custom);
301 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32f32, Custom);
302 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32i32, Custom);
304 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
305 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Custom);
306 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Custom);
308 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
309 for (MVT VT : ScalarIntVTs) {
310 // These should use [SU]DIVREM, so set them to expand
311 setOperationAction(ISD::SDIV, VT, Expand);
312 setOperationAction(ISD::UDIV, VT, Expand);
313 setOperationAction(ISD::SREM, VT, Expand);
314 setOperationAction(ISD::UREM, VT, Expand);
316 // GPU does not have divrem function for signed or unsigned.
317 setOperationAction(ISD::SDIVREM, VT, Custom);
318 setOperationAction(ISD::UDIVREM, VT, Custom);
320 // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
321 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
322 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
324 setOperationAction(ISD::BSWAP, VT, Expand);
325 setOperationAction(ISD::CTTZ, VT, Expand);
326 setOperationAction(ISD::CTLZ, VT, Expand);
328 // AMDGPU uses ADDC/SUBC/ADDE/SUBE
329 setOperationAction(ISD::ADDC, VT, Legal);
330 setOperationAction(ISD::SUBC, VT, Legal);
331 setOperationAction(ISD::ADDE, VT, Legal);
332 setOperationAction(ISD::SUBE, VT, Legal);
335 // The hardware supports 32-bit ROTR, but not ROTL.
336 setOperationAction(ISD::ROTL, MVT::i32, Expand);
337 setOperationAction(ISD::ROTL, MVT::i64, Expand);
338 setOperationAction(ISD::ROTR, MVT::i64, Expand);
340 setOperationAction(ISD::MUL, MVT::i64, Expand);
341 setOperationAction(ISD::MULHU, MVT::i64, Expand);
342 setOperationAction(ISD::MULHS, MVT::i64, Expand);
343 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
344 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
345 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
346 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
347 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
349 setOperationAction(ISD::SMIN, MVT::i32, Legal);
350 setOperationAction(ISD::UMIN, MVT::i32, Legal);
351 setOperationAction(ISD::SMAX, MVT::i32, Legal);
352 setOperationAction(ISD::UMAX, MVT::i32, Legal);
354 setOperationAction(ISD::CTTZ, MVT::i64, Custom);
355 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom);
356 setOperationAction(ISD::CTLZ, MVT::i64, Custom);
357 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359 static const MVT::SimpleValueType VectorIntTypes[] = {
360 MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32
363 for (MVT VT : VectorIntTypes) {
364 // Expand the following operations for the current type by default.
365 setOperationAction(ISD::ADD, VT, Expand);
366 setOperationAction(ISD::AND, VT, Expand);
367 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
368 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
369 setOperationAction(ISD::MUL, VT, Expand);
370 setOperationAction(ISD::MULHU, VT, Expand);
371 setOperationAction(ISD::MULHS, VT, Expand);
372 setOperationAction(ISD::OR, VT, Expand);
373 setOperationAction(ISD::SHL, VT, Expand);
374 setOperationAction(ISD::SRA, VT, Expand);
375 setOperationAction(ISD::SRL, VT, Expand);
376 setOperationAction(ISD::ROTL, VT, Expand);
377 setOperationAction(ISD::ROTR, VT, Expand);
378 setOperationAction(ISD::SUB, VT, Expand);
379 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
380 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
381 setOperationAction(ISD::SDIV, VT, Expand);
382 setOperationAction(ISD::UDIV, VT, Expand);
383 setOperationAction(ISD::SREM, VT, Expand);
384 setOperationAction(ISD::UREM, VT, Expand);
385 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
386 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
387 setOperationAction(ISD::SDIVREM, VT, Custom);
388 setOperationAction(ISD::UDIVREM, VT, Expand);
389 setOperationAction(ISD::SELECT, VT, Expand);
390 setOperationAction(ISD::VSELECT, VT, Expand);
391 setOperationAction(ISD::SELECT_CC, VT, Expand);
392 setOperationAction(ISD::XOR, VT, Expand);
393 setOperationAction(ISD::BSWAP, VT, Expand);
394 setOperationAction(ISD::CTPOP, VT, Expand);
395 setOperationAction(ISD::CTTZ, VT, Expand);
396 setOperationAction(ISD::CTLZ, VT, Expand);
397 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
398 setOperationAction(ISD::SETCC, VT, Expand);
401 static const MVT::SimpleValueType FloatVectorTypes[] = {
402 MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32
405 for (MVT VT : FloatVectorTypes) {
406 setOperationAction(ISD::FABS, VT, Expand);
407 setOperationAction(ISD::FMINNUM, VT, Expand);
408 setOperationAction(ISD::FMAXNUM, VT, Expand);
409 setOperationAction(ISD::FADD, VT, Expand);
410 setOperationAction(ISD::FCEIL, VT, Expand);
411 setOperationAction(ISD::FCOS, VT, Expand);
412 setOperationAction(ISD::FDIV, VT, Expand);
413 setOperationAction(ISD::FEXP2, VT, Expand);
414 setOperationAction(ISD::FEXP, VT, Expand);
415 setOperationAction(ISD::FLOG2, VT, Expand);
416 setOperationAction(ISD::FREM, VT, Expand);
417 setOperationAction(ISD::FLOG, VT, Expand);
418 setOperationAction(ISD::FLOG10, VT, Expand);
419 setOperationAction(ISD::FPOW, VT, Expand);
420 setOperationAction(ISD::FFLOOR, VT, Expand);
421 setOperationAction(ISD::FTRUNC, VT, Expand);
422 setOperationAction(ISD::FMUL, VT, Expand);
423 setOperationAction(ISD::FMA, VT, Expand);
424 setOperationAction(ISD::FRINT, VT, Expand);
425 setOperationAction(ISD::FNEARBYINT, VT, Expand);
426 setOperationAction(ISD::FSQRT, VT, Expand);
427 setOperationAction(ISD::FSIN, VT, Expand);
428 setOperationAction(ISD::FSUB, VT, Expand);
429 setOperationAction(ISD::FNEG, VT, Expand);
430 setOperationAction(ISD::VSELECT, VT, Expand);
431 setOperationAction(ISD::SELECT_CC, VT, Expand);
432 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
433 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
434 setOperationAction(ISD::SETCC, VT, Expand);
435 setOperationAction(ISD::FCANONICALIZE, VT, Expand);
438 // This causes using an unrolled select operation rather than expansion with
439 // bit operations. This is in general better, but the alternative using BFI
440 // instructions may be better if the select sources are SGPRs.
441 setOperationAction(ISD::SELECT, MVT::v2f32, Promote);
442 AddPromotedToType(ISD::SELECT, MVT::v2f32, MVT::v2i32);
444 setOperationAction(ISD::SELECT, MVT::v3f32, Promote);
445 AddPromotedToType(ISD::SELECT, MVT::v3f32, MVT::v3i32);
447 setOperationAction(ISD::SELECT, MVT::v4f32, Promote);
448 AddPromotedToType(ISD::SELECT, MVT::v4f32, MVT::v4i32);
450 setOperationAction(ISD::SELECT, MVT::v5f32, Promote);
451 AddPromotedToType(ISD::SELECT, MVT::v5f32, MVT::v5i32);
453 // There are no libcalls of any kind.
454 for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
455 setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
457 setBooleanContents(ZeroOrNegativeOneBooleanContent);
458 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
460 setSchedulingPreference(Sched::RegPressure);
461 setJumpIsExpensive(true);
463 // FIXME: This is only partially true. If we have to do vector compares, any
464 // SGPR pair can be a condition register. If we have a uniform condition, we
465 // are better off doing SALU operations, where there is only one SCC. For now,
466 // we don't have a way of knowing during instruction selection if a condition
467 // will be uniform and we always use vector compares. Assume we are using
468 // vector compares until that is fixed.
469 setHasMultipleConditionRegisters(true);
471 setMinCmpXchgSizeInBits(32);
472 setSupportsUnalignedAtomics(false);
474 PredictableSelectIsExpensive = false;
476 // We want to find all load dependencies for long chains of stores to enable
477 // merging into very wide vectors. The problem is with vectors with > 4
478 // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
479 // vectors are a legal type, even though we have to split the loads
480 // usually. When we can more precisely specify load legality per address
481 // space, we should be able to make FindBetterChain/MergeConsecutiveStores
482 // smarter so that they can figure out what to do in 2 iterations without all
483 // N > 4 stores on the same chain.
484 GatherAllAliasesMaxDepth = 16;
486 // memcpy/memmove/memset are expanded in the IR, so we shouldn't need to worry
487 // about these during lowering.
488 MaxStoresPerMemcpy = 0xffffffff;
489 MaxStoresPerMemmove = 0xffffffff;
490 MaxStoresPerMemset = 0xffffffff;
492 setTargetDAGCombine(ISD::BITCAST);
493 setTargetDAGCombine(ISD::SHL);
494 setTargetDAGCombine(ISD::SRA);
495 setTargetDAGCombine(ISD::SRL);
496 setTargetDAGCombine(ISD::TRUNCATE);
497 setTargetDAGCombine(ISD::MUL);
498 setTargetDAGCombine(ISD::MULHU);
499 setTargetDAGCombine(ISD::MULHS);
500 setTargetDAGCombine(ISD::SELECT);
501 setTargetDAGCombine(ISD::SELECT_CC);
502 setTargetDAGCombine(ISD::STORE);
503 setTargetDAGCombine(ISD::FADD);
504 setTargetDAGCombine(ISD::FSUB);
505 setTargetDAGCombine(ISD::FNEG);
506 setTargetDAGCombine(ISD::FABS);
507 setTargetDAGCombine(ISD::AssertZext);
508 setTargetDAGCombine(ISD::AssertSext);
509 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
512 //===----------------------------------------------------------------------===//
513 // Target Information
514 //===----------------------------------------------------------------------===//
516 LLVM_READNONE
517 static bool fnegFoldsIntoOp(unsigned Opc) {
518 switch (Opc) {
519 case ISD::FADD:
520 case ISD::FSUB:
521 case ISD::FMUL:
522 case ISD::FMA:
523 case ISD::FMAD:
524 case ISD::FMINNUM:
525 case ISD::FMAXNUM:
526 case ISD::FMINNUM_IEEE:
527 case ISD::FMAXNUM_IEEE:
528 case ISD::FSIN:
529 case ISD::FTRUNC:
530 case ISD::FRINT:
531 case ISD::FNEARBYINT:
532 case ISD::FCANONICALIZE:
533 case AMDGPUISD::RCP:
534 case AMDGPUISD::RCP_LEGACY:
535 case AMDGPUISD::RCP_IFLAG:
536 case AMDGPUISD::SIN_HW:
537 case AMDGPUISD::FMUL_LEGACY:
538 case AMDGPUISD::FMIN_LEGACY:
539 case AMDGPUISD::FMAX_LEGACY:
540 case AMDGPUISD::FMED3:
541 return true;
542 default:
543 return false;
547 /// \p returns true if the operation will definitely need to use a 64-bit
548 /// encoding, and thus will use a VOP3 encoding regardless of the source
549 /// modifiers.
550 LLVM_READONLY
551 static bool opMustUseVOP3Encoding(const SDNode *N, MVT VT) {
552 return N->getNumOperands() > 2 || VT == MVT::f64;
555 // Most FP instructions support source modifiers, but this could be refined
556 // slightly.
557 LLVM_READONLY
558 static bool hasSourceMods(const SDNode *N) {
559 if (isa<MemSDNode>(N))
560 return false;
562 switch (N->getOpcode()) {
563 case ISD::CopyToReg:
564 case ISD::SELECT:
565 case ISD::FDIV:
566 case ISD::FREM:
567 case ISD::INLINEASM:
568 case ISD::INLINEASM_BR:
569 case AMDGPUISD::INTERP_P1:
570 case AMDGPUISD::INTERP_P2:
571 case AMDGPUISD::DIV_SCALE:
573 // TODO: Should really be looking at the users of the bitcast. These are
574 // problematic because bitcasts are used to legalize all stores to integer
575 // types.
576 case ISD::BITCAST:
577 return false;
578 default:
579 return true;
583 bool AMDGPUTargetLowering::allUsesHaveSourceMods(const SDNode *N,
584 unsigned CostThreshold) {
585 // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus
586 // it is truly free to use a source modifier in all cases. If there are
587 // multiple users but for each one will necessitate using VOP3, there will be
588 // a code size increase. Try to avoid increasing code size unless we know it
589 // will save on the instruction count.
590 unsigned NumMayIncreaseSize = 0;
591 MVT VT = N->getValueType(0).getScalarType().getSimpleVT();
593 // XXX - Should this limit number of uses to check?
594 for (const SDNode *U : N->uses()) {
595 if (!hasSourceMods(U))
596 return false;
598 if (!opMustUseVOP3Encoding(U, VT)) {
599 if (++NumMayIncreaseSize > CostThreshold)
600 return false;
604 return true;
607 MVT AMDGPUTargetLowering::getVectorIdxTy(const DataLayout &) const {
608 return MVT::i32;
611 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
612 return true;
615 // The backend supports 32 and 64 bit floating point immediates.
616 // FIXME: Why are we reporting vectors of FP immediates as legal?
617 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
618 bool ForCodeSize) const {
619 EVT ScalarVT = VT.getScalarType();
620 return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
621 (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
624 // We don't want to shrink f64 / f32 constants.
625 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
626 EVT ScalarVT = VT.getScalarType();
627 return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
630 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
631 ISD::LoadExtType ExtTy,
632 EVT NewVT) const {
633 // TODO: This may be worth removing. Check regression tests for diffs.
634 if (!TargetLoweringBase::shouldReduceLoadWidth(N, ExtTy, NewVT))
635 return false;
637 unsigned NewSize = NewVT.getStoreSizeInBits();
639 // If we are reducing to a 32-bit load, this is always better.
640 if (NewSize == 32)
641 return true;
643 EVT OldVT = N->getValueType(0);
644 unsigned OldSize = OldVT.getStoreSizeInBits();
646 MemSDNode *MN = cast<MemSDNode>(N);
647 unsigned AS = MN->getAddressSpace();
648 // Do not shrink an aligned scalar load to sub-dword.
649 // Scalar engine cannot do sub-dword loads.
650 if (OldSize >= 32 && NewSize < 32 && MN->getAlignment() >= 4 &&
651 (AS == AMDGPUAS::CONSTANT_ADDRESS ||
652 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
653 (isa<LoadSDNode>(N) &&
654 AS == AMDGPUAS::GLOBAL_ADDRESS && MN->isInvariant())) &&
655 AMDGPUInstrInfo::isUniformMMO(MN->getMemOperand()))
656 return false;
658 // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
659 // extloads, so doing one requires using a buffer_load. In cases where we
660 // still couldn't use a scalar load, using the wider load shouldn't really
661 // hurt anything.
663 // If the old size already had to be an extload, there's no harm in continuing
664 // to reduce the width.
665 return (OldSize < 32);
668 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy, EVT CastTy,
669 const SelectionDAG &DAG,
670 const MachineMemOperand &MMO) const {
672 assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
674 if (LoadTy.getScalarType() == MVT::i32)
675 return false;
677 unsigned LScalarSize = LoadTy.getScalarSizeInBits();
678 unsigned CastScalarSize = CastTy.getScalarSizeInBits();
680 if ((LScalarSize >= CastScalarSize) && (CastScalarSize < 32))
681 return false;
683 bool Fast = false;
684 return allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
685 CastTy, MMO, &Fast) &&
686 Fast;
689 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
690 // profitable with the expansion for 64-bit since it's generally good to
691 // speculate things.
692 // FIXME: These should really have the size as a parameter.
693 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
694 return true;
697 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
698 return true;
701 bool AMDGPUTargetLowering::isSDNodeAlwaysUniform(const SDNode * N) const {
702 switch (N->getOpcode()) {
703 default:
704 return false;
705 case ISD::EntryToken:
706 case ISD::TokenFactor:
707 return true;
708 case ISD::INTRINSIC_WO_CHAIN:
710 unsigned IntrID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
711 switch (IntrID) {
712 default:
713 return false;
714 case Intrinsic::amdgcn_readfirstlane:
715 case Intrinsic::amdgcn_readlane:
716 return true;
719 break;
720 case ISD::LOAD:
722 if (cast<LoadSDNode>(N)->getMemOperand()->getAddrSpace() ==
723 AMDGPUAS::CONSTANT_ADDRESS_32BIT)
724 return true;
725 return false;
727 break;
731 //===---------------------------------------------------------------------===//
732 // Target Properties
733 //===---------------------------------------------------------------------===//
735 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
736 assert(VT.isFloatingPoint());
738 // Packed operations do not have a fabs modifier.
739 return VT == MVT::f32 || VT == MVT::f64 ||
740 (Subtarget->has16BitInsts() && VT == MVT::f16);
743 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
744 assert(VT.isFloatingPoint());
745 return VT == MVT::f32 || VT == MVT::f64 ||
746 (Subtarget->has16BitInsts() && VT == MVT::f16) ||
747 (Subtarget->hasVOP3PInsts() && VT == MVT::v2f16);
750 bool AMDGPUTargetLowering:: storeOfVectorConstantIsCheap(EVT MemVT,
751 unsigned NumElem,
752 unsigned AS) const {
753 return true;
756 bool AMDGPUTargetLowering::aggressivelyPreferBuildVectorSources(EVT VecVT) const {
757 // There are few operations which truly have vector input operands. Any vector
758 // operation is going to involve operations on each component, and a
759 // build_vector will be a copy per element, so it always makes sense to use a
760 // build_vector input in place of the extracted element to avoid a copy into a
761 // super register.
763 // We should probably only do this if all users are extracts only, but this
764 // should be the common case.
765 return true;
768 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
769 // Truncate is just accessing a subregister.
771 unsigned SrcSize = Source.getSizeInBits();
772 unsigned DestSize = Dest.getSizeInBits();
774 return DestSize < SrcSize && DestSize % 32 == 0 ;
777 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
778 // Truncate is just accessing a subregister.
780 unsigned SrcSize = Source->getScalarSizeInBits();
781 unsigned DestSize = Dest->getScalarSizeInBits();
783 if (DestSize== 16 && Subtarget->has16BitInsts())
784 return SrcSize >= 32;
786 return DestSize < SrcSize && DestSize % 32 == 0;
789 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
790 unsigned SrcSize = Src->getScalarSizeInBits();
791 unsigned DestSize = Dest->getScalarSizeInBits();
793 if (SrcSize == 16 && Subtarget->has16BitInsts())
794 return DestSize >= 32;
796 return SrcSize == 32 && DestSize == 64;
799 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
800 // Any register load of a 64-bit value really requires 2 32-bit moves. For all
801 // practical purposes, the extra mov 0 to load a 64-bit is free. As used,
802 // this will enable reducing 64-bit operations the 32-bit, which is always
803 // good.
805 if (Src == MVT::i16)
806 return Dest == MVT::i32 ||Dest == MVT::i64 ;
808 return Src == MVT::i32 && Dest == MVT::i64;
811 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
812 return isZExtFree(Val.getValueType(), VT2);
815 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
816 // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
817 // limited number of native 64-bit operations. Shrinking an operation to fit
818 // in a single 32-bit register should always be helpful. As currently used,
819 // this is much less general than the name suggests, and is only used in
820 // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
821 // not profitable, and may actually be harmful.
822 return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
825 //===---------------------------------------------------------------------===//
826 // TargetLowering Callbacks
827 //===---------------------------------------------------------------------===//
829 CCAssignFn *AMDGPUCallLowering::CCAssignFnForCall(CallingConv::ID CC,
830 bool IsVarArg) {
831 switch (CC) {
832 case CallingConv::AMDGPU_VS:
833 case CallingConv::AMDGPU_GS:
834 case CallingConv::AMDGPU_PS:
835 case CallingConv::AMDGPU_CS:
836 case CallingConv::AMDGPU_HS:
837 case CallingConv::AMDGPU_ES:
838 case CallingConv::AMDGPU_LS:
839 return CC_AMDGPU;
840 case CallingConv::C:
841 case CallingConv::Fast:
842 case CallingConv::Cold:
843 return CC_AMDGPU_Func;
844 case CallingConv::AMDGPU_KERNEL:
845 case CallingConv::SPIR_KERNEL:
846 default:
847 report_fatal_error("Unsupported calling convention for call");
851 CCAssignFn *AMDGPUCallLowering::CCAssignFnForReturn(CallingConv::ID CC,
852 bool IsVarArg) {
853 switch (CC) {
854 case CallingConv::AMDGPU_KERNEL:
855 case CallingConv::SPIR_KERNEL:
856 llvm_unreachable("kernels should not be handled here");
857 case CallingConv::AMDGPU_VS:
858 case CallingConv::AMDGPU_GS:
859 case CallingConv::AMDGPU_PS:
860 case CallingConv::AMDGPU_CS:
861 case CallingConv::AMDGPU_HS:
862 case CallingConv::AMDGPU_ES:
863 case CallingConv::AMDGPU_LS:
864 return RetCC_SI_Shader;
865 case CallingConv::C:
866 case CallingConv::Fast:
867 case CallingConv::Cold:
868 return RetCC_AMDGPU_Func;
869 default:
870 report_fatal_error("Unsupported calling convention.");
874 /// The SelectionDAGBuilder will automatically promote function arguments
875 /// with illegal types. However, this does not work for the AMDGPU targets
876 /// since the function arguments are stored in memory as these illegal types.
877 /// In order to handle this properly we need to get the original types sizes
878 /// from the LLVM IR Function and fixup the ISD:InputArg values before
879 /// passing them to AnalyzeFormalArguments()
881 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
882 /// input values across multiple registers. Each item in the Ins array
883 /// represents a single value that will be stored in registers. Ins[x].VT is
884 /// the value type of the value that will be stored in the register, so
885 /// whatever SDNode we lower the argument to needs to be this type.
887 /// In order to correctly lower the arguments we need to know the size of each
888 /// argument. Since Ins[x].VT gives us the size of the register that will
889 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
890 /// for the orignal function argument so that we can deduce the correct memory
891 /// type to use for Ins[x]. In most cases the correct memory type will be
892 /// Ins[x].ArgVT. However, this will not always be the case. If, for example,
893 /// we have a kernel argument of type v8i8, this argument will be split into
894 /// 8 parts and each part will be represented by its own item in the Ins array.
895 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
896 /// the argument before it was split. From this, we deduce that the memory type
897 /// for each individual part is i8. We pass the memory type as LocVT to the
898 /// calling convention analysis function and the register type (Ins[x].VT) as
899 /// the ValVT.
900 void AMDGPUTargetLowering::analyzeFormalArgumentsCompute(
901 CCState &State,
902 const SmallVectorImpl<ISD::InputArg> &Ins) const {
903 const MachineFunction &MF = State.getMachineFunction();
904 const Function &Fn = MF.getFunction();
905 LLVMContext &Ctx = Fn.getParent()->getContext();
906 const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(MF);
907 const unsigned ExplicitOffset = ST.getExplicitKernelArgOffset(Fn);
908 CallingConv::ID CC = Fn.getCallingConv();
910 unsigned MaxAlign = 1;
911 uint64_t ExplicitArgOffset = 0;
912 const DataLayout &DL = Fn.getParent()->getDataLayout();
914 unsigned InIndex = 0;
916 for (const Argument &Arg : Fn.args()) {
917 Type *BaseArgTy = Arg.getType();
918 unsigned Align = DL.getABITypeAlignment(BaseArgTy);
919 MaxAlign = std::max(Align, MaxAlign);
920 unsigned AllocSize = DL.getTypeAllocSize(BaseArgTy);
922 uint64_t ArgOffset = alignTo(ExplicitArgOffset, Align) + ExplicitOffset;
923 ExplicitArgOffset = alignTo(ExplicitArgOffset, Align) + AllocSize;
925 // We're basically throwing away everything passed into us and starting over
926 // to get accurate in-memory offsets. The "PartOffset" is completely useless
927 // to us as computed in Ins.
929 // We also need to figure out what type legalization is trying to do to get
930 // the correct memory offsets.
932 SmallVector<EVT, 16> ValueVTs;
933 SmallVector<uint64_t, 16> Offsets;
934 ComputeValueVTs(*this, DL, BaseArgTy, ValueVTs, &Offsets, ArgOffset);
936 for (unsigned Value = 0, NumValues = ValueVTs.size();
937 Value != NumValues; ++Value) {
938 uint64_t BasePartOffset = Offsets[Value];
940 EVT ArgVT = ValueVTs[Value];
941 EVT MemVT = ArgVT;
942 MVT RegisterVT = getRegisterTypeForCallingConv(Ctx, CC, ArgVT);
943 unsigned NumRegs = getNumRegistersForCallingConv(Ctx, CC, ArgVT);
945 if (NumRegs == 1) {
946 // This argument is not split, so the IR type is the memory type.
947 if (ArgVT.isExtended()) {
948 // We have an extended type, like i24, so we should just use the
949 // register type.
950 MemVT = RegisterVT;
951 } else {
952 MemVT = ArgVT;
954 } else if (ArgVT.isVector() && RegisterVT.isVector() &&
955 ArgVT.getScalarType() == RegisterVT.getScalarType()) {
956 assert(ArgVT.getVectorNumElements() > RegisterVT.getVectorNumElements());
957 // We have a vector value which has been split into a vector with
958 // the same scalar type, but fewer elements. This should handle
959 // all the floating-point vector types.
960 MemVT = RegisterVT;
961 } else if (ArgVT.isVector() &&
962 ArgVT.getVectorNumElements() == NumRegs) {
963 // This arg has been split so that each element is stored in a separate
964 // register.
965 MemVT = ArgVT.getScalarType();
966 } else if (ArgVT.isExtended()) {
967 // We have an extended type, like i65.
968 MemVT = RegisterVT;
969 } else {
970 unsigned MemoryBits = ArgVT.getStoreSizeInBits() / NumRegs;
971 assert(ArgVT.getStoreSizeInBits() % NumRegs == 0);
972 if (RegisterVT.isInteger()) {
973 MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
974 } else if (RegisterVT.isVector()) {
975 assert(!RegisterVT.getScalarType().isFloatingPoint());
976 unsigned NumElements = RegisterVT.getVectorNumElements();
977 assert(MemoryBits % NumElements == 0);
978 // This vector type has been split into another vector type with
979 // a different elements size.
980 EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
981 MemoryBits / NumElements);
982 MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
983 } else {
984 llvm_unreachable("cannot deduce memory type.");
988 // Convert one element vectors to scalar.
989 if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
990 MemVT = MemVT.getScalarType();
992 // Round up vec3/vec5 argument.
993 if (MemVT.isVector() && !MemVT.isPow2VectorType()) {
994 assert(MemVT.getVectorNumElements() == 3 ||
995 MemVT.getVectorNumElements() == 5);
996 MemVT = MemVT.getPow2VectorType(State.getContext());
999 unsigned PartOffset = 0;
1000 for (unsigned i = 0; i != NumRegs; ++i) {
1001 State.addLoc(CCValAssign::getCustomMem(InIndex++, RegisterVT,
1002 BasePartOffset + PartOffset,
1003 MemVT.getSimpleVT(),
1004 CCValAssign::Full));
1005 PartOffset += MemVT.getStoreSize();
1011 SDValue AMDGPUTargetLowering::LowerReturn(
1012 SDValue Chain, CallingConv::ID CallConv,
1013 bool isVarArg,
1014 const SmallVectorImpl<ISD::OutputArg> &Outs,
1015 const SmallVectorImpl<SDValue> &OutVals,
1016 const SDLoc &DL, SelectionDAG &DAG) const {
1017 // FIXME: Fails for r600 tests
1018 //assert(!isVarArg && Outs.empty() && OutVals.empty() &&
1019 // "wave terminate should not have return values");
1020 return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
1023 //===---------------------------------------------------------------------===//
1024 // Target specific lowering
1025 //===---------------------------------------------------------------------===//
1027 /// Selects the correct CCAssignFn for a given CallingConvention value.
1028 CCAssignFn *AMDGPUTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1029 bool IsVarArg) {
1030 return AMDGPUCallLowering::CCAssignFnForCall(CC, IsVarArg);
1033 CCAssignFn *AMDGPUTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1034 bool IsVarArg) {
1035 return AMDGPUCallLowering::CCAssignFnForReturn(CC, IsVarArg);
1038 SDValue AMDGPUTargetLowering::addTokenForArgument(SDValue Chain,
1039 SelectionDAG &DAG,
1040 MachineFrameInfo &MFI,
1041 int ClobberedFI) const {
1042 SmallVector<SDValue, 8> ArgChains;
1043 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
1044 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
1046 // Include the original chain at the beginning of the list. When this is
1047 // used by target LowerCall hooks, this helps legalize find the
1048 // CALLSEQ_BEGIN node.
1049 ArgChains.push_back(Chain);
1051 // Add a chain value for each stack argument corresponding
1052 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1053 UE = DAG.getEntryNode().getNode()->use_end();
1054 U != UE; ++U) {
1055 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) {
1056 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) {
1057 if (FI->getIndex() < 0) {
1058 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
1059 int64_t InLastByte = InFirstByte;
1060 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
1062 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1063 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1064 ArgChains.push_back(SDValue(L, 1));
1070 // Build a tokenfactor for all the chains.
1071 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
1074 SDValue AMDGPUTargetLowering::lowerUnhandledCall(CallLoweringInfo &CLI,
1075 SmallVectorImpl<SDValue> &InVals,
1076 StringRef Reason) const {
1077 SDValue Callee = CLI.Callee;
1078 SelectionDAG &DAG = CLI.DAG;
1080 const Function &Fn = DAG.getMachineFunction().getFunction();
1082 StringRef FuncName("<unknown>");
1084 if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
1085 FuncName = G->getSymbol();
1086 else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1087 FuncName = G->getGlobal()->getName();
1089 DiagnosticInfoUnsupported NoCalls(
1090 Fn, Reason + FuncName, CLI.DL.getDebugLoc());
1091 DAG.getContext()->diagnose(NoCalls);
1093 if (!CLI.IsTailCall) {
1094 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
1095 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
1098 return DAG.getEntryNode();
1101 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
1102 SmallVectorImpl<SDValue> &InVals) const {
1103 return lowerUnhandledCall(CLI, InVals, "unsupported call to function ");
1106 SDValue AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1107 SelectionDAG &DAG) const {
1108 const Function &Fn = DAG.getMachineFunction().getFunction();
1110 DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
1111 SDLoc(Op).getDebugLoc());
1112 DAG.getContext()->diagnose(NoDynamicAlloca);
1113 auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
1114 return DAG.getMergeValues(Ops, SDLoc());
1117 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
1118 SelectionDAG &DAG) const {
1119 switch (Op.getOpcode()) {
1120 default:
1121 Op->print(errs(), &DAG);
1122 llvm_unreachable("Custom lowering code for this"
1123 "instruction is not implemented yet!");
1124 break;
1125 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
1126 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
1127 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
1128 case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
1129 case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
1130 case ISD::FREM: return LowerFREM(Op, DAG);
1131 case ISD::FCEIL: return LowerFCEIL(Op, DAG);
1132 case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
1133 case ISD::FRINT: return LowerFRINT(Op, DAG);
1134 case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
1135 case ISD::FROUND: return LowerFROUND(Op, DAG);
1136 case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
1137 case ISD::FLOG:
1138 return LowerFLOG(Op, DAG, 1 / AMDGPU_LOG2E_F);
1139 case ISD::FLOG10:
1140 return LowerFLOG(Op, DAG, AMDGPU_LN2_F / AMDGPU_LN10_F);
1141 case ISD::FEXP:
1142 return lowerFEXP(Op, DAG);
1143 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
1144 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
1145 case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
1146 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
1147 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
1148 case ISD::CTTZ:
1149 case ISD::CTTZ_ZERO_UNDEF:
1150 case ISD::CTLZ:
1151 case ISD::CTLZ_ZERO_UNDEF:
1152 return LowerCTLZ_CTTZ(Op, DAG);
1153 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1155 return Op;
1158 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
1159 SmallVectorImpl<SDValue> &Results,
1160 SelectionDAG &DAG) const {
1161 switch (N->getOpcode()) {
1162 case ISD::SIGN_EXTEND_INREG:
1163 // Different parts of legalization seem to interpret which type of
1164 // sign_extend_inreg is the one to check for custom lowering. The extended
1165 // from type is what really matters, but some places check for custom
1166 // lowering of the result type. This results in trying to use
1167 // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
1168 // nothing here and let the illegal result integer be handled normally.
1169 return;
1170 default:
1171 return;
1175 bool AMDGPUTargetLowering::hasDefinedInitializer(const GlobalValue *GV) {
1176 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1177 if (!GVar || !GVar->hasInitializer())
1178 return false;
1180 return !isa<UndefValue>(GVar->getInitializer());
1183 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
1184 SDValue Op,
1185 SelectionDAG &DAG) const {
1187 const DataLayout &DL = DAG.getDataLayout();
1188 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
1189 const GlobalValue *GV = G->getGlobal();
1191 if (G->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1192 G->getAddressSpace() == AMDGPUAS::REGION_ADDRESS) {
1193 if (!MFI->isEntryFunction()) {
1194 const Function &Fn = DAG.getMachineFunction().getFunction();
1195 DiagnosticInfoUnsupported BadLDSDecl(
1196 Fn, "local memory global used by non-kernel function", SDLoc(Op).getDebugLoc());
1197 DAG.getContext()->diagnose(BadLDSDecl);
1200 // XXX: What does the value of G->getOffset() mean?
1201 assert(G->getOffset() == 0 &&
1202 "Do not know what to do with an non-zero offset");
1204 // TODO: We could emit code to handle the initialization somewhere.
1205 if (!hasDefinedInitializer(GV)) {
1206 unsigned Offset = MFI->allocateLDSGlobal(DL, *GV);
1207 return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
1211 const Function &Fn = DAG.getMachineFunction().getFunction();
1212 DiagnosticInfoUnsupported BadInit(
1213 Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
1214 DAG.getContext()->diagnose(BadInit);
1215 return SDValue();
1218 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
1219 SelectionDAG &DAG) const {
1220 SmallVector<SDValue, 8> Args;
1222 EVT VT = Op.getValueType();
1223 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
1224 SDLoc SL(Op);
1225 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(0));
1226 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(1));
1228 SDValue BV = DAG.getBuildVector(MVT::v2i32, SL, { Lo, Hi });
1229 return DAG.getNode(ISD::BITCAST, SL, VT, BV);
1232 for (const SDUse &U : Op->ops())
1233 DAG.ExtractVectorElements(U.get(), Args);
1235 return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1238 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
1239 SelectionDAG &DAG) const {
1241 SmallVector<SDValue, 8> Args;
1242 unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1243 EVT VT = Op.getValueType();
1244 DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
1245 VT.getVectorNumElements());
1247 return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1250 /// Generate Min/Max node
1251 SDValue AMDGPUTargetLowering::combineFMinMaxLegacy(const SDLoc &DL, EVT VT,
1252 SDValue LHS, SDValue RHS,
1253 SDValue True, SDValue False,
1254 SDValue CC,
1255 DAGCombinerInfo &DCI) const {
1256 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1257 return SDValue();
1259 SelectionDAG &DAG = DCI.DAG;
1260 ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1261 switch (CCOpcode) {
1262 case ISD::SETOEQ:
1263 case ISD::SETONE:
1264 case ISD::SETUNE:
1265 case ISD::SETNE:
1266 case ISD::SETUEQ:
1267 case ISD::SETEQ:
1268 case ISD::SETFALSE:
1269 case ISD::SETFALSE2:
1270 case ISD::SETTRUE:
1271 case ISD::SETTRUE2:
1272 case ISD::SETUO:
1273 case ISD::SETO:
1274 break;
1275 case ISD::SETULE:
1276 case ISD::SETULT: {
1277 if (LHS == True)
1278 return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1279 return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1281 case ISD::SETOLE:
1282 case ISD::SETOLT:
1283 case ISD::SETLE:
1284 case ISD::SETLT: {
1285 // Ordered. Assume ordered for undefined.
1287 // Only do this after legalization to avoid interfering with other combines
1288 // which might occur.
1289 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1290 !DCI.isCalledByLegalizer())
1291 return SDValue();
1293 // We need to permute the operands to get the correct NaN behavior. The
1294 // selected operand is the second one based on the failing compare with NaN,
1295 // so permute it based on the compare type the hardware uses.
1296 if (LHS == True)
1297 return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1298 return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1300 case ISD::SETUGE:
1301 case ISD::SETUGT: {
1302 if (LHS == True)
1303 return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1304 return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1306 case ISD::SETGT:
1307 case ISD::SETGE:
1308 case ISD::SETOGE:
1309 case ISD::SETOGT: {
1310 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1311 !DCI.isCalledByLegalizer())
1312 return SDValue();
1314 if (LHS == True)
1315 return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1316 return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1318 case ISD::SETCC_INVALID:
1319 llvm_unreachable("Invalid setcc condcode!");
1321 return SDValue();
1324 std::pair<SDValue, SDValue>
1325 AMDGPUTargetLowering::split64BitValue(SDValue Op, SelectionDAG &DAG) const {
1326 SDLoc SL(Op);
1328 SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1330 const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1331 const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1333 SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1334 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1336 return std::make_pair(Lo, Hi);
1339 SDValue AMDGPUTargetLowering::getLoHalf64(SDValue Op, SelectionDAG &DAG) const {
1340 SDLoc SL(Op);
1342 SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1343 const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1344 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1347 SDValue AMDGPUTargetLowering::getHiHalf64(SDValue Op, SelectionDAG &DAG) const {
1348 SDLoc SL(Op);
1350 SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1351 const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1355 // Split a vector type into two parts. The first part is a power of two vector.
1356 // The second part is whatever is left over, and is a scalar if it would
1357 // otherwise be a 1-vector.
1358 std::pair<EVT, EVT>
1359 AMDGPUTargetLowering::getSplitDestVTs(const EVT &VT, SelectionDAG &DAG) const {
1360 EVT LoVT, HiVT;
1361 EVT EltVT = VT.getVectorElementType();
1362 unsigned NumElts = VT.getVectorNumElements();
1363 unsigned LoNumElts = PowerOf2Ceil((NumElts + 1) / 2);
1364 LoVT = EVT::getVectorVT(*DAG.getContext(), EltVT, LoNumElts);
1365 HiVT = NumElts - LoNumElts == 1
1366 ? EltVT
1367 : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts - LoNumElts);
1368 return std::make_pair(LoVT, HiVT);
1371 // Split a vector value into two parts of types LoVT and HiVT. HiVT could be
1372 // scalar.
1373 std::pair<SDValue, SDValue>
1374 AMDGPUTargetLowering::splitVector(const SDValue &N, const SDLoc &DL,
1375 const EVT &LoVT, const EVT &HiVT,
1376 SelectionDAG &DAG) const {
1377 assert(LoVT.getVectorNumElements() +
1378 (HiVT.isVector() ? HiVT.getVectorNumElements() : 1) <=
1379 N.getValueType().getVectorNumElements() &&
1380 "More vector elements requested than available!");
1381 auto IdxTy = getVectorIdxTy(DAG.getDataLayout());
1382 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
1383 DAG.getConstant(0, DL, IdxTy));
1384 SDValue Hi = DAG.getNode(
1385 HiVT.isVector() ? ISD::EXTRACT_SUBVECTOR : ISD::EXTRACT_VECTOR_ELT, DL,
1386 HiVT, N, DAG.getConstant(LoVT.getVectorNumElements(), DL, IdxTy));
1387 return std::make_pair(Lo, Hi);
1390 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1391 SelectionDAG &DAG) const {
1392 LoadSDNode *Load = cast<LoadSDNode>(Op);
1393 EVT VT = Op.getValueType();
1396 // If this is a 2 element vector, we really want to scalarize and not create
1397 // weird 1 element vectors.
1398 if (VT.getVectorNumElements() == 2)
1399 return scalarizeVectorLoad(Load, DAG);
1401 SDValue BasePtr = Load->getBasePtr();
1402 EVT MemVT = Load->getMemoryVT();
1403 SDLoc SL(Op);
1405 const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1407 EVT LoVT, HiVT;
1408 EVT LoMemVT, HiMemVT;
1409 SDValue Lo, Hi;
1411 std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1412 std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1413 std::tie(Lo, Hi) = splitVector(Op, SL, LoVT, HiVT, DAG);
1415 unsigned Size = LoMemVT.getStoreSize();
1416 unsigned BaseAlign = Load->getAlignment();
1417 unsigned HiAlign = MinAlign(BaseAlign, Size);
1419 SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1420 Load->getChain(), BasePtr, SrcValue, LoMemVT,
1421 BaseAlign, Load->getMemOperand()->getFlags());
1422 SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, Size);
1423 SDValue HiLoad =
1424 DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1425 HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1426 HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1428 auto IdxTy = getVectorIdxTy(DAG.getDataLayout());
1429 SDValue Join;
1430 if (LoVT == HiVT) {
1431 // This is the case that the vector is power of two so was evenly split.
1432 Join = DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad);
1433 } else {
1434 Join = DAG.getNode(ISD::INSERT_SUBVECTOR, SL, VT, DAG.getUNDEF(VT), LoLoad,
1435 DAG.getConstant(0, SL, IdxTy));
1436 Join = DAG.getNode(HiVT.isVector() ? ISD::INSERT_SUBVECTOR
1437 : ISD::INSERT_VECTOR_ELT,
1438 SL, VT, Join, HiLoad,
1439 DAG.getConstant(LoVT.getVectorNumElements(), SL, IdxTy));
1442 SDValue Ops[] = {Join, DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1443 LoLoad.getValue(1), HiLoad.getValue(1))};
1445 return DAG.getMergeValues(Ops, SL);
1448 // Widen a vector load from vec3 to vec4.
1449 SDValue AMDGPUTargetLowering::WidenVectorLoad(SDValue Op,
1450 SelectionDAG &DAG) const {
1451 LoadSDNode *Load = cast<LoadSDNode>(Op);
1452 EVT VT = Op.getValueType();
1453 assert(VT.getVectorNumElements() == 3);
1454 SDValue BasePtr = Load->getBasePtr();
1455 EVT MemVT = Load->getMemoryVT();
1456 SDLoc SL(Op);
1457 const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1458 unsigned BaseAlign = Load->getAlignment();
1460 EVT WideVT =
1461 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
1462 EVT WideMemVT =
1463 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 4);
1464 SDValue WideLoad = DAG.getExtLoad(
1465 Load->getExtensionType(), SL, WideVT, Load->getChain(), BasePtr, SrcValue,
1466 WideMemVT, BaseAlign, Load->getMemOperand()->getFlags());
1467 return DAG.getMergeValues(
1468 {DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, VT, WideLoad,
1469 DAG.getConstant(0, SL, getVectorIdxTy(DAG.getDataLayout()))),
1470 WideLoad.getValue(1)},
1471 SL);
1474 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1475 SelectionDAG &DAG) const {
1476 StoreSDNode *Store = cast<StoreSDNode>(Op);
1477 SDValue Val = Store->getValue();
1478 EVT VT = Val.getValueType();
1480 // If this is a 2 element vector, we really want to scalarize and not create
1481 // weird 1 element vectors.
1482 if (VT.getVectorNumElements() == 2)
1483 return scalarizeVectorStore(Store, DAG);
1485 EVT MemVT = Store->getMemoryVT();
1486 SDValue Chain = Store->getChain();
1487 SDValue BasePtr = Store->getBasePtr();
1488 SDLoc SL(Op);
1490 EVT LoVT, HiVT;
1491 EVT LoMemVT, HiMemVT;
1492 SDValue Lo, Hi;
1494 std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1495 std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1496 std::tie(Lo, Hi) = splitVector(Val, SL, LoVT, HiVT, DAG);
1498 SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, LoMemVT.getStoreSize());
1500 const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1501 unsigned BaseAlign = Store->getAlignment();
1502 unsigned Size = LoMemVT.getStoreSize();
1503 unsigned HiAlign = MinAlign(BaseAlign, Size);
1505 SDValue LoStore =
1506 DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1507 Store->getMemOperand()->getFlags());
1508 SDValue HiStore =
1509 DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1510 HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1512 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1515 // This is a shortcut for integer division because we have fast i32<->f32
1516 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1517 // float is enough to accurately represent up to a 24-bit signed integer.
1518 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG,
1519 bool Sign) const {
1520 SDLoc DL(Op);
1521 EVT VT = Op.getValueType();
1522 SDValue LHS = Op.getOperand(0);
1523 SDValue RHS = Op.getOperand(1);
1524 MVT IntVT = MVT::i32;
1525 MVT FltVT = MVT::f32;
1527 unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1528 if (LHSSignBits < 9)
1529 return SDValue();
1531 unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1532 if (RHSSignBits < 9)
1533 return SDValue();
1535 unsigned BitSize = VT.getSizeInBits();
1536 unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1537 unsigned DivBits = BitSize - SignBits;
1538 if (Sign)
1539 ++DivBits;
1541 ISD::NodeType ToFp = Sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1542 ISD::NodeType ToInt = Sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1544 SDValue jq = DAG.getConstant(1, DL, IntVT);
1546 if (Sign) {
1547 // char|short jq = ia ^ ib;
1548 jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1550 // jq = jq >> (bitsize - 2)
1551 jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1552 DAG.getConstant(BitSize - 2, DL, VT));
1554 // jq = jq | 0x1
1555 jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1558 // int ia = (int)LHS;
1559 SDValue ia = LHS;
1561 // int ib, (int)RHS;
1562 SDValue ib = RHS;
1564 // float fa = (float)ia;
1565 SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1567 // float fb = (float)ib;
1568 SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1570 SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1571 fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1573 // fq = trunc(fq);
1574 fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1576 // float fqneg = -fq;
1577 SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1579 // float fr = mad(fqneg, fb, fa);
1580 unsigned OpCode = Subtarget->hasFP32Denormals() ?
1581 (unsigned)AMDGPUISD::FMAD_FTZ :
1582 (unsigned)ISD::FMAD;
1583 SDValue fr = DAG.getNode(OpCode, DL, FltVT, fqneg, fb, fa);
1585 // int iq = (int)fq;
1586 SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1588 // fr = fabs(fr);
1589 fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1591 // fb = fabs(fb);
1592 fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1594 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1596 // int cv = fr >= fb;
1597 SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1599 // jq = (cv ? jq : 0);
1600 jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1602 // dst = iq + jq;
1603 SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1605 // Rem needs compensation, it's easier to recompute it
1606 SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1607 Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1609 // Truncate to number of bits this divide really is.
1610 if (Sign) {
1611 SDValue InRegSize
1612 = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1613 Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1614 Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1615 } else {
1616 SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1617 Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1618 Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1621 return DAG.getMergeValues({ Div, Rem }, DL);
1624 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1625 SelectionDAG &DAG,
1626 SmallVectorImpl<SDValue> &Results) const {
1627 SDLoc DL(Op);
1628 EVT VT = Op.getValueType();
1630 assert(VT == MVT::i64 && "LowerUDIVREM64 expects an i64");
1632 EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1634 SDValue One = DAG.getConstant(1, DL, HalfVT);
1635 SDValue Zero = DAG.getConstant(0, DL, HalfVT);
1637 //HiLo split
1638 SDValue LHS = Op.getOperand(0);
1639 SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1640 SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, One);
1642 SDValue RHS = Op.getOperand(1);
1643 SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1644 SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, One);
1646 if (DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1647 DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1649 SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1650 LHS_Lo, RHS_Lo);
1652 SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), Zero});
1653 SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), Zero});
1655 Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1656 Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1657 return;
1660 if (isTypeLegal(MVT::i64)) {
1661 // Compute denominator reciprocal.
1662 unsigned FMAD = Subtarget->hasFP32Denormals() ?
1663 (unsigned)AMDGPUISD::FMAD_FTZ :
1664 (unsigned)ISD::FMAD;
1666 SDValue Cvt_Lo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Lo);
1667 SDValue Cvt_Hi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Hi);
1668 SDValue Mad1 = DAG.getNode(FMAD, DL, MVT::f32, Cvt_Hi,
1669 DAG.getConstantFP(APInt(32, 0x4f800000).bitsToFloat(), DL, MVT::f32),
1670 Cvt_Lo);
1671 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, DL, MVT::f32, Mad1);
1672 SDValue Mul1 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Rcp,
1673 DAG.getConstantFP(APInt(32, 0x5f7ffffc).bitsToFloat(), DL, MVT::f32));
1674 SDValue Mul2 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Mul1,
1675 DAG.getConstantFP(APInt(32, 0x2f800000).bitsToFloat(), DL, MVT::f32));
1676 SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, MVT::f32, Mul2);
1677 SDValue Mad2 = DAG.getNode(FMAD, DL, MVT::f32, Trunc,
1678 DAG.getConstantFP(APInt(32, 0xcf800000).bitsToFloat(), DL, MVT::f32),
1679 Mul1);
1680 SDValue Rcp_Lo = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Mad2);
1681 SDValue Rcp_Hi = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Trunc);
1682 SDValue Rcp64 = DAG.getBitcast(VT,
1683 DAG.getBuildVector(MVT::v2i32, DL, {Rcp_Lo, Rcp_Hi}));
1685 SDValue Zero64 = DAG.getConstant(0, DL, VT);
1686 SDValue One64 = DAG.getConstant(1, DL, VT);
1687 SDValue Zero1 = DAG.getConstant(0, DL, MVT::i1);
1688 SDVTList HalfCarryVT = DAG.getVTList(HalfVT, MVT::i1);
1690 SDValue Neg_RHS = DAG.getNode(ISD::SUB, DL, VT, Zero64, RHS);
1691 SDValue Mullo1 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Rcp64);
1692 SDValue Mulhi1 = DAG.getNode(ISD::MULHU, DL, VT, Rcp64, Mullo1);
1693 SDValue Mulhi1_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1694 Zero);
1695 SDValue Mulhi1_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1696 One);
1698 SDValue Add1_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Lo,
1699 Mulhi1_Lo, Zero1);
1700 SDValue Add1_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Hi,
1701 Mulhi1_Hi, Add1_Lo.getValue(1));
1702 SDValue Add1_HiNc = DAG.getNode(ISD::ADD, DL, HalfVT, Rcp_Hi, Mulhi1_Hi);
1703 SDValue Add1 = DAG.getBitcast(VT,
1704 DAG.getBuildVector(MVT::v2i32, DL, {Add1_Lo, Add1_Hi}));
1706 SDValue Mullo2 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Add1);
1707 SDValue Mulhi2 = DAG.getNode(ISD::MULHU, DL, VT, Add1, Mullo2);
1708 SDValue Mulhi2_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1709 Zero);
1710 SDValue Mulhi2_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1711 One);
1713 SDValue Add2_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_Lo,
1714 Mulhi2_Lo, Zero1);
1715 SDValue Add2_HiC = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_HiNc,
1716 Mulhi2_Hi, Add1_Lo.getValue(1));
1717 SDValue Add2_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add2_HiC,
1718 Zero, Add2_Lo.getValue(1));
1719 SDValue Add2 = DAG.getBitcast(VT,
1720 DAG.getBuildVector(MVT::v2i32, DL, {Add2_Lo, Add2_Hi}));
1721 SDValue Mulhi3 = DAG.getNode(ISD::MULHU, DL, VT, LHS, Add2);
1723 SDValue Mul3 = DAG.getNode(ISD::MUL, DL, VT, RHS, Mulhi3);
1725 SDValue Mul3_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, Zero);
1726 SDValue Mul3_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, One);
1727 SDValue Sub1_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Lo,
1728 Mul3_Lo, Zero1);
1729 SDValue Sub1_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Hi,
1730 Mul3_Hi, Sub1_Lo.getValue(1));
1731 SDValue Sub1_Mi = DAG.getNode(ISD::SUB, DL, HalfVT, LHS_Hi, Mul3_Hi);
1732 SDValue Sub1 = DAG.getBitcast(VT,
1733 DAG.getBuildVector(MVT::v2i32, DL, {Sub1_Lo, Sub1_Hi}));
1735 SDValue MinusOne = DAG.getConstant(0xffffffffu, DL, HalfVT);
1736 SDValue C1 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, MinusOne, Zero,
1737 ISD::SETUGE);
1738 SDValue C2 = DAG.getSelectCC(DL, Sub1_Lo, RHS_Lo, MinusOne, Zero,
1739 ISD::SETUGE);
1740 SDValue C3 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, C2, C1, ISD::SETEQ);
1742 // TODO: Here and below portions of the code can be enclosed into if/endif.
1743 // Currently control flow is unconditional and we have 4 selects after
1744 // potential endif to substitute PHIs.
1746 // if C3 != 0 ...
1747 SDValue Sub2_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Lo,
1748 RHS_Lo, Zero1);
1749 SDValue Sub2_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Mi,
1750 RHS_Hi, Sub1_Lo.getValue(1));
1751 SDValue Sub2_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1752 Zero, Sub2_Lo.getValue(1));
1753 SDValue Sub2 = DAG.getBitcast(VT,
1754 DAG.getBuildVector(MVT::v2i32, DL, {Sub2_Lo, Sub2_Hi}));
1756 SDValue Add3 = DAG.getNode(ISD::ADD, DL, VT, Mulhi3, One64);
1758 SDValue C4 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, MinusOne, Zero,
1759 ISD::SETUGE);
1760 SDValue C5 = DAG.getSelectCC(DL, Sub2_Lo, RHS_Lo, MinusOne, Zero,
1761 ISD::SETUGE);
1762 SDValue C6 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, C5, C4, ISD::SETEQ);
1764 // if (C6 != 0)
1765 SDValue Add4 = DAG.getNode(ISD::ADD, DL, VT, Add3, One64);
1767 SDValue Sub3_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Lo,
1768 RHS_Lo, Zero1);
1769 SDValue Sub3_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1770 RHS_Hi, Sub2_Lo.getValue(1));
1771 SDValue Sub3_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub3_Mi,
1772 Zero, Sub3_Lo.getValue(1));
1773 SDValue Sub3 = DAG.getBitcast(VT,
1774 DAG.getBuildVector(MVT::v2i32, DL, {Sub3_Lo, Sub3_Hi}));
1776 // endif C6
1777 // endif C3
1779 SDValue Sel1 = DAG.getSelectCC(DL, C6, Zero, Add4, Add3, ISD::SETNE);
1780 SDValue Div = DAG.getSelectCC(DL, C3, Zero, Sel1, Mulhi3, ISD::SETNE);
1782 SDValue Sel2 = DAG.getSelectCC(DL, C6, Zero, Sub3, Sub2, ISD::SETNE);
1783 SDValue Rem = DAG.getSelectCC(DL, C3, Zero, Sel2, Sub1, ISD::SETNE);
1785 Results.push_back(Div);
1786 Results.push_back(Rem);
1788 return;
1791 // r600 expandion.
1792 // Get Speculative values
1793 SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1794 SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1796 SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, Zero, REM_Part, LHS_Hi, ISD::SETEQ);
1797 SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, Zero});
1798 REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1800 SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, Zero, DIV_Part, Zero, ISD::SETEQ);
1801 SDValue DIV_Lo = Zero;
1803 const unsigned halfBitWidth = HalfVT.getSizeInBits();
1805 for (unsigned i = 0; i < halfBitWidth; ++i) {
1806 const unsigned bitPos = halfBitWidth - i - 1;
1807 SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1808 // Get value of high bit
1809 SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1810 HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, One);
1811 HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1813 // Shift
1814 REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1815 // Add LHS high bit
1816 REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1818 SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1819 SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, Zero, ISD::SETUGE);
1821 DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1823 // Update REM
1824 SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1825 REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1828 SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1829 DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1830 Results.push_back(DIV);
1831 Results.push_back(REM);
1834 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1835 SelectionDAG &DAG) const {
1836 SDLoc DL(Op);
1837 EVT VT = Op.getValueType();
1839 if (VT == MVT::i64) {
1840 SmallVector<SDValue, 2> Results;
1841 LowerUDIVREM64(Op, DAG, Results);
1842 return DAG.getMergeValues(Results, DL);
1845 if (VT == MVT::i32) {
1846 if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1847 return Res;
1850 SDValue Num = Op.getOperand(0);
1851 SDValue Den = Op.getOperand(1);
1853 // RCP = URECIP(Den) = 2^32 / Den + e
1854 // e is rounding error.
1855 SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1857 // RCP_LO = mul(RCP, Den) */
1858 SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1860 // RCP_HI = mulhu (RCP, Den) */
1861 SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1863 // NEG_RCP_LO = -RCP_LO
1864 SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1865 RCP_LO);
1867 // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1868 SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1869 NEG_RCP_LO, RCP_LO,
1870 ISD::SETEQ);
1871 // Calculate the rounding error from the URECIP instruction
1872 // E = mulhu(ABS_RCP_LO, RCP)
1873 SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1875 // RCP_A_E = RCP + E
1876 SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1878 // RCP_S_E = RCP - E
1879 SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1881 // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1882 SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1883 RCP_A_E, RCP_S_E,
1884 ISD::SETEQ);
1885 // Quotient = mulhu(Tmp0, Num)
1886 SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1888 // Num_S_Remainder = Quotient * Den
1889 SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1891 // Remainder = Num - Num_S_Remainder
1892 SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1894 // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1895 SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1896 DAG.getConstant(-1, DL, VT),
1897 DAG.getConstant(0, DL, VT),
1898 ISD::SETUGE);
1899 // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1900 SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1901 Num_S_Remainder,
1902 DAG.getConstant(-1, DL, VT),
1903 DAG.getConstant(0, DL, VT),
1904 ISD::SETUGE);
1905 // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1906 SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1907 Remainder_GE_Zero);
1909 // Calculate Division result:
1911 // Quotient_A_One = Quotient + 1
1912 SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1913 DAG.getConstant(1, DL, VT));
1915 // Quotient_S_One = Quotient - 1
1916 SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1917 DAG.getConstant(1, DL, VT));
1919 // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1920 SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1921 Quotient, Quotient_A_One, ISD::SETEQ);
1923 // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1924 Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1925 Quotient_S_One, Div, ISD::SETEQ);
1927 // Calculate Rem result:
1929 // Remainder_S_Den = Remainder - Den
1930 SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1932 // Remainder_A_Den = Remainder + Den
1933 SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1935 // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1936 SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1937 Remainder, Remainder_S_Den, ISD::SETEQ);
1939 // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1940 Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1941 Remainder_A_Den, Rem, ISD::SETEQ);
1942 SDValue Ops[2] = {
1943 Div,
1946 return DAG.getMergeValues(Ops, DL);
1949 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1950 SelectionDAG &DAG) const {
1951 SDLoc DL(Op);
1952 EVT VT = Op.getValueType();
1954 SDValue LHS = Op.getOperand(0);
1955 SDValue RHS = Op.getOperand(1);
1957 SDValue Zero = DAG.getConstant(0, DL, VT);
1958 SDValue NegOne = DAG.getConstant(-1, DL, VT);
1960 if (VT == MVT::i32) {
1961 if (SDValue Res = LowerDIVREM24(Op, DAG, true))
1962 return Res;
1965 if (VT == MVT::i64 &&
1966 DAG.ComputeNumSignBits(LHS) > 32 &&
1967 DAG.ComputeNumSignBits(RHS) > 32) {
1968 EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1970 //HiLo split
1971 SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1972 SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1973 SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1974 LHS_Lo, RHS_Lo);
1975 SDValue Res[2] = {
1976 DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1977 DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1979 return DAG.getMergeValues(Res, DL);
1982 SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1983 SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1984 SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1985 SDValue RSign = LHSign; // Remainder sign is the same as LHS
1987 LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1988 RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1990 LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1991 RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1993 SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1994 SDValue Rem = Div.getValue(1);
1996 Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1997 Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1999 Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
2000 Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
2002 SDValue Res[2] = {
2003 Div,
2006 return DAG.getMergeValues(Res, DL);
2009 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
2010 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
2011 SDLoc SL(Op);
2012 EVT VT = Op.getValueType();
2013 SDValue X = Op.getOperand(0);
2014 SDValue Y = Op.getOperand(1);
2016 // TODO: Should this propagate fast-math-flags?
2018 SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
2019 SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
2020 SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
2022 return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
2025 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
2026 SDLoc SL(Op);
2027 SDValue Src = Op.getOperand(0);
2029 // result = trunc(src)
2030 // if (src > 0.0 && src != result)
2031 // result += 1.0
2033 SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2035 const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2036 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
2038 EVT SetCCVT =
2039 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2041 SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
2042 SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2043 SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2045 SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
2046 // TODO: Should this propagate fast-math-flags?
2047 return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2050 static SDValue extractF64Exponent(SDValue Hi, const SDLoc &SL,
2051 SelectionDAG &DAG) {
2052 const unsigned FractBits = 52;
2053 const unsigned ExpBits = 11;
2055 SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
2057 DAG.getConstant(FractBits - 32, SL, MVT::i32),
2058 DAG.getConstant(ExpBits, SL, MVT::i32));
2059 SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
2060 DAG.getConstant(1023, SL, MVT::i32));
2062 return Exp;
2065 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
2066 SDLoc SL(Op);
2067 SDValue Src = Op.getOperand(0);
2069 assert(Op.getValueType() == MVT::f64);
2071 const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2072 const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2074 SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2076 // Extract the upper half, since this is where we will find the sign and
2077 // exponent.
2078 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
2080 SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2082 const unsigned FractBits = 52;
2084 // Extract the sign bit.
2085 const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
2086 SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
2088 // Extend back to 64-bits.
2089 SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
2090 SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
2092 SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
2093 const SDValue FractMask
2094 = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
2096 SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
2097 SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
2098 SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
2100 EVT SetCCVT =
2101 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
2103 const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
2105 SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2106 SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2108 SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
2109 SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
2111 return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
2114 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
2115 SDLoc SL(Op);
2116 SDValue Src = Op.getOperand(0);
2118 assert(Op.getValueType() == MVT::f64);
2120 APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
2121 SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
2122 SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
2124 // TODO: Should this propagate fast-math-flags?
2126 SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
2127 SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
2129 SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
2131 APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
2132 SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
2134 EVT SetCCVT =
2135 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2136 SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
2138 return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
2141 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
2142 // FNEARBYINT and FRINT are the same, except in their handling of FP
2143 // exceptions. Those aren't really meaningful for us, and OpenCL only has
2144 // rint, so just treat them as equivalent.
2145 return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
2148 // XXX - May require not supporting f32 denormals?
2150 // Don't handle v2f16. The extra instructions to scalarize and repack around the
2151 // compare and vselect end up producing worse code than scalarizing the whole
2152 // operation.
2153 SDValue AMDGPUTargetLowering::LowerFROUND32_16(SDValue Op, SelectionDAG &DAG) const {
2154 SDLoc SL(Op);
2155 SDValue X = Op.getOperand(0);
2156 EVT VT = Op.getValueType();
2158 SDValue T = DAG.getNode(ISD::FTRUNC, SL, VT, X);
2160 // TODO: Should this propagate fast-math-flags?
2162 SDValue Diff = DAG.getNode(ISD::FSUB, SL, VT, X, T);
2164 SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, VT, Diff);
2166 const SDValue Zero = DAG.getConstantFP(0.0, SL, VT);
2167 const SDValue One = DAG.getConstantFP(1.0, SL, VT);
2168 const SDValue Half = DAG.getConstantFP(0.5, SL, VT);
2170 SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, VT, One, X);
2172 EVT SetCCVT =
2173 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2175 SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
2177 SDValue Sel = DAG.getNode(ISD::SELECT, SL, VT, Cmp, SignOne, Zero);
2179 return DAG.getNode(ISD::FADD, SL, VT, T, Sel);
2182 SDValue AMDGPUTargetLowering::LowerFROUND64(SDValue Op, SelectionDAG &DAG) const {
2183 SDLoc SL(Op);
2184 SDValue X = Op.getOperand(0);
2186 SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
2188 const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2189 const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2190 const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
2191 const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
2192 EVT SetCCVT =
2193 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
2195 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2197 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
2199 SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2201 const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
2202 MVT::i64);
2204 SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
2205 SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
2206 DAG.getConstant(INT64_C(0x0008000000000000), SL,
2207 MVT::i64),
2208 Exp);
2210 SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
2211 SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
2212 DAG.getConstant(0, SL, MVT::i64), Tmp0,
2213 ISD::SETNE);
2215 SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
2216 D, DAG.getConstant(0, SL, MVT::i64));
2217 SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
2219 K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
2220 K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
2222 SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2223 SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2224 SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
2226 SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
2227 ExpEqNegOne,
2228 DAG.getConstantFP(1.0, SL, MVT::f64),
2229 DAG.getConstantFP(0.0, SL, MVT::f64));
2231 SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
2233 K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
2234 K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
2236 return K;
2239 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2240 EVT VT = Op.getValueType();
2242 if (VT == MVT::f32 || VT == MVT::f16)
2243 return LowerFROUND32_16(Op, DAG);
2245 if (VT == MVT::f64)
2246 return LowerFROUND64(Op, DAG);
2248 llvm_unreachable("unhandled type");
2251 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
2252 SDLoc SL(Op);
2253 SDValue Src = Op.getOperand(0);
2255 // result = trunc(src);
2256 // if (src < 0.0 && src != result)
2257 // result += -1.0.
2259 SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2261 const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2262 const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
2264 EVT SetCCVT =
2265 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2267 SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
2268 SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2269 SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2271 SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
2272 // TODO: Should this propagate fast-math-flags?
2273 return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2276 SDValue AMDGPUTargetLowering::LowerFLOG(SDValue Op, SelectionDAG &DAG,
2277 double Log2BaseInverted) const {
2278 EVT VT = Op.getValueType();
2280 SDLoc SL(Op);
2281 SDValue Operand = Op.getOperand(0);
2282 SDValue Log2Operand = DAG.getNode(ISD::FLOG2, SL, VT, Operand);
2283 SDValue Log2BaseInvertedOperand = DAG.getConstantFP(Log2BaseInverted, SL, VT);
2285 return DAG.getNode(ISD::FMUL, SL, VT, Log2Operand, Log2BaseInvertedOperand);
2288 // Return M_LOG2E of appropriate type
2289 static SDValue getLog2EVal(SelectionDAG &DAG, const SDLoc &SL, EVT VT) {
2290 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
2291 case MVT::f32:
2292 return DAG.getConstantFP(1.44269504088896340735992468100189214f, SL, VT);
2293 case MVT::f16:
2294 return DAG.getConstantFP(
2295 APFloat(APFloat::IEEEhalf(), "1.44269504088896340735992468100189214"),
2296 SL, VT);
2297 case MVT::f64:
2298 return DAG.getConstantFP(
2299 APFloat(APFloat::IEEEdouble(), "0x1.71547652b82fep+0"), SL, VT);
2300 default:
2301 llvm_unreachable("unsupported fp type");
2305 // exp2(M_LOG2E_F * f);
2306 SDValue AMDGPUTargetLowering::lowerFEXP(SDValue Op, SelectionDAG &DAG) const {
2307 EVT VT = Op.getValueType();
2308 SDLoc SL(Op);
2309 SDValue Src = Op.getOperand(0);
2311 const SDValue K = getLog2EVal(DAG, SL, VT);
2312 SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Src, K, Op->getFlags());
2313 return DAG.getNode(ISD::FEXP2, SL, VT, Mul, Op->getFlags());
2316 static bool isCtlzOpc(unsigned Opc) {
2317 return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2320 static bool isCttzOpc(unsigned Opc) {
2321 return Opc == ISD::CTTZ || Opc == ISD::CTTZ_ZERO_UNDEF;
2324 SDValue AMDGPUTargetLowering::LowerCTLZ_CTTZ(SDValue Op, SelectionDAG &DAG) const {
2325 SDLoc SL(Op);
2326 SDValue Src = Op.getOperand(0);
2327 bool ZeroUndef = Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
2328 Op.getOpcode() == ISD::CTLZ_ZERO_UNDEF;
2330 unsigned ISDOpc, NewOpc;
2331 if (isCtlzOpc(Op.getOpcode())) {
2332 ISDOpc = ISD::CTLZ_ZERO_UNDEF;
2333 NewOpc = AMDGPUISD::FFBH_U32;
2334 } else if (isCttzOpc(Op.getOpcode())) {
2335 ISDOpc = ISD::CTTZ_ZERO_UNDEF;
2336 NewOpc = AMDGPUISD::FFBL_B32;
2337 } else
2338 llvm_unreachable("Unexpected OPCode!!!");
2341 if (ZeroUndef && Src.getValueType() == MVT::i32)
2342 return DAG.getNode(NewOpc, SL, MVT::i32, Src);
2344 SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2346 const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2347 const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2349 SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
2350 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
2352 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2353 *DAG.getContext(), MVT::i32);
2355 SDValue HiOrLo = isCtlzOpc(Op.getOpcode()) ? Hi : Lo;
2356 SDValue Hi0orLo0 = DAG.getSetCC(SL, SetCCVT, HiOrLo, Zero, ISD::SETEQ);
2358 SDValue OprLo = DAG.getNode(ISDOpc, SL, MVT::i32, Lo);
2359 SDValue OprHi = DAG.getNode(ISDOpc, SL, MVT::i32, Hi);
2361 const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
2362 SDValue Add, NewOpr;
2363 if (isCtlzOpc(Op.getOpcode())) {
2364 Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprLo, Bits32);
2365 // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
2366 NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprHi);
2367 } else {
2368 Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprHi, Bits32);
2369 // cttz(x) = lo_32(x) == 0 ? cttz(hi_32(x)) + 32 : cttz(lo_32(x))
2370 NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprLo);
2373 if (!ZeroUndef) {
2374 // Test if the full 64-bit input is zero.
2376 // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
2377 // which we probably don't want.
2378 SDValue LoOrHi = isCtlzOpc(Op.getOpcode()) ? Lo : Hi;
2379 SDValue Lo0OrHi0 = DAG.getSetCC(SL, SetCCVT, LoOrHi, Zero, ISD::SETEQ);
2380 SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0OrHi0, Hi0orLo0);
2382 // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
2383 // with the same cycles, otherwise it is slower.
2384 // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
2385 // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
2387 const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
2389 // The instruction returns -1 for 0 input, but the defined intrinsic
2390 // behavior is to return the number of bits.
2391 NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32,
2392 SrcIsZero, Bits32, NewOpr);
2395 return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewOpr);
2398 SDValue AMDGPUTargetLowering::LowerINT_TO_FP32(SDValue Op, SelectionDAG &DAG,
2399 bool Signed) const {
2400 // Unsigned
2401 // cul2f(ulong u)
2403 // uint lz = clz(u);
2404 // uint e = (u != 0) ? 127U + 63U - lz : 0;
2405 // u = (u << lz) & 0x7fffffffffffffffUL;
2406 // ulong t = u & 0xffffffffffUL;
2407 // uint v = (e << 23) | (uint)(u >> 40);
2408 // uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
2409 // return as_float(v + r);
2411 // Signed
2412 // cl2f(long l)
2414 // long s = l >> 63;
2415 // float r = cul2f((l + s) ^ s);
2416 // return s ? -r : r;
2419 SDLoc SL(Op);
2420 SDValue Src = Op.getOperand(0);
2421 SDValue L = Src;
2423 SDValue S;
2424 if (Signed) {
2425 const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
2426 S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
2428 SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
2429 L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
2432 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2433 *DAG.getContext(), MVT::f32);
2436 SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
2437 SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
2438 SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
2439 LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
2441 SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
2442 SDValue E = DAG.getSelect(SL, MVT::i32,
2443 DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
2444 DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
2445 ZeroI32);
2447 SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
2448 DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
2449 DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
2451 SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
2452 DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
2454 SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
2455 U, DAG.getConstant(40, SL, MVT::i64));
2457 SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
2458 DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
2459 DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, UShl));
2461 SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
2462 SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
2463 SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
2465 SDValue One = DAG.getConstant(1, SL, MVT::i32);
2467 SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
2469 SDValue R = DAG.getSelect(SL, MVT::i32,
2470 RCmp,
2471 One,
2472 DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
2473 R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
2474 R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
2476 if (!Signed)
2477 return R;
2479 SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
2480 return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
2483 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
2484 bool Signed) const {
2485 SDLoc SL(Op);
2486 SDValue Src = Op.getOperand(0);
2488 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2490 SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2491 DAG.getConstant(0, SL, MVT::i32));
2492 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2493 DAG.getConstant(1, SL, MVT::i32));
2495 SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2496 SL, MVT::f64, Hi);
2498 SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2500 SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2501 DAG.getConstant(32, SL, MVT::i32));
2502 // TODO: Should this propagate fast-math-flags?
2503 return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2506 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
2507 SelectionDAG &DAG) const {
2508 assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2509 "operation should be legal");
2511 // TODO: Factor out code common with LowerSINT_TO_FP.
2513 EVT DestVT = Op.getValueType();
2514 if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2515 SDLoc DL(Op);
2516 SDValue Src = Op.getOperand(0);
2518 SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2519 SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2520 SDValue FPRound =
2521 DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2523 return FPRound;
2526 if (DestVT == MVT::f32)
2527 return LowerINT_TO_FP32(Op, DAG, false);
2529 assert(DestVT == MVT::f64);
2530 return LowerINT_TO_FP64(Op, DAG, false);
2533 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
2534 SelectionDAG &DAG) const {
2535 assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2536 "operation should be legal");
2538 // TODO: Factor out code common with LowerUINT_TO_FP.
2540 EVT DestVT = Op.getValueType();
2541 if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2542 SDLoc DL(Op);
2543 SDValue Src = Op.getOperand(0);
2545 SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2546 SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2547 SDValue FPRound =
2548 DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2550 return FPRound;
2553 if (DestVT == MVT::f32)
2554 return LowerINT_TO_FP32(Op, DAG, true);
2556 assert(DestVT == MVT::f64);
2557 return LowerINT_TO_FP64(Op, DAG, true);
2560 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2561 bool Signed) const {
2562 SDLoc SL(Op);
2564 SDValue Src = Op.getOperand(0);
2566 SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2568 SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2569 MVT::f64);
2570 SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2571 MVT::f64);
2572 // TODO: Should this propagate fast-math-flags?
2573 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2575 SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2578 SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2580 SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2581 MVT::i32, FloorMul);
2582 SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2584 SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2586 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2589 SDValue AMDGPUTargetLowering::LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) const {
2590 SDLoc DL(Op);
2591 SDValue N0 = Op.getOperand(0);
2593 // Convert to target node to get known bits
2594 if (N0.getValueType() == MVT::f32)
2595 return DAG.getNode(AMDGPUISD::FP_TO_FP16, DL, Op.getValueType(), N0);
2597 if (getTargetMachine().Options.UnsafeFPMath) {
2598 // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2599 return SDValue();
2602 assert(N0.getSimpleValueType() == MVT::f64);
2604 // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2605 const unsigned ExpMask = 0x7ff;
2606 const unsigned ExpBiasf64 = 1023;
2607 const unsigned ExpBiasf16 = 15;
2608 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2609 SDValue One = DAG.getConstant(1, DL, MVT::i32);
2610 SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2611 SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2612 DAG.getConstant(32, DL, MVT::i64));
2613 UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2614 U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2615 SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2616 DAG.getConstant(20, DL, MVT::i64));
2617 E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2618 DAG.getConstant(ExpMask, DL, MVT::i32));
2619 // Subtract the fp64 exponent bias (1023) to get the real exponent and
2620 // add the f16 bias (15) to get the biased exponent for the f16 format.
2621 E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2622 DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2624 SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2625 DAG.getConstant(8, DL, MVT::i32));
2626 M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2627 DAG.getConstant(0xffe, DL, MVT::i32));
2629 SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2630 DAG.getConstant(0x1ff, DL, MVT::i32));
2631 MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2633 SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2634 M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2636 // (M != 0 ? 0x0200 : 0) | 0x7c00;
2637 SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2638 DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2639 Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2641 // N = M | (E << 12);
2642 SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2643 DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2644 DAG.getConstant(12, DL, MVT::i32)));
2646 // B = clamp(1-E, 0, 13);
2647 SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2648 One, E);
2649 SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2650 B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2651 DAG.getConstant(13, DL, MVT::i32));
2653 SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2654 DAG.getConstant(0x1000, DL, MVT::i32));
2656 SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2657 SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2658 SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2659 D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2661 SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2662 SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2663 DAG.getConstant(0x7, DL, MVT::i32));
2664 V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2665 DAG.getConstant(2, DL, MVT::i32));
2666 SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2667 One, Zero, ISD::SETEQ);
2668 SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2669 One, Zero, ISD::SETGT);
2670 V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2671 V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2673 V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2674 DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2675 V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2676 I, V, ISD::SETEQ);
2678 // Extract the sign bit.
2679 SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2680 DAG.getConstant(16, DL, MVT::i32));
2681 Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2682 DAG.getConstant(0x8000, DL, MVT::i32));
2684 V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2685 return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2688 SDValue AMDGPUTargetLowering::LowerFP_TO_SINT(SDValue Op,
2689 SelectionDAG &DAG) const {
2690 SDValue Src = Op.getOperand(0);
2692 // TODO: Factor out code common with LowerFP_TO_UINT.
2694 EVT SrcVT = Src.getValueType();
2695 if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2696 SDLoc DL(Op);
2698 SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2699 SDValue FpToInt32 =
2700 DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2702 return FpToInt32;
2705 if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2706 return LowerFP64_TO_INT(Op, DAG, true);
2708 return SDValue();
2711 SDValue AMDGPUTargetLowering::LowerFP_TO_UINT(SDValue Op,
2712 SelectionDAG &DAG) const {
2713 SDValue Src = Op.getOperand(0);
2715 // TODO: Factor out code common with LowerFP_TO_SINT.
2717 EVT SrcVT = Src.getValueType();
2718 if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2719 SDLoc DL(Op);
2721 SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2722 SDValue FpToInt32 =
2723 DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2725 return FpToInt32;
2728 if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2729 return LowerFP64_TO_INT(Op, DAG, false);
2731 return SDValue();
2734 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2735 SelectionDAG &DAG) const {
2736 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2737 MVT VT = Op.getSimpleValueType();
2738 MVT ScalarVT = VT.getScalarType();
2740 assert(VT.isVector());
2742 SDValue Src = Op.getOperand(0);
2743 SDLoc DL(Op);
2745 // TODO: Don't scalarize on Evergreen?
2746 unsigned NElts = VT.getVectorNumElements();
2747 SmallVector<SDValue, 8> Args;
2748 DAG.ExtractVectorElements(Src, Args, 0, NElts);
2750 SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2751 for (unsigned I = 0; I < NElts; ++I)
2752 Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2754 return DAG.getBuildVector(VT, DL, Args);
2757 //===----------------------------------------------------------------------===//
2758 // Custom DAG optimizations
2759 //===----------------------------------------------------------------------===//
2761 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2762 return AMDGPUTargetLowering::numBitsUnsigned(Op, DAG) <= 24;
2765 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2766 EVT VT = Op.getValueType();
2767 return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2768 // as unsigned 24-bit values.
2769 AMDGPUTargetLowering::numBitsSigned(Op, DAG) < 24;
2772 static SDValue simplifyI24(SDNode *Node24,
2773 TargetLowering::DAGCombinerInfo &DCI) {
2774 SelectionDAG &DAG = DCI.DAG;
2775 bool IsIntrin = Node24->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
2777 SDValue LHS = IsIntrin ? Node24->getOperand(1) : Node24->getOperand(0);
2778 SDValue RHS = IsIntrin ? Node24->getOperand(2) : Node24->getOperand(1);
2779 unsigned NewOpcode = Node24->getOpcode();
2780 if (IsIntrin) {
2781 unsigned IID = cast<ConstantSDNode>(Node24->getOperand(0))->getZExtValue();
2782 NewOpcode = IID == Intrinsic::amdgcn_mul_i24 ?
2783 AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2786 APInt Demanded = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 24);
2788 // First try to simplify using GetDemandedBits which allows the operands to
2789 // have other uses, but will only perform simplifications that involve
2790 // bypassing some nodes for this user.
2791 SDValue DemandedLHS = DAG.GetDemandedBits(LHS, Demanded);
2792 SDValue DemandedRHS = DAG.GetDemandedBits(RHS, Demanded);
2793 if (DemandedLHS || DemandedRHS)
2794 return DAG.getNode(NewOpcode, SDLoc(Node24), Node24->getVTList(),
2795 DemandedLHS ? DemandedLHS : LHS,
2796 DemandedRHS ? DemandedRHS : RHS);
2798 // Now try SimplifyDemandedBits which can simplify the nodes used by our
2799 // operands if this node is the only user.
2800 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2801 if (TLI.SimplifyDemandedBits(LHS, Demanded, DCI))
2802 return SDValue(Node24, 0);
2803 if (TLI.SimplifyDemandedBits(RHS, Demanded, DCI))
2804 return SDValue(Node24, 0);
2806 return SDValue();
2809 template <typename IntTy>
2810 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0, uint32_t Offset,
2811 uint32_t Width, const SDLoc &DL) {
2812 if (Width + Offset < 32) {
2813 uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2814 IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2815 return DAG.getConstant(Result, DL, MVT::i32);
2818 return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2821 static bool hasVolatileUser(SDNode *Val) {
2822 for (SDNode *U : Val->uses()) {
2823 if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2824 if (M->isVolatile())
2825 return true;
2829 return false;
2832 bool AMDGPUTargetLowering::shouldCombineMemoryType(EVT VT) const {
2833 // i32 vectors are the canonical memory type.
2834 if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2835 return false;
2837 if (!VT.isByteSized())
2838 return false;
2840 unsigned Size = VT.getStoreSize();
2842 if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2843 return false;
2845 if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2846 return false;
2848 return true;
2851 // Find a load or store from corresponding pattern root.
2852 // Roots may be build_vector, bitconvert or their combinations.
2853 static MemSDNode* findMemSDNode(SDNode *N) {
2854 N = AMDGPUTargetLowering::stripBitcast(SDValue(N,0)).getNode();
2855 if (MemSDNode *MN = dyn_cast<MemSDNode>(N))
2856 return MN;
2857 assert(isa<BuildVectorSDNode>(N));
2858 for (SDValue V : N->op_values())
2859 if (MemSDNode *MN =
2860 dyn_cast<MemSDNode>(AMDGPUTargetLowering::stripBitcast(V)))
2861 return MN;
2862 llvm_unreachable("cannot find MemSDNode in the pattern!");
2865 bool AMDGPUTargetLowering::SelectFlatOffset(bool IsSigned,
2866 SelectionDAG &DAG,
2867 SDNode *N,
2868 SDValue Addr,
2869 SDValue &VAddr,
2870 SDValue &Offset,
2871 SDValue &SLC) const {
2872 const GCNSubtarget &ST =
2873 DAG.getMachineFunction().getSubtarget<GCNSubtarget>();
2874 int64_t OffsetVal = 0;
2876 if (ST.hasFlatInstOffsets() &&
2877 (!ST.hasFlatSegmentOffsetBug() ||
2878 findMemSDNode(N)->getAddressSpace() != AMDGPUAS::FLAT_ADDRESS) &&
2879 DAG.isBaseWithConstantOffset(Addr)) {
2880 SDValue N0 = Addr.getOperand(0);
2881 SDValue N1 = Addr.getOperand(1);
2882 int64_t COffsetVal = cast<ConstantSDNode>(N1)->getSExtValue();
2884 const SIInstrInfo *TII = ST.getInstrInfo();
2885 if (TII->isLegalFLATOffset(COffsetVal, findMemSDNode(N)->getAddressSpace(),
2886 IsSigned)) {
2887 Addr = N0;
2888 OffsetVal = COffsetVal;
2892 VAddr = Addr;
2893 Offset = DAG.getTargetConstant(OffsetVal, SDLoc(), MVT::i16);
2894 SLC = DAG.getTargetConstant(0, SDLoc(), MVT::i1);
2896 return true;
2899 // Replace load of an illegal type with a store of a bitcast to a friendlier
2900 // type.
2901 SDValue AMDGPUTargetLowering::performLoadCombine(SDNode *N,
2902 DAGCombinerInfo &DCI) const {
2903 if (!DCI.isBeforeLegalize())
2904 return SDValue();
2906 LoadSDNode *LN = cast<LoadSDNode>(N);
2907 if (LN->isVolatile() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2908 return SDValue();
2910 SDLoc SL(N);
2911 SelectionDAG &DAG = DCI.DAG;
2912 EVT VT = LN->getMemoryVT();
2914 unsigned Size = VT.getStoreSize();
2915 unsigned Align = LN->getAlignment();
2916 if (Align < Size && isTypeLegal(VT)) {
2917 bool IsFast;
2918 unsigned AS = LN->getAddressSpace();
2920 // Expand unaligned loads earlier than legalization. Due to visitation order
2921 // problems during legalization, the emitted instructions to pack and unpack
2922 // the bytes again are not eliminated in the case of an unaligned copy.
2923 if (!allowsMisalignedMemoryAccesses(
2924 VT, AS, Align, LN->getMemOperand()->getFlags(), &IsFast)) {
2925 if (VT.isVector())
2926 return scalarizeVectorLoad(LN, DAG);
2928 SDValue Ops[2];
2929 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2930 return DAG.getMergeValues(Ops, SDLoc(N));
2933 if (!IsFast)
2934 return SDValue();
2937 if (!shouldCombineMemoryType(VT))
2938 return SDValue();
2940 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2942 SDValue NewLoad
2943 = DAG.getLoad(NewVT, SL, LN->getChain(),
2944 LN->getBasePtr(), LN->getMemOperand());
2946 SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2947 DCI.CombineTo(N, BC, NewLoad.getValue(1));
2948 return SDValue(N, 0);
2951 // Replace store of an illegal type with a store of a bitcast to a friendlier
2952 // type.
2953 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2954 DAGCombinerInfo &DCI) const {
2955 if (!DCI.isBeforeLegalize())
2956 return SDValue();
2958 StoreSDNode *SN = cast<StoreSDNode>(N);
2959 if (SN->isVolatile() || !ISD::isNormalStore(SN))
2960 return SDValue();
2962 EVT VT = SN->getMemoryVT();
2963 unsigned Size = VT.getStoreSize();
2965 SDLoc SL(N);
2966 SelectionDAG &DAG = DCI.DAG;
2967 unsigned Align = SN->getAlignment();
2968 if (Align < Size && isTypeLegal(VT)) {
2969 bool IsFast;
2970 unsigned AS = SN->getAddressSpace();
2972 // Expand unaligned stores earlier than legalization. Due to visitation
2973 // order problems during legalization, the emitted instructions to pack and
2974 // unpack the bytes again are not eliminated in the case of an unaligned
2975 // copy.
2976 if (!allowsMisalignedMemoryAccesses(
2977 VT, AS, Align, SN->getMemOperand()->getFlags(), &IsFast)) {
2978 if (VT.isVector())
2979 return scalarizeVectorStore(SN, DAG);
2981 return expandUnalignedStore(SN, DAG);
2984 if (!IsFast)
2985 return SDValue();
2988 if (!shouldCombineMemoryType(VT))
2989 return SDValue();
2991 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2992 SDValue Val = SN->getValue();
2994 //DCI.AddToWorklist(Val.getNode());
2996 bool OtherUses = !Val.hasOneUse();
2997 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2998 if (OtherUses) {
2999 SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
3000 DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
3003 return DAG.getStore(SN->getChain(), SL, CastVal,
3004 SN->getBasePtr(), SN->getMemOperand());
3007 // FIXME: This should go in generic DAG combiner with an isTruncateFree check,
3008 // but isTruncateFree is inaccurate for i16 now because of SALU vs. VALU
3009 // issues.
3010 SDValue AMDGPUTargetLowering::performAssertSZExtCombine(SDNode *N,
3011 DAGCombinerInfo &DCI) const {
3012 SelectionDAG &DAG = DCI.DAG;
3013 SDValue N0 = N->getOperand(0);
3015 // (vt2 (assertzext (truncate vt0:x), vt1)) ->
3016 // (vt2 (truncate (assertzext vt0:x, vt1)))
3017 if (N0.getOpcode() == ISD::TRUNCATE) {
3018 SDValue N1 = N->getOperand(1);
3019 EVT ExtVT = cast<VTSDNode>(N1)->getVT();
3020 SDLoc SL(N);
3022 SDValue Src = N0.getOperand(0);
3023 EVT SrcVT = Src.getValueType();
3024 if (SrcVT.bitsGE(ExtVT)) {
3025 SDValue NewInReg = DAG.getNode(N->getOpcode(), SL, SrcVT, Src, N1);
3026 return DAG.getNode(ISD::TRUNCATE, SL, N->getValueType(0), NewInReg);
3030 return SDValue();
3033 SDValue AMDGPUTargetLowering::performIntrinsicWOChainCombine(
3034 SDNode *N, DAGCombinerInfo &DCI) const {
3035 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3036 switch (IID) {
3037 case Intrinsic::amdgcn_mul_i24:
3038 case Intrinsic::amdgcn_mul_u24:
3039 return simplifyI24(N, DCI);
3040 default:
3041 return SDValue();
3045 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
3046 /// binary operation \p Opc to it with the corresponding constant operands.
3047 SDValue AMDGPUTargetLowering::splitBinaryBitConstantOpImpl(
3048 DAGCombinerInfo &DCI, const SDLoc &SL,
3049 unsigned Opc, SDValue LHS,
3050 uint32_t ValLo, uint32_t ValHi) const {
3051 SelectionDAG &DAG = DCI.DAG;
3052 SDValue Lo, Hi;
3053 std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
3055 SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
3056 SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
3058 SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
3059 SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
3061 // Re-visit the ands. It's possible we eliminated one of them and it could
3062 // simplify the vector.
3063 DCI.AddToWorklist(Lo.getNode());
3064 DCI.AddToWorklist(Hi.getNode());
3066 SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
3067 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3070 SDValue AMDGPUTargetLowering::performShlCombine(SDNode *N,
3071 DAGCombinerInfo &DCI) const {
3072 EVT VT = N->getValueType(0);
3074 ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3075 if (!RHS)
3076 return SDValue();
3078 SDValue LHS = N->getOperand(0);
3079 unsigned RHSVal = RHS->getZExtValue();
3080 if (!RHSVal)
3081 return LHS;
3083 SDLoc SL(N);
3084 SelectionDAG &DAG = DCI.DAG;
3086 switch (LHS->getOpcode()) {
3087 default:
3088 break;
3089 case ISD::ZERO_EXTEND:
3090 case ISD::SIGN_EXTEND:
3091 case ISD::ANY_EXTEND: {
3092 SDValue X = LHS->getOperand(0);
3094 if (VT == MVT::i32 && RHSVal == 16 && X.getValueType() == MVT::i16 &&
3095 isOperationLegal(ISD::BUILD_VECTOR, MVT::v2i16)) {
3096 // Prefer build_vector as the canonical form if packed types are legal.
3097 // (shl ([asz]ext i16:x), 16 -> build_vector 0, x
3098 SDValue Vec = DAG.getBuildVector(MVT::v2i16, SL,
3099 { DAG.getConstant(0, SL, MVT::i16), LHS->getOperand(0) });
3100 return DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3103 // shl (ext x) => zext (shl x), if shift does not overflow int
3104 if (VT != MVT::i64)
3105 break;
3106 KnownBits Known = DAG.computeKnownBits(X);
3107 unsigned LZ = Known.countMinLeadingZeros();
3108 if (LZ < RHSVal)
3109 break;
3110 EVT XVT = X.getValueType();
3111 SDValue Shl = DAG.getNode(ISD::SHL, SL, XVT, X, SDValue(RHS, 0));
3112 return DAG.getZExtOrTrunc(Shl, SL, VT);
3116 if (VT != MVT::i64)
3117 return SDValue();
3119 // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
3121 // On some subtargets, 64-bit shift is a quarter rate instruction. In the
3122 // common case, splitting this into a move and a 32-bit shift is faster and
3123 // the same code size.
3124 if (RHSVal < 32)
3125 return SDValue();
3127 SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
3129 SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
3130 SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
3132 const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3134 SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
3135 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3138 SDValue AMDGPUTargetLowering::performSraCombine(SDNode *N,
3139 DAGCombinerInfo &DCI) const {
3140 if (N->getValueType(0) != MVT::i64)
3141 return SDValue();
3143 const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3144 if (!RHS)
3145 return SDValue();
3147 SelectionDAG &DAG = DCI.DAG;
3148 SDLoc SL(N);
3149 unsigned RHSVal = RHS->getZExtValue();
3151 // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
3152 if (RHSVal == 32) {
3153 SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3154 SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3155 DAG.getConstant(31, SL, MVT::i32));
3157 SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
3158 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3161 // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
3162 if (RHSVal == 63) {
3163 SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3164 SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3165 DAG.getConstant(31, SL, MVT::i32));
3166 SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
3167 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3170 return SDValue();
3173 SDValue AMDGPUTargetLowering::performSrlCombine(SDNode *N,
3174 DAGCombinerInfo &DCI) const {
3175 auto *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3176 if (!RHS)
3177 return SDValue();
3179 EVT VT = N->getValueType(0);
3180 SDValue LHS = N->getOperand(0);
3181 unsigned ShiftAmt = RHS->getZExtValue();
3182 SelectionDAG &DAG = DCI.DAG;
3183 SDLoc SL(N);
3185 // fold (srl (and x, c1 << c2), c2) -> (and (srl(x, c2), c1)
3186 // this improves the ability to match BFE patterns in isel.
3187 if (LHS.getOpcode() == ISD::AND) {
3188 if (auto *Mask = dyn_cast<ConstantSDNode>(LHS.getOperand(1))) {
3189 if (Mask->getAPIntValue().isShiftedMask() &&
3190 Mask->getAPIntValue().countTrailingZeros() == ShiftAmt) {
3191 return DAG.getNode(
3192 ISD::AND, SL, VT,
3193 DAG.getNode(ISD::SRL, SL, VT, LHS.getOperand(0), N->getOperand(1)),
3194 DAG.getNode(ISD::SRL, SL, VT, LHS.getOperand(1), N->getOperand(1)));
3199 if (VT != MVT::i64)
3200 return SDValue();
3202 if (ShiftAmt < 32)
3203 return SDValue();
3205 // srl i64:x, C for C >= 32
3206 // =>
3207 // build_pair (srl hi_32(x), C - 32), 0
3208 SDValue One = DAG.getConstant(1, SL, MVT::i32);
3209 SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3211 SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, LHS);
3212 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecOp, One);
3214 SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
3215 SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
3217 SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
3219 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
3222 SDValue AMDGPUTargetLowering::performTruncateCombine(
3223 SDNode *N, DAGCombinerInfo &DCI) const {
3224 SDLoc SL(N);
3225 SelectionDAG &DAG = DCI.DAG;
3226 EVT VT = N->getValueType(0);
3227 SDValue Src = N->getOperand(0);
3229 // vt1 (truncate (bitcast (build_vector vt0:x, ...))) -> vt1 (bitcast vt0:x)
3230 if (Src.getOpcode() == ISD::BITCAST && !VT.isVector()) {
3231 SDValue Vec = Src.getOperand(0);
3232 if (Vec.getOpcode() == ISD::BUILD_VECTOR) {
3233 SDValue Elt0 = Vec.getOperand(0);
3234 EVT EltVT = Elt0.getValueType();
3235 if (VT.getSizeInBits() <= EltVT.getSizeInBits()) {
3236 if (EltVT.isFloatingPoint()) {
3237 Elt0 = DAG.getNode(ISD::BITCAST, SL,
3238 EltVT.changeTypeToInteger(), Elt0);
3241 return DAG.getNode(ISD::TRUNCATE, SL, VT, Elt0);
3246 // Equivalent of above for accessing the high element of a vector as an
3247 // integer operation.
3248 // trunc (srl (bitcast (build_vector x, y))), 16 -> trunc (bitcast y)
3249 if (Src.getOpcode() == ISD::SRL && !VT.isVector()) {
3250 if (auto K = isConstOrConstSplat(Src.getOperand(1))) {
3251 if (2 * K->getZExtValue() == Src.getValueType().getScalarSizeInBits()) {
3252 SDValue BV = stripBitcast(Src.getOperand(0));
3253 if (BV.getOpcode() == ISD::BUILD_VECTOR &&
3254 BV.getValueType().getVectorNumElements() == 2) {
3255 SDValue SrcElt = BV.getOperand(1);
3256 EVT SrcEltVT = SrcElt.getValueType();
3257 if (SrcEltVT.isFloatingPoint()) {
3258 SrcElt = DAG.getNode(ISD::BITCAST, SL,
3259 SrcEltVT.changeTypeToInteger(), SrcElt);
3262 return DAG.getNode(ISD::TRUNCATE, SL, VT, SrcElt);
3268 // Partially shrink 64-bit shifts to 32-bit if reduced to 16-bit.
3270 // i16 (trunc (srl i64:x, K)), K <= 16 ->
3271 // i16 (trunc (srl (i32 (trunc x), K)))
3272 if (VT.getScalarSizeInBits() < 32) {
3273 EVT SrcVT = Src.getValueType();
3274 if (SrcVT.getScalarSizeInBits() > 32 &&
3275 (Src.getOpcode() == ISD::SRL ||
3276 Src.getOpcode() == ISD::SRA ||
3277 Src.getOpcode() == ISD::SHL)) {
3278 SDValue Amt = Src.getOperand(1);
3279 KnownBits Known = DAG.computeKnownBits(Amt);
3280 unsigned Size = VT.getScalarSizeInBits();
3281 if ((Known.isConstant() && Known.getConstant().ule(Size)) ||
3282 (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size))) {
3283 EVT MidVT = VT.isVector() ?
3284 EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3285 VT.getVectorNumElements()) : MVT::i32;
3287 EVT NewShiftVT = getShiftAmountTy(MidVT, DAG.getDataLayout());
3288 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MidVT,
3289 Src.getOperand(0));
3290 DCI.AddToWorklist(Trunc.getNode());
3292 if (Amt.getValueType() != NewShiftVT) {
3293 Amt = DAG.getZExtOrTrunc(Amt, SL, NewShiftVT);
3294 DCI.AddToWorklist(Amt.getNode());
3297 SDValue ShrunkShift = DAG.getNode(Src.getOpcode(), SL, MidVT,
3298 Trunc, Amt);
3299 return DAG.getNode(ISD::TRUNCATE, SL, VT, ShrunkShift);
3304 return SDValue();
3307 // We need to specifically handle i64 mul here to avoid unnecessary conversion
3308 // instructions. If we only match on the legalized i64 mul expansion,
3309 // SimplifyDemandedBits will be unable to remove them because there will be
3310 // multiple uses due to the separate mul + mulh[su].
3311 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
3312 SDValue N0, SDValue N1, unsigned Size, bool Signed) {
3313 if (Size <= 32) {
3314 unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3315 return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
3318 // Because we want to eliminate extension instructions before the
3319 // operation, we need to create a single user here (i.e. not the separate
3320 // mul_lo + mul_hi) so that SimplifyDemandedBits will deal with it.
3322 unsigned MulOpc = Signed ? AMDGPUISD::MUL_LOHI_I24 : AMDGPUISD::MUL_LOHI_U24;
3324 SDValue Mul = DAG.getNode(MulOpc, SL,
3325 DAG.getVTList(MVT::i32, MVT::i32), N0, N1);
3327 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64,
3328 Mul.getValue(0), Mul.getValue(1));
3331 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
3332 DAGCombinerInfo &DCI) const {
3333 EVT VT = N->getValueType(0);
3335 unsigned Size = VT.getSizeInBits();
3336 if (VT.isVector() || Size > 64)
3337 return SDValue();
3339 // There are i16 integer mul/mad.
3340 if (Subtarget->has16BitInsts() && VT.getScalarType().bitsLE(MVT::i16))
3341 return SDValue();
3343 SelectionDAG &DAG = DCI.DAG;
3344 SDLoc DL(N);
3346 SDValue N0 = N->getOperand(0);
3347 SDValue N1 = N->getOperand(1);
3349 // SimplifyDemandedBits has the annoying habit of turning useful zero_extends
3350 // in the source into any_extends if the result of the mul is truncated. Since
3351 // we can assume the high bits are whatever we want, use the underlying value
3352 // to avoid the unknown high bits from interfering.
3353 if (N0.getOpcode() == ISD::ANY_EXTEND)
3354 N0 = N0.getOperand(0);
3356 if (N1.getOpcode() == ISD::ANY_EXTEND)
3357 N1 = N1.getOperand(0);
3359 SDValue Mul;
3361 if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
3362 N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3363 N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3364 Mul = getMul24(DAG, DL, N0, N1, Size, false);
3365 } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
3366 N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3367 N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3368 Mul = getMul24(DAG, DL, N0, N1, Size, true);
3369 } else {
3370 return SDValue();
3373 // We need to use sext even for MUL_U24, because MUL_U24 is used
3374 // for signed multiply of 8 and 16-bit types.
3375 return DAG.getSExtOrTrunc(Mul, DL, VT);
3378 SDValue AMDGPUTargetLowering::performMulhsCombine(SDNode *N,
3379 DAGCombinerInfo &DCI) const {
3380 EVT VT = N->getValueType(0);
3382 if (!Subtarget->hasMulI24() || VT.isVector())
3383 return SDValue();
3385 SelectionDAG &DAG = DCI.DAG;
3386 SDLoc DL(N);
3388 SDValue N0 = N->getOperand(0);
3389 SDValue N1 = N->getOperand(1);
3391 if (!isI24(N0, DAG) || !isI24(N1, DAG))
3392 return SDValue();
3394 N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3395 N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3397 SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
3398 DCI.AddToWorklist(Mulhi.getNode());
3399 return DAG.getSExtOrTrunc(Mulhi, DL, VT);
3402 SDValue AMDGPUTargetLowering::performMulhuCombine(SDNode *N,
3403 DAGCombinerInfo &DCI) const {
3404 EVT VT = N->getValueType(0);
3406 if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
3407 return SDValue();
3409 SelectionDAG &DAG = DCI.DAG;
3410 SDLoc DL(N);
3412 SDValue N0 = N->getOperand(0);
3413 SDValue N1 = N->getOperand(1);
3415 if (!isU24(N0, DAG) || !isU24(N1, DAG))
3416 return SDValue();
3418 N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3419 N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3421 SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
3422 DCI.AddToWorklist(Mulhi.getNode());
3423 return DAG.getZExtOrTrunc(Mulhi, DL, VT);
3426 SDValue AMDGPUTargetLowering::performMulLoHi24Combine(
3427 SDNode *N, DAGCombinerInfo &DCI) const {
3428 SelectionDAG &DAG = DCI.DAG;
3430 // Simplify demanded bits before splitting into multiple users.
3431 if (SDValue V = simplifyI24(N, DCI))
3432 return V;
3434 SDValue N0 = N->getOperand(0);
3435 SDValue N1 = N->getOperand(1);
3437 bool Signed = (N->getOpcode() == AMDGPUISD::MUL_LOHI_I24);
3439 unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3440 unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
3442 SDLoc SL(N);
3444 SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
3445 SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
3446 return DAG.getMergeValues({ MulLo, MulHi }, SL);
3449 static bool isNegativeOne(SDValue Val) {
3450 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
3451 return C->isAllOnesValue();
3452 return false;
3455 SDValue AMDGPUTargetLowering::getFFBX_U32(SelectionDAG &DAG,
3456 SDValue Op,
3457 const SDLoc &DL,
3458 unsigned Opc) const {
3459 EVT VT = Op.getValueType();
3460 EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
3461 if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
3462 LegalVT != MVT::i16))
3463 return SDValue();
3465 if (VT != MVT::i32)
3466 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
3468 SDValue FFBX = DAG.getNode(Opc, DL, MVT::i32, Op);
3469 if (VT != MVT::i32)
3470 FFBX = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBX);
3472 return FFBX;
3475 // The native instructions return -1 on 0 input. Optimize out a select that
3476 // produces -1 on 0.
3478 // TODO: If zero is not undef, we could also do this if the output is compared
3479 // against the bitwidth.
3481 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
3482 SDValue AMDGPUTargetLowering::performCtlz_CttzCombine(const SDLoc &SL, SDValue Cond,
3483 SDValue LHS, SDValue RHS,
3484 DAGCombinerInfo &DCI) const {
3485 ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3486 if (!CmpRhs || !CmpRhs->isNullValue())
3487 return SDValue();
3489 SelectionDAG &DAG = DCI.DAG;
3490 ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
3491 SDValue CmpLHS = Cond.getOperand(0);
3493 unsigned Opc = isCttzOpc(RHS.getOpcode()) ? AMDGPUISD::FFBL_B32 :
3494 AMDGPUISD::FFBH_U32;
3496 // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
3497 // select (setcc x, 0, eq), -1, (cttz_zero_undef x) -> ffbl_u32 x
3498 if (CCOpcode == ISD::SETEQ &&
3499 (isCtlzOpc(RHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3500 RHS.getOperand(0) == CmpLHS &&
3501 isNegativeOne(LHS)) {
3502 return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3505 // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
3506 // select (setcc x, 0, ne), (cttz_zero_undef x), -1 -> ffbl_u32 x
3507 if (CCOpcode == ISD::SETNE &&
3508 (isCtlzOpc(LHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3509 LHS.getOperand(0) == CmpLHS &&
3510 isNegativeOne(RHS)) {
3511 return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3514 return SDValue();
3517 static SDValue distributeOpThroughSelect(TargetLowering::DAGCombinerInfo &DCI,
3518 unsigned Op,
3519 const SDLoc &SL,
3520 SDValue Cond,
3521 SDValue N1,
3522 SDValue N2) {
3523 SelectionDAG &DAG = DCI.DAG;
3524 EVT VT = N1.getValueType();
3526 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
3527 N1.getOperand(0), N2.getOperand(0));
3528 DCI.AddToWorklist(NewSelect.getNode());
3529 return DAG.getNode(Op, SL, VT, NewSelect);
3532 // Pull a free FP operation out of a select so it may fold into uses.
3534 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
3535 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
3537 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
3538 // select c, (fabs x), +k -> fabs (select c, x, k)
3539 static SDValue foldFreeOpFromSelect(TargetLowering::DAGCombinerInfo &DCI,
3540 SDValue N) {
3541 SelectionDAG &DAG = DCI.DAG;
3542 SDValue Cond = N.getOperand(0);
3543 SDValue LHS = N.getOperand(1);
3544 SDValue RHS = N.getOperand(2);
3546 EVT VT = N.getValueType();
3547 if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
3548 (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
3549 return distributeOpThroughSelect(DCI, LHS.getOpcode(),
3550 SDLoc(N), Cond, LHS, RHS);
3553 bool Inv = false;
3554 if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
3555 std::swap(LHS, RHS);
3556 Inv = true;
3559 // TODO: Support vector constants.
3560 ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
3561 if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
3562 SDLoc SL(N);
3563 // If one side is an fneg/fabs and the other is a constant, we can push the
3564 // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
3565 SDValue NewLHS = LHS.getOperand(0);
3566 SDValue NewRHS = RHS;
3568 // Careful: if the neg can be folded up, don't try to pull it back down.
3569 bool ShouldFoldNeg = true;
3571 if (NewLHS.hasOneUse()) {
3572 unsigned Opc = NewLHS.getOpcode();
3573 if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
3574 ShouldFoldNeg = false;
3575 if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
3576 ShouldFoldNeg = false;
3579 if (ShouldFoldNeg) {
3580 if (LHS.getOpcode() == ISD::FNEG)
3581 NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3582 else if (CRHS->isNegative())
3583 return SDValue();
3585 if (Inv)
3586 std::swap(NewLHS, NewRHS);
3588 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
3589 Cond, NewLHS, NewRHS);
3590 DCI.AddToWorklist(NewSelect.getNode());
3591 return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
3595 return SDValue();
3599 SDValue AMDGPUTargetLowering::performSelectCombine(SDNode *N,
3600 DAGCombinerInfo &DCI) const {
3601 if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
3602 return Folded;
3604 SDValue Cond = N->getOperand(0);
3605 if (Cond.getOpcode() != ISD::SETCC)
3606 return SDValue();
3608 EVT VT = N->getValueType(0);
3609 SDValue LHS = Cond.getOperand(0);
3610 SDValue RHS = Cond.getOperand(1);
3611 SDValue CC = Cond.getOperand(2);
3613 SDValue True = N->getOperand(1);
3614 SDValue False = N->getOperand(2);
3616 if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
3617 SelectionDAG &DAG = DCI.DAG;
3618 if (DAG.isConstantValueOfAnyType(True) &&
3619 !DAG.isConstantValueOfAnyType(False)) {
3620 // Swap cmp + select pair to move constant to false input.
3621 // This will allow using VOPC cndmasks more often.
3622 // select (setcc x, y), k, x -> select (setccinv x, y), x, k
3624 SDLoc SL(N);
3625 ISD::CondCode NewCC = getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3626 LHS.getValueType().isInteger());
3628 SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
3629 return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
3632 if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
3633 SDValue MinMax
3634 = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
3635 // Revisit this node so we can catch min3/max3/med3 patterns.
3636 //DCI.AddToWorklist(MinMax.getNode());
3637 return MinMax;
3641 // There's no reason to not do this if the condition has other uses.
3642 return performCtlz_CttzCombine(SDLoc(N), Cond, True, False, DCI);
3645 static bool isInv2Pi(const APFloat &APF) {
3646 static const APFloat KF16(APFloat::IEEEhalf(), APInt(16, 0x3118));
3647 static const APFloat KF32(APFloat::IEEEsingle(), APInt(32, 0x3e22f983));
3648 static const APFloat KF64(APFloat::IEEEdouble(), APInt(64, 0x3fc45f306dc9c882));
3650 return APF.bitwiseIsEqual(KF16) ||
3651 APF.bitwiseIsEqual(KF32) ||
3652 APF.bitwiseIsEqual(KF64);
3655 // 0 and 1.0 / (0.5 * pi) do not have inline immmediates, so there is an
3656 // additional cost to negate them.
3657 bool AMDGPUTargetLowering::isConstantCostlierToNegate(SDValue N) const {
3658 if (const ConstantFPSDNode *C = isConstOrConstSplatFP(N)) {
3659 if (C->isZero() && !C->isNegative())
3660 return true;
3662 if (Subtarget->hasInv2PiInlineImm() && isInv2Pi(C->getValueAPF()))
3663 return true;
3666 return false;
3669 static unsigned inverseMinMax(unsigned Opc) {
3670 switch (Opc) {
3671 case ISD::FMAXNUM:
3672 return ISD::FMINNUM;
3673 case ISD::FMINNUM:
3674 return ISD::FMAXNUM;
3675 case ISD::FMAXNUM_IEEE:
3676 return ISD::FMINNUM_IEEE;
3677 case ISD::FMINNUM_IEEE:
3678 return ISD::FMAXNUM_IEEE;
3679 case AMDGPUISD::FMAX_LEGACY:
3680 return AMDGPUISD::FMIN_LEGACY;
3681 case AMDGPUISD::FMIN_LEGACY:
3682 return AMDGPUISD::FMAX_LEGACY;
3683 default:
3684 llvm_unreachable("invalid min/max opcode");
3688 SDValue AMDGPUTargetLowering::performFNegCombine(SDNode *N,
3689 DAGCombinerInfo &DCI) const {
3690 SelectionDAG &DAG = DCI.DAG;
3691 SDValue N0 = N->getOperand(0);
3692 EVT VT = N->getValueType(0);
3694 unsigned Opc = N0.getOpcode();
3696 // If the input has multiple uses and we can either fold the negate down, or
3697 // the other uses cannot, give up. This both prevents unprofitable
3698 // transformations and infinite loops: we won't repeatedly try to fold around
3699 // a negate that has no 'good' form.
3700 if (N0.hasOneUse()) {
3701 // This may be able to fold into the source, but at a code size cost. Don't
3702 // fold if the fold into the user is free.
3703 if (allUsesHaveSourceMods(N, 0))
3704 return SDValue();
3705 } else {
3706 if (fnegFoldsIntoOp(Opc) &&
3707 (allUsesHaveSourceMods(N) || !allUsesHaveSourceMods(N0.getNode())))
3708 return SDValue();
3711 SDLoc SL(N);
3712 switch (Opc) {
3713 case ISD::FADD: {
3714 if (!mayIgnoreSignedZero(N0))
3715 return SDValue();
3717 // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
3718 SDValue LHS = N0.getOperand(0);
3719 SDValue RHS = N0.getOperand(1);
3721 if (LHS.getOpcode() != ISD::FNEG)
3722 LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3723 else
3724 LHS = LHS.getOperand(0);
3726 if (RHS.getOpcode() != ISD::FNEG)
3727 RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3728 else
3729 RHS = RHS.getOperand(0);
3731 SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
3732 if (Res.getOpcode() != ISD::FADD)
3733 return SDValue(); // Op got folded away.
3734 if (!N0.hasOneUse())
3735 DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3736 return Res;
3738 case ISD::FMUL:
3739 case AMDGPUISD::FMUL_LEGACY: {
3740 // (fneg (fmul x, y)) -> (fmul x, (fneg y))
3741 // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
3742 SDValue LHS = N0.getOperand(0);
3743 SDValue RHS = N0.getOperand(1);
3745 if (LHS.getOpcode() == ISD::FNEG)
3746 LHS = LHS.getOperand(0);
3747 else if (RHS.getOpcode() == ISD::FNEG)
3748 RHS = RHS.getOperand(0);
3749 else
3750 RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3752 SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
3753 if (Res.getOpcode() != Opc)
3754 return SDValue(); // Op got folded away.
3755 if (!N0.hasOneUse())
3756 DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3757 return Res;
3759 case ISD::FMA:
3760 case ISD::FMAD: {
3761 if (!mayIgnoreSignedZero(N0))
3762 return SDValue();
3764 // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
3765 SDValue LHS = N0.getOperand(0);
3766 SDValue MHS = N0.getOperand(1);
3767 SDValue RHS = N0.getOperand(2);
3769 if (LHS.getOpcode() == ISD::FNEG)
3770 LHS = LHS.getOperand(0);
3771 else if (MHS.getOpcode() == ISD::FNEG)
3772 MHS = MHS.getOperand(0);
3773 else
3774 MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
3776 if (RHS.getOpcode() != ISD::FNEG)
3777 RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3778 else
3779 RHS = RHS.getOperand(0);
3781 SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
3782 if (Res.getOpcode() != Opc)
3783 return SDValue(); // Op got folded away.
3784 if (!N0.hasOneUse())
3785 DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3786 return Res;
3788 case ISD::FMAXNUM:
3789 case ISD::FMINNUM:
3790 case ISD::FMAXNUM_IEEE:
3791 case ISD::FMINNUM_IEEE:
3792 case AMDGPUISD::FMAX_LEGACY:
3793 case AMDGPUISD::FMIN_LEGACY: {
3794 // fneg (fmaxnum x, y) -> fminnum (fneg x), (fneg y)
3795 // fneg (fminnum x, y) -> fmaxnum (fneg x), (fneg y)
3796 // fneg (fmax_legacy x, y) -> fmin_legacy (fneg x), (fneg y)
3797 // fneg (fmin_legacy x, y) -> fmax_legacy (fneg x), (fneg y)
3799 SDValue LHS = N0.getOperand(0);
3800 SDValue RHS = N0.getOperand(1);
3802 // 0 doesn't have a negated inline immediate.
3803 // TODO: This constant check should be generalized to other operations.
3804 if (isConstantCostlierToNegate(RHS))
3805 return SDValue();
3807 SDValue NegLHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3808 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3809 unsigned Opposite = inverseMinMax(Opc);
3811 SDValue Res = DAG.getNode(Opposite, SL, VT, NegLHS, NegRHS, N0->getFlags());
3812 if (Res.getOpcode() != Opposite)
3813 return SDValue(); // Op got folded away.
3814 if (!N0.hasOneUse())
3815 DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3816 return Res;
3818 case AMDGPUISD::FMED3: {
3819 SDValue Ops[3];
3820 for (unsigned I = 0; I < 3; ++I)
3821 Ops[I] = DAG.getNode(ISD::FNEG, SL, VT, N0->getOperand(I), N0->getFlags());
3823 SDValue Res = DAG.getNode(AMDGPUISD::FMED3, SL, VT, Ops, N0->getFlags());
3824 if (Res.getOpcode() != AMDGPUISD::FMED3)
3825 return SDValue(); // Op got folded away.
3826 if (!N0.hasOneUse())
3827 DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3828 return Res;
3830 case ISD::FP_EXTEND:
3831 case ISD::FTRUNC:
3832 case ISD::FRINT:
3833 case ISD::FNEARBYINT: // XXX - Should fround be handled?
3834 case ISD::FSIN:
3835 case ISD::FCANONICALIZE:
3836 case AMDGPUISD::RCP:
3837 case AMDGPUISD::RCP_LEGACY:
3838 case AMDGPUISD::RCP_IFLAG:
3839 case AMDGPUISD::SIN_HW: {
3840 SDValue CvtSrc = N0.getOperand(0);
3841 if (CvtSrc.getOpcode() == ISD::FNEG) {
3842 // (fneg (fp_extend (fneg x))) -> (fp_extend x)
3843 // (fneg (rcp (fneg x))) -> (rcp x)
3844 return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
3847 if (!N0.hasOneUse())
3848 return SDValue();
3850 // (fneg (fp_extend x)) -> (fp_extend (fneg x))
3851 // (fneg (rcp x)) -> (rcp (fneg x))
3852 SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3853 return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
3855 case ISD::FP_ROUND: {
3856 SDValue CvtSrc = N0.getOperand(0);
3858 if (CvtSrc.getOpcode() == ISD::FNEG) {
3859 // (fneg (fp_round (fneg x))) -> (fp_round x)
3860 return DAG.getNode(ISD::FP_ROUND, SL, VT,
3861 CvtSrc.getOperand(0), N0.getOperand(1));
3864 if (!N0.hasOneUse())
3865 return SDValue();
3867 // (fneg (fp_round x)) -> (fp_round (fneg x))
3868 SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3869 return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
3871 case ISD::FP16_TO_FP: {
3872 // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
3873 // f16, but legalization of f16 fneg ends up pulling it out of the source.
3874 // Put the fneg back as a legal source operation that can be matched later.
3875 SDLoc SL(N);
3877 SDValue Src = N0.getOperand(0);
3878 EVT SrcVT = Src.getValueType();
3880 // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
3881 SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
3882 DAG.getConstant(0x8000, SL, SrcVT));
3883 return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
3885 default:
3886 return SDValue();
3890 SDValue AMDGPUTargetLowering::performFAbsCombine(SDNode *N,
3891 DAGCombinerInfo &DCI) const {
3892 SelectionDAG &DAG = DCI.DAG;
3893 SDValue N0 = N->getOperand(0);
3895 if (!N0.hasOneUse())
3896 return SDValue();
3898 switch (N0.getOpcode()) {
3899 case ISD::FP16_TO_FP: {
3900 assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3901 SDLoc SL(N);
3902 SDValue Src = N0.getOperand(0);
3903 EVT SrcVT = Src.getValueType();
3905 // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3906 SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3907 DAG.getConstant(0x7fff, SL, SrcVT));
3908 return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3910 default:
3911 return SDValue();
3915 SDValue AMDGPUTargetLowering::performRcpCombine(SDNode *N,
3916 DAGCombinerInfo &DCI) const {
3917 const auto *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3918 if (!CFP)
3919 return SDValue();
3921 // XXX - Should this flush denormals?
3922 const APFloat &Val = CFP->getValueAPF();
3923 APFloat One(Val.getSemantics(), "1.0");
3924 return DCI.DAG.getConstantFP(One / Val, SDLoc(N), N->getValueType(0));
3927 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
3928 DAGCombinerInfo &DCI) const {
3929 SelectionDAG &DAG = DCI.DAG;
3930 SDLoc DL(N);
3932 switch(N->getOpcode()) {
3933 default:
3934 break;
3935 case ISD::BITCAST: {
3936 EVT DestVT = N->getValueType(0);
3938 // Push casts through vector builds. This helps avoid emitting a large
3939 // number of copies when materializing floating point vector constants.
3941 // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3942 // vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3943 if (DestVT.isVector()) {
3944 SDValue Src = N->getOperand(0);
3945 if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3946 EVT SrcVT = Src.getValueType();
3947 unsigned NElts = DestVT.getVectorNumElements();
3949 if (SrcVT.getVectorNumElements() == NElts) {
3950 EVT DestEltVT = DestVT.getVectorElementType();
3952 SmallVector<SDValue, 8> CastedElts;
3953 SDLoc SL(N);
3954 for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3955 SDValue Elt = Src.getOperand(I);
3956 CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3959 return DAG.getBuildVector(DestVT, SL, CastedElts);
3964 if (DestVT.getSizeInBits() != 64 && !DestVT.isVector())
3965 break;
3967 // Fold bitcasts of constants.
3969 // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3970 // TODO: Generalize and move to DAGCombiner
3971 SDValue Src = N->getOperand(0);
3972 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3973 if (Src.getValueType() == MVT::i64) {
3974 SDLoc SL(N);
3975 uint64_t CVal = C->getZExtValue();
3976 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3977 DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3978 DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3979 return DAG.getNode(ISD::BITCAST, SL, DestVT, BV);
3983 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3984 const APInt &Val = C->getValueAPF().bitcastToAPInt();
3985 SDLoc SL(N);
3986 uint64_t CVal = Val.getZExtValue();
3987 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3988 DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3989 DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3991 return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3994 break;
3996 case ISD::SHL: {
3997 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3998 break;
4000 return performShlCombine(N, DCI);
4002 case ISD::SRL: {
4003 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4004 break;
4006 return performSrlCombine(N, DCI);
4008 case ISD::SRA: {
4009 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4010 break;
4012 return performSraCombine(N, DCI);
4014 case ISD::TRUNCATE:
4015 return performTruncateCombine(N, DCI);
4016 case ISD::MUL:
4017 return performMulCombine(N, DCI);
4018 case ISD::MULHS:
4019 return performMulhsCombine(N, DCI);
4020 case ISD::MULHU:
4021 return performMulhuCombine(N, DCI);
4022 case AMDGPUISD::MUL_I24:
4023 case AMDGPUISD::MUL_U24:
4024 case AMDGPUISD::MULHI_I24:
4025 case AMDGPUISD::MULHI_U24: {
4026 if (SDValue V = simplifyI24(N, DCI))
4027 return V;
4028 return SDValue();
4030 case AMDGPUISD::MUL_LOHI_I24:
4031 case AMDGPUISD::MUL_LOHI_U24:
4032 return performMulLoHi24Combine(N, DCI);
4033 case ISD::SELECT:
4034 return performSelectCombine(N, DCI);
4035 case ISD::FNEG:
4036 return performFNegCombine(N, DCI);
4037 case ISD::FABS:
4038 return performFAbsCombine(N, DCI);
4039 case AMDGPUISD::BFE_I32:
4040 case AMDGPUISD::BFE_U32: {
4041 assert(!N->getValueType(0).isVector() &&
4042 "Vector handling of BFE not implemented");
4043 ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
4044 if (!Width)
4045 break;
4047 uint32_t WidthVal = Width->getZExtValue() & 0x1f;
4048 if (WidthVal == 0)
4049 return DAG.getConstant(0, DL, MVT::i32);
4051 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
4052 if (!Offset)
4053 break;
4055 SDValue BitsFrom = N->getOperand(0);
4056 uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
4058 bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
4060 if (OffsetVal == 0) {
4061 // This is already sign / zero extended, so try to fold away extra BFEs.
4062 unsigned SignBits = Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
4064 unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
4065 if (OpSignBits >= SignBits)
4066 return BitsFrom;
4068 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
4069 if (Signed) {
4070 // This is a sign_extend_inreg. Replace it to take advantage of existing
4071 // DAG Combines. If not eliminated, we will match back to BFE during
4072 // selection.
4074 // TODO: The sext_inreg of extended types ends, although we can could
4075 // handle them in a single BFE.
4076 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
4077 DAG.getValueType(SmallVT));
4080 return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
4083 if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
4084 if (Signed) {
4085 return constantFoldBFE<int32_t>(DAG,
4086 CVal->getSExtValue(),
4087 OffsetVal,
4088 WidthVal,
4089 DL);
4092 return constantFoldBFE<uint32_t>(DAG,
4093 CVal->getZExtValue(),
4094 OffsetVal,
4095 WidthVal,
4096 DL);
4099 if ((OffsetVal + WidthVal) >= 32 &&
4100 !(Subtarget->hasSDWA() && OffsetVal == 16 && WidthVal == 16)) {
4101 SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
4102 return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
4103 BitsFrom, ShiftVal);
4106 if (BitsFrom.hasOneUse()) {
4107 APInt Demanded = APInt::getBitsSet(32,
4108 OffsetVal,
4109 OffsetVal + WidthVal);
4111 KnownBits Known;
4112 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4113 !DCI.isBeforeLegalizeOps());
4114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4115 if (TLI.ShrinkDemandedConstant(BitsFrom, Demanded, TLO) ||
4116 TLI.SimplifyDemandedBits(BitsFrom, Demanded, Known, TLO)) {
4117 DCI.CommitTargetLoweringOpt(TLO);
4121 break;
4123 case ISD::LOAD:
4124 return performLoadCombine(N, DCI);
4125 case ISD::STORE:
4126 return performStoreCombine(N, DCI);
4127 case AMDGPUISD::RCP:
4128 case AMDGPUISD::RCP_IFLAG:
4129 return performRcpCombine(N, DCI);
4130 case ISD::AssertZext:
4131 case ISD::AssertSext:
4132 return performAssertSZExtCombine(N, DCI);
4133 case ISD::INTRINSIC_WO_CHAIN:
4134 return performIntrinsicWOChainCombine(N, DCI);
4136 return SDValue();
4139 //===----------------------------------------------------------------------===//
4140 // Helper functions
4141 //===----------------------------------------------------------------------===//
4143 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4144 const TargetRegisterClass *RC,
4145 unsigned Reg, EVT VT,
4146 const SDLoc &SL,
4147 bool RawReg) const {
4148 MachineFunction &MF = DAG.getMachineFunction();
4149 MachineRegisterInfo &MRI = MF.getRegInfo();
4150 unsigned VReg;
4152 if (!MRI.isLiveIn(Reg)) {
4153 VReg = MRI.createVirtualRegister(RC);
4154 MRI.addLiveIn(Reg, VReg);
4155 } else {
4156 VReg = MRI.getLiveInVirtReg(Reg);
4159 if (RawReg)
4160 return DAG.getRegister(VReg, VT);
4162 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, VReg, VT);
4165 // This may be called multiple times, and nothing prevents creating multiple
4166 // objects at the same offset. See if we already defined this object.
4167 static int getOrCreateFixedStackObject(MachineFrameInfo &MFI, unsigned Size,
4168 int64_t Offset) {
4169 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
4170 if (MFI.getObjectOffset(I) == Offset) {
4171 assert(MFI.getObjectSize(I) == Size);
4172 return I;
4176 return MFI.CreateFixedObject(Size, Offset, true);
4179 SDValue AMDGPUTargetLowering::loadStackInputValue(SelectionDAG &DAG,
4180 EVT VT,
4181 const SDLoc &SL,
4182 int64_t Offset) const {
4183 MachineFunction &MF = DAG.getMachineFunction();
4184 MachineFrameInfo &MFI = MF.getFrameInfo();
4185 int FI = getOrCreateFixedStackObject(MFI, VT.getStoreSize(), Offset);
4187 auto SrcPtrInfo = MachinePointerInfo::getStack(MF, Offset);
4188 SDValue Ptr = DAG.getFrameIndex(FI, MVT::i32);
4190 return DAG.getLoad(VT, SL, DAG.getEntryNode(), Ptr, SrcPtrInfo, 4,
4191 MachineMemOperand::MODereferenceable |
4192 MachineMemOperand::MOInvariant);
4195 SDValue AMDGPUTargetLowering::storeStackInputValue(SelectionDAG &DAG,
4196 const SDLoc &SL,
4197 SDValue Chain,
4198 SDValue ArgVal,
4199 int64_t Offset) const {
4200 MachineFunction &MF = DAG.getMachineFunction();
4201 MachinePointerInfo DstInfo = MachinePointerInfo::getStack(MF, Offset);
4203 SDValue Ptr = DAG.getConstant(Offset, SL, MVT::i32);
4204 SDValue Store = DAG.getStore(Chain, SL, ArgVal, Ptr, DstInfo, 4,
4205 MachineMemOperand::MODereferenceable);
4206 return Store;
4209 SDValue AMDGPUTargetLowering::loadInputValue(SelectionDAG &DAG,
4210 const TargetRegisterClass *RC,
4211 EVT VT, const SDLoc &SL,
4212 const ArgDescriptor &Arg) const {
4213 assert(Arg && "Attempting to load missing argument");
4215 SDValue V = Arg.isRegister() ?
4216 CreateLiveInRegister(DAG, RC, Arg.getRegister(), VT, SL) :
4217 loadStackInputValue(DAG, VT, SL, Arg.getStackOffset());
4219 if (!Arg.isMasked())
4220 return V;
4222 unsigned Mask = Arg.getMask();
4223 unsigned Shift = countTrailingZeros<unsigned>(Mask);
4224 V = DAG.getNode(ISD::SRL, SL, VT, V,
4225 DAG.getShiftAmountConstant(Shift, VT, SL));
4226 return DAG.getNode(ISD::AND, SL, VT, V,
4227 DAG.getConstant(Mask >> Shift, SL, VT));
4230 uint32_t AMDGPUTargetLowering::getImplicitParameterOffset(
4231 const MachineFunction &MF, const ImplicitParameter Param) const {
4232 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
4233 const AMDGPUSubtarget &ST =
4234 AMDGPUSubtarget::get(getTargetMachine(), MF.getFunction());
4235 unsigned ExplicitArgOffset = ST.getExplicitKernelArgOffset(MF.getFunction());
4236 unsigned Alignment = ST.getAlignmentForImplicitArgPtr();
4237 uint64_t ArgOffset = alignTo(MFI->getExplicitKernArgSize(), Alignment) +
4238 ExplicitArgOffset;
4239 switch (Param) {
4240 case GRID_DIM:
4241 return ArgOffset;
4242 case GRID_OFFSET:
4243 return ArgOffset + 4;
4245 llvm_unreachable("unexpected implicit parameter type");
4248 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
4250 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
4251 switch ((AMDGPUISD::NodeType)Opcode) {
4252 case AMDGPUISD::FIRST_NUMBER: break;
4253 // AMDIL DAG nodes
4254 NODE_NAME_CASE(UMUL);
4255 NODE_NAME_CASE(BRANCH_COND);
4257 // AMDGPU DAG nodes
4258 NODE_NAME_CASE(IF)
4259 NODE_NAME_CASE(ELSE)
4260 NODE_NAME_CASE(LOOP)
4261 NODE_NAME_CASE(CALL)
4262 NODE_NAME_CASE(TC_RETURN)
4263 NODE_NAME_CASE(TRAP)
4264 NODE_NAME_CASE(RET_FLAG)
4265 NODE_NAME_CASE(RETURN_TO_EPILOG)
4266 NODE_NAME_CASE(ENDPGM)
4267 NODE_NAME_CASE(DWORDADDR)
4268 NODE_NAME_CASE(FRACT)
4269 NODE_NAME_CASE(SETCC)
4270 NODE_NAME_CASE(SETREG)
4271 NODE_NAME_CASE(DENORM_MODE)
4272 NODE_NAME_CASE(FMA_W_CHAIN)
4273 NODE_NAME_CASE(FMUL_W_CHAIN)
4274 NODE_NAME_CASE(CLAMP)
4275 NODE_NAME_CASE(COS_HW)
4276 NODE_NAME_CASE(SIN_HW)
4277 NODE_NAME_CASE(FMAX_LEGACY)
4278 NODE_NAME_CASE(FMIN_LEGACY)
4279 NODE_NAME_CASE(FMAX3)
4280 NODE_NAME_CASE(SMAX3)
4281 NODE_NAME_CASE(UMAX3)
4282 NODE_NAME_CASE(FMIN3)
4283 NODE_NAME_CASE(SMIN3)
4284 NODE_NAME_CASE(UMIN3)
4285 NODE_NAME_CASE(FMED3)
4286 NODE_NAME_CASE(SMED3)
4287 NODE_NAME_CASE(UMED3)
4288 NODE_NAME_CASE(FDOT2)
4289 NODE_NAME_CASE(URECIP)
4290 NODE_NAME_CASE(DIV_SCALE)
4291 NODE_NAME_CASE(DIV_FMAS)
4292 NODE_NAME_CASE(DIV_FIXUP)
4293 NODE_NAME_CASE(FMAD_FTZ)
4294 NODE_NAME_CASE(TRIG_PREOP)
4295 NODE_NAME_CASE(RCP)
4296 NODE_NAME_CASE(RSQ)
4297 NODE_NAME_CASE(RCP_LEGACY)
4298 NODE_NAME_CASE(RSQ_LEGACY)
4299 NODE_NAME_CASE(RCP_IFLAG)
4300 NODE_NAME_CASE(FMUL_LEGACY)
4301 NODE_NAME_CASE(RSQ_CLAMP)
4302 NODE_NAME_CASE(LDEXP)
4303 NODE_NAME_CASE(FP_CLASS)
4304 NODE_NAME_CASE(DOT4)
4305 NODE_NAME_CASE(CARRY)
4306 NODE_NAME_CASE(BORROW)
4307 NODE_NAME_CASE(BFE_U32)
4308 NODE_NAME_CASE(BFE_I32)
4309 NODE_NAME_CASE(BFI)
4310 NODE_NAME_CASE(BFM)
4311 NODE_NAME_CASE(FFBH_U32)
4312 NODE_NAME_CASE(FFBH_I32)
4313 NODE_NAME_CASE(FFBL_B32)
4314 NODE_NAME_CASE(MUL_U24)
4315 NODE_NAME_CASE(MUL_I24)
4316 NODE_NAME_CASE(MULHI_U24)
4317 NODE_NAME_CASE(MULHI_I24)
4318 NODE_NAME_CASE(MUL_LOHI_U24)
4319 NODE_NAME_CASE(MUL_LOHI_I24)
4320 NODE_NAME_CASE(MAD_U24)
4321 NODE_NAME_CASE(MAD_I24)
4322 NODE_NAME_CASE(MAD_I64_I32)
4323 NODE_NAME_CASE(MAD_U64_U32)
4324 NODE_NAME_CASE(PERM)
4325 NODE_NAME_CASE(TEXTURE_FETCH)
4326 NODE_NAME_CASE(EXPORT)
4327 NODE_NAME_CASE(EXPORT_DONE)
4328 NODE_NAME_CASE(R600_EXPORT)
4329 NODE_NAME_CASE(CONST_ADDRESS)
4330 NODE_NAME_CASE(REGISTER_LOAD)
4331 NODE_NAME_CASE(REGISTER_STORE)
4332 NODE_NAME_CASE(SAMPLE)
4333 NODE_NAME_CASE(SAMPLEB)
4334 NODE_NAME_CASE(SAMPLED)
4335 NODE_NAME_CASE(SAMPLEL)
4336 NODE_NAME_CASE(CVT_F32_UBYTE0)
4337 NODE_NAME_CASE(CVT_F32_UBYTE1)
4338 NODE_NAME_CASE(CVT_F32_UBYTE2)
4339 NODE_NAME_CASE(CVT_F32_UBYTE3)
4340 NODE_NAME_CASE(CVT_PKRTZ_F16_F32)
4341 NODE_NAME_CASE(CVT_PKNORM_I16_F32)
4342 NODE_NAME_CASE(CVT_PKNORM_U16_F32)
4343 NODE_NAME_CASE(CVT_PK_I16_I32)
4344 NODE_NAME_CASE(CVT_PK_U16_U32)
4345 NODE_NAME_CASE(FP_TO_FP16)
4346 NODE_NAME_CASE(FP16_ZEXT)
4347 NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
4348 NODE_NAME_CASE(CONST_DATA_PTR)
4349 NODE_NAME_CASE(PC_ADD_REL_OFFSET)
4350 NODE_NAME_CASE(LDS)
4351 NODE_NAME_CASE(KILL)
4352 NODE_NAME_CASE(DUMMY_CHAIN)
4353 case AMDGPUISD::FIRST_MEM_OPCODE_NUMBER: break;
4354 NODE_NAME_CASE(INTERP_MOV)
4355 NODE_NAME_CASE(INTERP_P1)
4356 NODE_NAME_CASE(INTERP_P2)
4357 NODE_NAME_CASE(INTERP_P1LL_F16)
4358 NODE_NAME_CASE(INTERP_P1LV_F16)
4359 NODE_NAME_CASE(INTERP_P2_F16)
4360 NODE_NAME_CASE(LOAD_D16_HI)
4361 NODE_NAME_CASE(LOAD_D16_LO)
4362 NODE_NAME_CASE(LOAD_D16_HI_I8)
4363 NODE_NAME_CASE(LOAD_D16_HI_U8)
4364 NODE_NAME_CASE(LOAD_D16_LO_I8)
4365 NODE_NAME_CASE(LOAD_D16_LO_U8)
4366 NODE_NAME_CASE(STORE_MSKOR)
4367 NODE_NAME_CASE(LOAD_CONSTANT)
4368 NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
4369 NODE_NAME_CASE(TBUFFER_STORE_FORMAT_D16)
4370 NODE_NAME_CASE(TBUFFER_LOAD_FORMAT)
4371 NODE_NAME_CASE(TBUFFER_LOAD_FORMAT_D16)
4372 NODE_NAME_CASE(DS_ORDERED_COUNT)
4373 NODE_NAME_CASE(ATOMIC_CMP_SWAP)
4374 NODE_NAME_CASE(ATOMIC_INC)
4375 NODE_NAME_CASE(ATOMIC_DEC)
4376 NODE_NAME_CASE(ATOMIC_LOAD_FMIN)
4377 NODE_NAME_CASE(ATOMIC_LOAD_FMAX)
4378 NODE_NAME_CASE(BUFFER_LOAD)
4379 NODE_NAME_CASE(BUFFER_LOAD_UBYTE)
4380 NODE_NAME_CASE(BUFFER_LOAD_USHORT)
4381 NODE_NAME_CASE(BUFFER_LOAD_BYTE)
4382 NODE_NAME_CASE(BUFFER_LOAD_SHORT)
4383 NODE_NAME_CASE(BUFFER_LOAD_FORMAT)
4384 NODE_NAME_CASE(BUFFER_LOAD_FORMAT_D16)
4385 NODE_NAME_CASE(SBUFFER_LOAD)
4386 NODE_NAME_CASE(BUFFER_STORE)
4387 NODE_NAME_CASE(BUFFER_STORE_BYTE)
4388 NODE_NAME_CASE(BUFFER_STORE_SHORT)
4389 NODE_NAME_CASE(BUFFER_STORE_FORMAT)
4390 NODE_NAME_CASE(BUFFER_STORE_FORMAT_D16)
4391 NODE_NAME_CASE(BUFFER_ATOMIC_SWAP)
4392 NODE_NAME_CASE(BUFFER_ATOMIC_ADD)
4393 NODE_NAME_CASE(BUFFER_ATOMIC_SUB)
4394 NODE_NAME_CASE(BUFFER_ATOMIC_SMIN)
4395 NODE_NAME_CASE(BUFFER_ATOMIC_UMIN)
4396 NODE_NAME_CASE(BUFFER_ATOMIC_SMAX)
4397 NODE_NAME_CASE(BUFFER_ATOMIC_UMAX)
4398 NODE_NAME_CASE(BUFFER_ATOMIC_AND)
4399 NODE_NAME_CASE(BUFFER_ATOMIC_OR)
4400 NODE_NAME_CASE(BUFFER_ATOMIC_XOR)
4401 NODE_NAME_CASE(BUFFER_ATOMIC_INC)
4402 NODE_NAME_CASE(BUFFER_ATOMIC_DEC)
4403 NODE_NAME_CASE(BUFFER_ATOMIC_CMPSWAP)
4404 NODE_NAME_CASE(BUFFER_ATOMIC_FADD)
4405 NODE_NAME_CASE(BUFFER_ATOMIC_PK_FADD)
4406 NODE_NAME_CASE(ATOMIC_FADD)
4407 NODE_NAME_CASE(ATOMIC_PK_FADD)
4409 case AMDGPUISD::LAST_AMDGPU_ISD_NUMBER: break;
4411 return nullptr;
4414 SDValue AMDGPUTargetLowering::getSqrtEstimate(SDValue Operand,
4415 SelectionDAG &DAG, int Enabled,
4416 int &RefinementSteps,
4417 bool &UseOneConstNR,
4418 bool Reciprocal) const {
4419 EVT VT = Operand.getValueType();
4421 if (VT == MVT::f32) {
4422 RefinementSteps = 0;
4423 return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
4426 // TODO: There is also f64 rsq instruction, but the documentation is less
4427 // clear on its precision.
4429 return SDValue();
4432 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
4433 SelectionDAG &DAG, int Enabled,
4434 int &RefinementSteps) const {
4435 EVT VT = Operand.getValueType();
4437 if (VT == MVT::f32) {
4438 // Reciprocal, < 1 ulp error.
4440 // This reciprocal approximation converges to < 0.5 ulp error with one
4441 // newton rhapson performed with two fused multiple adds (FMAs).
4443 RefinementSteps = 0;
4444 return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
4447 // TODO: There is also f64 rcp instruction, but the documentation is less
4448 // clear on its precision.
4450 return SDValue();
4453 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
4454 const SDValue Op, KnownBits &Known,
4455 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
4457 Known.resetAll(); // Don't know anything.
4459 unsigned Opc = Op.getOpcode();
4461 switch (Opc) {
4462 default:
4463 break;
4464 case AMDGPUISD::CARRY:
4465 case AMDGPUISD::BORROW: {
4466 Known.Zero = APInt::getHighBitsSet(32, 31);
4467 break;
4470 case AMDGPUISD::BFE_I32:
4471 case AMDGPUISD::BFE_U32: {
4472 ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4473 if (!CWidth)
4474 return;
4476 uint32_t Width = CWidth->getZExtValue() & 0x1f;
4478 if (Opc == AMDGPUISD::BFE_U32)
4479 Known.Zero = APInt::getHighBitsSet(32, 32 - Width);
4481 break;
4483 case AMDGPUISD::FP_TO_FP16:
4484 case AMDGPUISD::FP16_ZEXT: {
4485 unsigned BitWidth = Known.getBitWidth();
4487 // High bits are zero.
4488 Known.Zero = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
4489 break;
4491 case AMDGPUISD::MUL_U24:
4492 case AMDGPUISD::MUL_I24: {
4493 KnownBits LHSKnown = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
4494 KnownBits RHSKnown = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
4495 unsigned TrailZ = LHSKnown.countMinTrailingZeros() +
4496 RHSKnown.countMinTrailingZeros();
4497 Known.Zero.setLowBits(std::min(TrailZ, 32u));
4499 // Truncate to 24 bits.
4500 LHSKnown = LHSKnown.trunc(24);
4501 RHSKnown = RHSKnown.trunc(24);
4503 bool Negative = false;
4504 if (Opc == AMDGPUISD::MUL_I24) {
4505 unsigned LHSValBits = 24 - LHSKnown.countMinSignBits();
4506 unsigned RHSValBits = 24 - RHSKnown.countMinSignBits();
4507 unsigned MaxValBits = std::min(LHSValBits + RHSValBits, 32u);
4508 if (MaxValBits >= 32)
4509 break;
4510 bool LHSNegative = LHSKnown.isNegative();
4511 bool LHSPositive = LHSKnown.isNonNegative();
4512 bool RHSNegative = RHSKnown.isNegative();
4513 bool RHSPositive = RHSKnown.isNonNegative();
4514 if ((!LHSNegative && !LHSPositive) || (!RHSNegative && !RHSPositive))
4515 break;
4516 Negative = (LHSNegative && RHSPositive) || (LHSPositive && RHSNegative);
4517 if (Negative)
4518 Known.One.setHighBits(32 - MaxValBits);
4519 else
4520 Known.Zero.setHighBits(32 - MaxValBits);
4521 } else {
4522 unsigned LHSValBits = 24 - LHSKnown.countMinLeadingZeros();
4523 unsigned RHSValBits = 24 - RHSKnown.countMinLeadingZeros();
4524 unsigned MaxValBits = std::min(LHSValBits + RHSValBits, 32u);
4525 if (MaxValBits >= 32)
4526 break;
4527 Known.Zero.setHighBits(32 - MaxValBits);
4529 break;
4531 case AMDGPUISD::PERM: {
4532 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4533 if (!CMask)
4534 return;
4536 KnownBits LHSKnown = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
4537 KnownBits RHSKnown = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
4538 unsigned Sel = CMask->getZExtValue();
4540 for (unsigned I = 0; I < 32; I += 8) {
4541 unsigned SelBits = Sel & 0xff;
4542 if (SelBits < 4) {
4543 SelBits *= 8;
4544 Known.One |= ((RHSKnown.One.getZExtValue() >> SelBits) & 0xff) << I;
4545 Known.Zero |= ((RHSKnown.Zero.getZExtValue() >> SelBits) & 0xff) << I;
4546 } else if (SelBits < 7) {
4547 SelBits = (SelBits & 3) * 8;
4548 Known.One |= ((LHSKnown.One.getZExtValue() >> SelBits) & 0xff) << I;
4549 Known.Zero |= ((LHSKnown.Zero.getZExtValue() >> SelBits) & 0xff) << I;
4550 } else if (SelBits == 0x0c) {
4551 Known.Zero |= 0xFFull << I;
4552 } else if (SelBits > 0x0c) {
4553 Known.One |= 0xFFull << I;
4555 Sel >>= 8;
4557 break;
4559 case AMDGPUISD::BUFFER_LOAD_UBYTE: {
4560 Known.Zero.setHighBits(24);
4561 break;
4563 case AMDGPUISD::BUFFER_LOAD_USHORT: {
4564 Known.Zero.setHighBits(16);
4565 break;
4567 case AMDGPUISD::LDS: {
4568 auto GA = cast<GlobalAddressSDNode>(Op.getOperand(0).getNode());
4569 unsigned Align = GA->getGlobal()->getAlignment();
4571 Known.Zero.setHighBits(16);
4572 if (Align)
4573 Known.Zero.setLowBits(Log2_32(Align));
4574 break;
4576 case ISD::INTRINSIC_WO_CHAIN: {
4577 unsigned IID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4578 switch (IID) {
4579 case Intrinsic::amdgcn_mbcnt_lo:
4580 case Intrinsic::amdgcn_mbcnt_hi: {
4581 const GCNSubtarget &ST =
4582 DAG.getMachineFunction().getSubtarget<GCNSubtarget>();
4583 // These return at most the wavefront size - 1.
4584 unsigned Size = Op.getValueType().getSizeInBits();
4585 Known.Zero.setHighBits(Size - ST.getWavefrontSizeLog2());
4586 break;
4588 default:
4589 break;
4595 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
4596 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4597 unsigned Depth) const {
4598 switch (Op.getOpcode()) {
4599 case AMDGPUISD::BFE_I32: {
4600 ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4601 if (!Width)
4602 return 1;
4604 unsigned SignBits = 32 - Width->getZExtValue() + 1;
4605 if (!isNullConstant(Op.getOperand(1)))
4606 return SignBits;
4608 // TODO: Could probably figure something out with non-0 offsets.
4609 unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4610 return std::max(SignBits, Op0SignBits);
4613 case AMDGPUISD::BFE_U32: {
4614 ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4615 return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
4618 case AMDGPUISD::CARRY:
4619 case AMDGPUISD::BORROW:
4620 return 31;
4621 case AMDGPUISD::BUFFER_LOAD_BYTE:
4622 return 25;
4623 case AMDGPUISD::BUFFER_LOAD_SHORT:
4624 return 17;
4625 case AMDGPUISD::BUFFER_LOAD_UBYTE:
4626 return 24;
4627 case AMDGPUISD::BUFFER_LOAD_USHORT:
4628 return 16;
4629 case AMDGPUISD::FP_TO_FP16:
4630 case AMDGPUISD::FP16_ZEXT:
4631 return 16;
4632 default:
4633 return 1;
4637 bool AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
4638 const SelectionDAG &DAG,
4639 bool SNaN,
4640 unsigned Depth) const {
4641 unsigned Opcode = Op.getOpcode();
4642 switch (Opcode) {
4643 case AMDGPUISD::FMIN_LEGACY:
4644 case AMDGPUISD::FMAX_LEGACY: {
4645 if (SNaN)
4646 return true;
4648 // TODO: Can check no nans on one of the operands for each one, but which
4649 // one?
4650 return false;
4652 case AMDGPUISD::FMUL_LEGACY:
4653 case AMDGPUISD::CVT_PKRTZ_F16_F32: {
4654 if (SNaN)
4655 return true;
4656 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4657 DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4659 case AMDGPUISD::FMED3:
4660 case AMDGPUISD::FMIN3:
4661 case AMDGPUISD::FMAX3:
4662 case AMDGPUISD::FMAD_FTZ: {
4663 if (SNaN)
4664 return true;
4665 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4666 DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4667 DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4669 case AMDGPUISD::CVT_F32_UBYTE0:
4670 case AMDGPUISD::CVT_F32_UBYTE1:
4671 case AMDGPUISD::CVT_F32_UBYTE2:
4672 case AMDGPUISD::CVT_F32_UBYTE3:
4673 return true;
4675 case AMDGPUISD::RCP:
4676 case AMDGPUISD::RSQ:
4677 case AMDGPUISD::RCP_LEGACY:
4678 case AMDGPUISD::RSQ_LEGACY:
4679 case AMDGPUISD::RSQ_CLAMP: {
4680 if (SNaN)
4681 return true;
4683 // TODO: Need is known positive check.
4684 return false;
4686 case AMDGPUISD::LDEXP:
4687 case AMDGPUISD::FRACT: {
4688 if (SNaN)
4689 return true;
4690 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4692 case AMDGPUISD::DIV_SCALE:
4693 case AMDGPUISD::DIV_FMAS:
4694 case AMDGPUISD::DIV_FIXUP:
4695 case AMDGPUISD::TRIG_PREOP:
4696 // TODO: Refine on operands.
4697 return SNaN;
4698 case AMDGPUISD::SIN_HW:
4699 case AMDGPUISD::COS_HW: {
4700 // TODO: Need check for infinity
4701 return SNaN;
4703 case ISD::INTRINSIC_WO_CHAIN: {
4704 unsigned IntrinsicID
4705 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4706 // TODO: Handle more intrinsics
4707 switch (IntrinsicID) {
4708 case Intrinsic::amdgcn_cubeid:
4709 return true;
4711 case Intrinsic::amdgcn_frexp_mant: {
4712 if (SNaN)
4713 return true;
4714 return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4716 case Intrinsic::amdgcn_cvt_pkrtz: {
4717 if (SNaN)
4718 return true;
4719 return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4720 DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4722 case Intrinsic::amdgcn_fdot2:
4723 // TODO: Refine on operand
4724 return SNaN;
4725 default:
4726 return false;
4729 default:
4730 return false;
4734 TargetLowering::AtomicExpansionKind
4735 AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
4736 switch (RMW->getOperation()) {
4737 case AtomicRMWInst::Nand:
4738 case AtomicRMWInst::FAdd:
4739 case AtomicRMWInst::FSub:
4740 return AtomicExpansionKind::CmpXChg;
4741 default:
4742 return AtomicExpansionKind::None;