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.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUISelLowering.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPUMachineFunction.h"
19 #include "GCNSubtarget.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/IntrinsicsAMDGPU.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/KnownBits.h"
26 #include "llvm/Target/TargetMachine.h"
27 
28 using namespace llvm;
29 
30 #include "AMDGPUGenCallingConv.inc"
31 
32 static cl::opt<bool> AMDGPUBypassSlowDiv(
33   "amdgpu-bypass-slow-div",
34   cl::desc("Skip 64-bit divide for dynamic 32-bit values"),
35   cl::init(true));
36 
37 // Find a larger type to do a load / store of a vector with.
38 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
39   unsigned StoreSize = VT.getStoreSizeInBits();
40   if (StoreSize <= 32)
41     return EVT::getIntegerVT(Ctx, StoreSize);
42 
43   assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
44   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
45 }
46 
47 unsigned AMDGPUTargetLowering::numBitsUnsigned(SDValue Op, SelectionDAG &DAG) {
48   EVT VT = Op.getValueType();
49   KnownBits Known = DAG.computeKnownBits(Op);
50   return VT.getSizeInBits() - Known.countMinLeadingZeros();
51 }
52 
53 unsigned AMDGPUTargetLowering::numBitsSigned(SDValue Op, SelectionDAG &DAG) {
54   EVT VT = Op.getValueType();
55 
56   // In order for this to be a signed 24-bit value, bit 23, must
57   // be a sign bit.
58   return VT.getSizeInBits() - DAG.ComputeNumSignBits(Op);
59 }
60 
61 AMDGPUTargetLowering::AMDGPUTargetLowering(const TargetMachine &TM,
62                                            const AMDGPUSubtarget &STI)
63     : TargetLowering(TM), Subtarget(&STI) {
64   // Lower floating point store/load to integer store/load to reduce the number
65   // of patterns in tablegen.
66   setOperationAction(ISD::LOAD, MVT::f32, Promote);
67   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
68 
69   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
70   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
71 
72   setOperationAction(ISD::LOAD, MVT::v3f32, Promote);
73   AddPromotedToType(ISD::LOAD, MVT::v3f32, MVT::v3i32);
74 
75   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
76   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
77 
78   setOperationAction(ISD::LOAD, MVT::v5f32, Promote);
79   AddPromotedToType(ISD::LOAD, MVT::v5f32, MVT::v5i32);
80 
81   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
82   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
83 
84   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
85   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
86 
87   setOperationAction(ISD::LOAD, MVT::v32f32, Promote);
88   AddPromotedToType(ISD::LOAD, MVT::v32f32, MVT::v32i32);
89 
90   setOperationAction(ISD::LOAD, MVT::i64, Promote);
91   AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
92 
93   setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
94   AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
95 
96   setOperationAction(ISD::LOAD, MVT::f64, Promote);
97   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::v2i32);
98 
99   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
100   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v4i32);
101 
102   setOperationAction(ISD::LOAD, MVT::v4i64, Promote);
103   AddPromotedToType(ISD::LOAD, MVT::v4i64, MVT::v8i32);
104 
105   setOperationAction(ISD::LOAD, MVT::v4f64, Promote);
106   AddPromotedToType(ISD::LOAD, MVT::v4f64, MVT::v8i32);
107 
108   setOperationAction(ISD::LOAD, MVT::v8i64, Promote);
109   AddPromotedToType(ISD::LOAD, MVT::v8i64, MVT::v16i32);
110 
111   setOperationAction(ISD::LOAD, MVT::v8f64, Promote);
112   AddPromotedToType(ISD::LOAD, MVT::v8f64, MVT::v16i32);
113 
114   setOperationAction(ISD::LOAD, MVT::v16i64, Promote);
115   AddPromotedToType(ISD::LOAD, MVT::v16i64, MVT::v32i32);
116 
117   setOperationAction(ISD::LOAD, MVT::v16f64, Promote);
118   AddPromotedToType(ISD::LOAD, MVT::v16f64, MVT::v32i32);
119 
120   // There are no 64-bit extloads. These should be done as a 32-bit extload and
121   // an extension to 64-bit.
122   for (MVT VT : MVT::integer_valuetypes()) {
123     setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
124     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
125     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
126   }
127 
128   for (MVT VT : MVT::integer_valuetypes()) {
129     if (VT == MVT::i64)
130       continue;
131 
132     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
133     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
134     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
135     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
136 
137     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
138     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
139     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
140     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
141 
142     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
143     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
144     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
145     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
146   }
147 
148   for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
149     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
150     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
151     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
152     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
153     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
154     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
155     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
156     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
157     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
158     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v3i16, Expand);
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v3i16, Expand);
160     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v3i16, Expand);
161     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
162     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
163     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
164   }
165 
166   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
167   setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
168   setLoadExtAction(ISD::EXTLOAD, MVT::v3f32, MVT::v3f16, Expand);
169   setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
170   setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
171   setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Expand);
172   setLoadExtAction(ISD::EXTLOAD, MVT::v32f32, MVT::v32f16, Expand);
173 
174   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
175   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
176   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Expand);
177   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f32, Expand);
178   setLoadExtAction(ISD::EXTLOAD, MVT::v16f64, MVT::v16f32, Expand);
179 
180   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
181   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
182   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
183   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
184   setLoadExtAction(ISD::EXTLOAD, MVT::v16f64, MVT::v16f16, Expand);
185 
186   setOperationAction(ISD::STORE, MVT::f32, Promote);
187   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
188 
189   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
190   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
191 
192   setOperationAction(ISD::STORE, MVT::v3f32, Promote);
193   AddPromotedToType(ISD::STORE, MVT::v3f32, MVT::v3i32);
194 
195   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
196   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
197 
198   setOperationAction(ISD::STORE, MVT::v5f32, Promote);
199   AddPromotedToType(ISD::STORE, MVT::v5f32, MVT::v5i32);
200 
201   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
202   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
203 
204   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
205   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
206 
207   setOperationAction(ISD::STORE, MVT::v32f32, Promote);
208   AddPromotedToType(ISD::STORE, MVT::v32f32, MVT::v32i32);
209 
210   setOperationAction(ISD::STORE, MVT::i64, Promote);
211   AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
212 
213   setOperationAction(ISD::STORE, MVT::v2i64, Promote);
214   AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
215 
216   setOperationAction(ISD::STORE, MVT::f64, Promote);
217   AddPromotedToType(ISD::STORE, MVT::f64, MVT::v2i32);
218 
219   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
220   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v4i32);
221 
222   setOperationAction(ISD::STORE, MVT::v4i64, Promote);
223   AddPromotedToType(ISD::STORE, MVT::v4i64, MVT::v8i32);
224 
225   setOperationAction(ISD::STORE, MVT::v4f64, Promote);
226   AddPromotedToType(ISD::STORE, MVT::v4f64, MVT::v8i32);
227 
228   setOperationAction(ISD::STORE, MVT::v8i64, Promote);
229   AddPromotedToType(ISD::STORE, MVT::v8i64, MVT::v16i32);
230 
231   setOperationAction(ISD::STORE, MVT::v8f64, Promote);
232   AddPromotedToType(ISD::STORE, MVT::v8f64, MVT::v16i32);
233 
234   setOperationAction(ISD::STORE, MVT::v16i64, Promote);
235   AddPromotedToType(ISD::STORE, MVT::v16i64, MVT::v32i32);
236 
237   setOperationAction(ISD::STORE, MVT::v16f64, Promote);
238   AddPromotedToType(ISD::STORE, MVT::v16f64, MVT::v32i32);
239 
240   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
241   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
242   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
243   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
244 
245   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
246   setTruncStoreAction(MVT::v2i64, MVT::v2i8, Expand);
247   setTruncStoreAction(MVT::v2i64, MVT::v2i16, Expand);
248   setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
249 
250   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
251   setTruncStoreAction(MVT::v2f32, MVT::v2f16, Expand);
252   setTruncStoreAction(MVT::v3f32, MVT::v3f16, Expand);
253   setTruncStoreAction(MVT::v4f32, MVT::v4f16, Expand);
254   setTruncStoreAction(MVT::v8f32, MVT::v8f16, Expand);
255   setTruncStoreAction(MVT::v16f32, MVT::v16f16, Expand);
256   setTruncStoreAction(MVT::v32f32, MVT::v32f16, Expand);
257 
258   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
259   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
260 
261   setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
262   setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
263 
264   setTruncStoreAction(MVT::v4i64, MVT::v4i32, Expand);
265   setTruncStoreAction(MVT::v4i64, MVT::v4i16, Expand);
266   setTruncStoreAction(MVT::v4f64, MVT::v4f32, Expand);
267   setTruncStoreAction(MVT::v4f64, MVT::v4f16, Expand);
268 
269   setTruncStoreAction(MVT::v8f64, MVT::v8f32, Expand);
270   setTruncStoreAction(MVT::v8f64, MVT::v8f16, Expand);
271 
272   setTruncStoreAction(MVT::v16f64, MVT::v16f32, Expand);
273   setTruncStoreAction(MVT::v16f64, MVT::v16f16, Expand);
274   setTruncStoreAction(MVT::v16i64, MVT::v16i16, Expand);
275   setTruncStoreAction(MVT::v16i64, MVT::v16i16, Expand);
276   setTruncStoreAction(MVT::v16i64, MVT::v16i8, Expand);
277   setTruncStoreAction(MVT::v16i64, MVT::v16i8, Expand);
278   setTruncStoreAction(MVT::v16i64, MVT::v16i1, Expand);
279 
280   setOperationAction(ISD::Constant, MVT::i32, Legal);
281   setOperationAction(ISD::Constant, MVT::i64, Legal);
282   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
283   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
284 
285   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
286   setOperationAction(ISD::BRIND, MVT::Other, Expand);
287 
288   // This is totally unsupported, just custom lower to produce an error.
289   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
290 
291   // Library functions.  These default to Expand, but we have instructions
292   // for them.
293   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
294   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
295   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
296   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
297   setOperationAction(ISD::FABS,   MVT::f32, Legal);
298   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
299   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
300   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
301   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
302   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
303 
304   setOperationAction(ISD::FROUND, MVT::f32, Custom);
305   setOperationAction(ISD::FROUND, MVT::f64, Custom);
306 
307   setOperationAction(ISD::FLOG, MVT::f32, Custom);
308   setOperationAction(ISD::FLOG10, MVT::f32, Custom);
309   setOperationAction(ISD::FEXP, MVT::f32, Custom);
310 
311 
312   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
313   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
314 
315   setOperationAction(ISD::FREM, MVT::f16, Custom);
316   setOperationAction(ISD::FREM, MVT::f32, Custom);
317   setOperationAction(ISD::FREM, MVT::f64, Custom);
318 
319   // Expand to fneg + fadd.
320   setOperationAction(ISD::FSUB, MVT::f64, Expand);
321 
322   setOperationAction(ISD::CONCAT_VECTORS, MVT::v3i32, Custom);
323   setOperationAction(ISD::CONCAT_VECTORS, MVT::v3f32, Custom);
324   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
325   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
326   setOperationAction(ISD::CONCAT_VECTORS, MVT::v5i32, Custom);
327   setOperationAction(ISD::CONCAT_VECTORS, MVT::v5f32, Custom);
328   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
329   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
330   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
331   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
332   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v3f32, Custom);
333   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v3i32, Custom);
334   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
335   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
336   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v5f32, Custom);
337   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v5i32, Custom);
338   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
339   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
340   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16f32, Custom);
341   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16i32, Custom);
342   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32f32, Custom);
343   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32i32, Custom);
344   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f64, Custom);
345   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i64, Custom);
346   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f64, Custom);
347   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i64, Custom);
348   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f64, Custom);
349   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i64, Custom);
350   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16f64, Custom);
351   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16i64, Custom);
352 
353   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
354   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Custom);
355   setOperationAction(ISD::FP_TO_FP16, MVT::f32, Custom);
356 
357   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
358   for (MVT VT : ScalarIntVTs) {
359     // These should use [SU]DIVREM, so set them to expand
360     setOperationAction(ISD::SDIV, VT, Expand);
361     setOperationAction(ISD::UDIV, VT, Expand);
362     setOperationAction(ISD::SREM, VT, Expand);
363     setOperationAction(ISD::UREM, VT, Expand);
364 
365     // GPU does not have divrem function for signed or unsigned.
366     setOperationAction(ISD::SDIVREM, VT, Custom);
367     setOperationAction(ISD::UDIVREM, VT, Custom);
368 
369     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
370     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
371     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
372 
373     setOperationAction(ISD::BSWAP, VT, Expand);
374     setOperationAction(ISD::CTTZ, VT, Expand);
375     setOperationAction(ISD::CTLZ, VT, Expand);
376 
377     // AMDGPU uses ADDC/SUBC/ADDE/SUBE
378     setOperationAction(ISD::ADDC, VT, Legal);
379     setOperationAction(ISD::SUBC, VT, Legal);
380     setOperationAction(ISD::ADDE, VT, Legal);
381     setOperationAction(ISD::SUBE, VT, Legal);
382   }
383 
384   // The hardware supports 32-bit FSHR, but not FSHL.
385   setOperationAction(ISD::FSHR, MVT::i32, Legal);
386 
387   // The hardware supports 32-bit ROTR, but not ROTL.
388   setOperationAction(ISD::ROTL, MVT::i32, Expand);
389   setOperationAction(ISD::ROTL, MVT::i64, Expand);
390   setOperationAction(ISD::ROTR, MVT::i64, Expand);
391 
392   setOperationAction(ISD::MULHU, MVT::i16, Expand);
393   setOperationAction(ISD::MULHS, MVT::i16, Expand);
394 
395   setOperationAction(ISD::MUL, MVT::i64, Expand);
396   setOperationAction(ISD::MULHU, MVT::i64, Expand);
397   setOperationAction(ISD::MULHS, MVT::i64, Expand);
398   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
399   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
400   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
401   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
402   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
403 
404   setOperationAction(ISD::SMIN, MVT::i32, Legal);
405   setOperationAction(ISD::UMIN, MVT::i32, Legal);
406   setOperationAction(ISD::SMAX, MVT::i32, Legal);
407   setOperationAction(ISD::UMAX, MVT::i32, Legal);
408 
409   setOperationAction(ISD::CTTZ, MVT::i64, Custom);
410   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom);
411   setOperationAction(ISD::CTLZ, MVT::i64, Custom);
412   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
413 
414   static const MVT::SimpleValueType VectorIntTypes[] = {
415     MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32
416   };
417 
418   for (MVT VT : VectorIntTypes) {
419     // Expand the following operations for the current type by default.
420     setOperationAction(ISD::ADD,  VT, Expand);
421     setOperationAction(ISD::AND,  VT, Expand);
422     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
423     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
424     setOperationAction(ISD::MUL,  VT, Expand);
425     setOperationAction(ISD::MULHU, VT, Expand);
426     setOperationAction(ISD::MULHS, VT, Expand);
427     setOperationAction(ISD::OR,   VT, Expand);
428     setOperationAction(ISD::SHL,  VT, Expand);
429     setOperationAction(ISD::SRA,  VT, Expand);
430     setOperationAction(ISD::SRL,  VT, Expand);
431     setOperationAction(ISD::ROTL, VT, Expand);
432     setOperationAction(ISD::ROTR, VT, Expand);
433     setOperationAction(ISD::SUB,  VT, Expand);
434     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
435     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
436     setOperationAction(ISD::SDIV, VT, Expand);
437     setOperationAction(ISD::UDIV, VT, Expand);
438     setOperationAction(ISD::SREM, VT, Expand);
439     setOperationAction(ISD::UREM, VT, Expand);
440     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
441     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
442     setOperationAction(ISD::SDIVREM, VT, Expand);
443     setOperationAction(ISD::UDIVREM, VT, Expand);
444     setOperationAction(ISD::SELECT, VT, Expand);
445     setOperationAction(ISD::VSELECT, VT, Expand);
446     setOperationAction(ISD::SELECT_CC, VT, Expand);
447     setOperationAction(ISD::XOR,  VT, Expand);
448     setOperationAction(ISD::BSWAP, VT, Expand);
449     setOperationAction(ISD::CTPOP, VT, Expand);
450     setOperationAction(ISD::CTTZ, VT, Expand);
451     setOperationAction(ISD::CTLZ, VT, Expand);
452     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
453     setOperationAction(ISD::SETCC, VT, Expand);
454   }
455 
456   static const MVT::SimpleValueType FloatVectorTypes[] = {
457      MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32
458   };
459 
460   for (MVT VT : FloatVectorTypes) {
461     setOperationAction(ISD::FABS, VT, Expand);
462     setOperationAction(ISD::FMINNUM, VT, Expand);
463     setOperationAction(ISD::FMAXNUM, VT, Expand);
464     setOperationAction(ISD::FADD, VT, Expand);
465     setOperationAction(ISD::FCEIL, VT, Expand);
466     setOperationAction(ISD::FCOS, VT, Expand);
467     setOperationAction(ISD::FDIV, VT, Expand);
468     setOperationAction(ISD::FEXP2, VT, Expand);
469     setOperationAction(ISD::FEXP, VT, Expand);
470     setOperationAction(ISD::FLOG2, VT, Expand);
471     setOperationAction(ISD::FREM, VT, Expand);
472     setOperationAction(ISD::FLOG, VT, Expand);
473     setOperationAction(ISD::FLOG10, VT, Expand);
474     setOperationAction(ISD::FPOW, VT, Expand);
475     setOperationAction(ISD::FFLOOR, VT, Expand);
476     setOperationAction(ISD::FTRUNC, VT, Expand);
477     setOperationAction(ISD::FMUL, VT, Expand);
478     setOperationAction(ISD::FMA, VT, Expand);
479     setOperationAction(ISD::FRINT, VT, Expand);
480     setOperationAction(ISD::FNEARBYINT, VT, Expand);
481     setOperationAction(ISD::FSQRT, VT, Expand);
482     setOperationAction(ISD::FSIN, VT, Expand);
483     setOperationAction(ISD::FSUB, VT, Expand);
484     setOperationAction(ISD::FNEG, VT, Expand);
485     setOperationAction(ISD::VSELECT, VT, Expand);
486     setOperationAction(ISD::SELECT_CC, VT, Expand);
487     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
488     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
489     setOperationAction(ISD::SETCC, VT, Expand);
490     setOperationAction(ISD::FCANONICALIZE, VT, Expand);
491   }
492 
493   // This causes using an unrolled select operation rather than expansion with
494   // bit operations. This is in general better, but the alternative using BFI
495   // instructions may be better if the select sources are SGPRs.
496   setOperationAction(ISD::SELECT, MVT::v2f32, Promote);
497   AddPromotedToType(ISD::SELECT, MVT::v2f32, MVT::v2i32);
498 
499   setOperationAction(ISD::SELECT, MVT::v3f32, Promote);
500   AddPromotedToType(ISD::SELECT, MVT::v3f32, MVT::v3i32);
501 
502   setOperationAction(ISD::SELECT, MVT::v4f32, Promote);
503   AddPromotedToType(ISD::SELECT, MVT::v4f32, MVT::v4i32);
504 
505   setOperationAction(ISD::SELECT, MVT::v5f32, Promote);
506   AddPromotedToType(ISD::SELECT, MVT::v5f32, MVT::v5i32);
507 
508   // There are no libcalls of any kind.
509   for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
510     setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
511 
512   setSchedulingPreference(Sched::RegPressure);
513   setJumpIsExpensive(true);
514 
515   // FIXME: This is only partially true. If we have to do vector compares, any
516   // SGPR pair can be a condition register. If we have a uniform condition, we
517   // are better off doing SALU operations, where there is only one SCC. For now,
518   // we don't have a way of knowing during instruction selection if a condition
519   // will be uniform and we always use vector compares. Assume we are using
520   // vector compares until that is fixed.
521   setHasMultipleConditionRegisters(true);
522 
523   setMinCmpXchgSizeInBits(32);
524   setSupportsUnalignedAtomics(false);
525 
526   PredictableSelectIsExpensive = false;
527 
528   // We want to find all load dependencies for long chains of stores to enable
529   // merging into very wide vectors. The problem is with vectors with > 4
530   // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
531   // vectors are a legal type, even though we have to split the loads
532   // usually. When we can more precisely specify load legality per address
533   // space, we should be able to make FindBetterChain/MergeConsecutiveStores
534   // smarter so that they can figure out what to do in 2 iterations without all
535   // N > 4 stores on the same chain.
536   GatherAllAliasesMaxDepth = 16;
537 
538   // memcpy/memmove/memset are expanded in the IR, so we shouldn't need to worry
539   // about these during lowering.
540   MaxStoresPerMemcpy  = 0xffffffff;
541   MaxStoresPerMemmove = 0xffffffff;
542   MaxStoresPerMemset  = 0xffffffff;
543 
544   // The expansion for 64-bit division is enormous.
545   if (AMDGPUBypassSlowDiv)
546     addBypassSlowDiv(64, 32);
547 
548   setTargetDAGCombine(ISD::BITCAST);
549   setTargetDAGCombine(ISD::SHL);
550   setTargetDAGCombine(ISD::SRA);
551   setTargetDAGCombine(ISD::SRL);
552   setTargetDAGCombine(ISD::TRUNCATE);
553   setTargetDAGCombine(ISD::MUL);
554   setTargetDAGCombine(ISD::MULHU);
555   setTargetDAGCombine(ISD::MULHS);
556   setTargetDAGCombine(ISD::SELECT);
557   setTargetDAGCombine(ISD::SELECT_CC);
558   setTargetDAGCombine(ISD::STORE);
559   setTargetDAGCombine(ISD::FADD);
560   setTargetDAGCombine(ISD::FSUB);
561   setTargetDAGCombine(ISD::FNEG);
562   setTargetDAGCombine(ISD::FABS);
563   setTargetDAGCombine(ISD::AssertZext);
564   setTargetDAGCombine(ISD::AssertSext);
565   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
566 }
567 
568 bool AMDGPUTargetLowering::mayIgnoreSignedZero(SDValue Op) const {
569   if (getTargetMachine().Options.NoSignedZerosFPMath)
570     return true;
571 
572   const auto Flags = Op.getNode()->getFlags();
573   if (Flags.hasNoSignedZeros())
574     return true;
575 
576   return false;
577 }
578 
579 //===----------------------------------------------------------------------===//
580 // Target Information
581 //===----------------------------------------------------------------------===//
582 
583 LLVM_READNONE
584 static bool fnegFoldsIntoOp(unsigned Opc) {
585   switch (Opc) {
586   case ISD::FADD:
587   case ISD::FSUB:
588   case ISD::FMUL:
589   case ISD::FMA:
590   case ISD::FMAD:
591   case ISD::FMINNUM:
592   case ISD::FMAXNUM:
593   case ISD::FMINNUM_IEEE:
594   case ISD::FMAXNUM_IEEE:
595   case ISD::FSIN:
596   case ISD::FTRUNC:
597   case ISD::FRINT:
598   case ISD::FNEARBYINT:
599   case ISD::FCANONICALIZE:
600   case AMDGPUISD::RCP:
601   case AMDGPUISD::RCP_LEGACY:
602   case AMDGPUISD::RCP_IFLAG:
603   case AMDGPUISD::SIN_HW:
604   case AMDGPUISD::FMUL_LEGACY:
605   case AMDGPUISD::FMIN_LEGACY:
606   case AMDGPUISD::FMAX_LEGACY:
607   case AMDGPUISD::FMED3:
608     // TODO: handle llvm.amdgcn.fma.legacy
609     return true;
610   default:
611     return false;
612   }
613 }
614 
615 /// \p returns true if the operation will definitely need to use a 64-bit
616 /// encoding, and thus will use a VOP3 encoding regardless of the source
617 /// modifiers.
618 LLVM_READONLY
619 static bool opMustUseVOP3Encoding(const SDNode *N, MVT VT) {
620   return N->getNumOperands() > 2 || VT == MVT::f64;
621 }
622 
623 // Most FP instructions support source modifiers, but this could be refined
624 // slightly.
625 LLVM_READONLY
626 static bool hasSourceMods(const SDNode *N) {
627   if (isa<MemSDNode>(N))
628     return false;
629 
630   switch (N->getOpcode()) {
631   case ISD::CopyToReg:
632   case ISD::SELECT:
633   case ISD::FDIV:
634   case ISD::FREM:
635   case ISD::INLINEASM:
636   case ISD::INLINEASM_BR:
637   case AMDGPUISD::DIV_SCALE:
638   case ISD::INTRINSIC_W_CHAIN:
639 
640   // TODO: Should really be looking at the users of the bitcast. These are
641   // problematic because bitcasts are used to legalize all stores to integer
642   // types.
643   case ISD::BITCAST:
644     return false;
645   case ISD::INTRINSIC_WO_CHAIN: {
646     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
647     case Intrinsic::amdgcn_interp_p1:
648     case Intrinsic::amdgcn_interp_p2:
649     case Intrinsic::amdgcn_interp_mov:
650     case Intrinsic::amdgcn_interp_p1_f16:
651     case Intrinsic::amdgcn_interp_p2_f16:
652       return false;
653     default:
654       return true;
655     }
656   }
657   default:
658     return true;
659   }
660 }
661 
662 bool AMDGPUTargetLowering::allUsesHaveSourceMods(const SDNode *N,
663                                                  unsigned CostThreshold) {
664   // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus
665   // it is truly free to use a source modifier in all cases. If there are
666   // multiple users but for each one will necessitate using VOP3, there will be
667   // a code size increase. Try to avoid increasing code size unless we know it
668   // will save on the instruction count.
669   unsigned NumMayIncreaseSize = 0;
670   MVT VT = N->getValueType(0).getScalarType().getSimpleVT();
671 
672   // XXX - Should this limit number of uses to check?
673   for (const SDNode *U : N->uses()) {
674     if (!hasSourceMods(U))
675       return false;
676 
677     if (!opMustUseVOP3Encoding(U, VT)) {
678       if (++NumMayIncreaseSize > CostThreshold)
679         return false;
680     }
681   }
682 
683   return true;
684 }
685 
686 EVT AMDGPUTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
687                                               ISD::NodeType ExtendKind) const {
688   assert(!VT.isVector() && "only scalar expected");
689 
690   // Round to the next multiple of 32-bits.
691   unsigned Size = VT.getSizeInBits();
692   if (Size <= 32)
693     return MVT::i32;
694   return EVT::getIntegerVT(Context, 32 * ((Size + 31) / 32));
695 }
696 
697 MVT AMDGPUTargetLowering::getVectorIdxTy(const DataLayout &) const {
698   return MVT::i32;
699 }
700 
701 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
702   return true;
703 }
704 
705 // The backend supports 32 and 64 bit floating point immediates.
706 // FIXME: Why are we reporting vectors of FP immediates as legal?
707 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
708                                         bool ForCodeSize) const {
709   EVT ScalarVT = VT.getScalarType();
710   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
711          (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
712 }
713 
714 // We don't want to shrink f64 / f32 constants.
715 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
716   EVT ScalarVT = VT.getScalarType();
717   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
718 }
719 
720 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
721                                                  ISD::LoadExtType ExtTy,
722                                                  EVT NewVT) const {
723   // TODO: This may be worth removing. Check regression tests for diffs.
724   if (!TargetLoweringBase::shouldReduceLoadWidth(N, ExtTy, NewVT))
725     return false;
726 
727   unsigned NewSize = NewVT.getStoreSizeInBits();
728 
729   // If we are reducing to a 32-bit load or a smaller multi-dword load,
730   // this is always better.
731   if (NewSize >= 32)
732     return true;
733 
734   EVT OldVT = N->getValueType(0);
735   unsigned OldSize = OldVT.getStoreSizeInBits();
736 
737   MemSDNode *MN = cast<MemSDNode>(N);
738   unsigned AS = MN->getAddressSpace();
739   // Do not shrink an aligned scalar load to sub-dword.
740   // Scalar engine cannot do sub-dword loads.
741   if (OldSize >= 32 && NewSize < 32 && MN->getAlignment() >= 4 &&
742       (AS == AMDGPUAS::CONSTANT_ADDRESS ||
743        AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
744        (isa<LoadSDNode>(N) &&
745         AS == AMDGPUAS::GLOBAL_ADDRESS && MN->isInvariant())) &&
746       AMDGPUInstrInfo::isUniformMMO(MN->getMemOperand()))
747     return false;
748 
749   // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
750   // extloads, so doing one requires using a buffer_load. In cases where we
751   // still couldn't use a scalar load, using the wider load shouldn't really
752   // hurt anything.
753 
754   // If the old size already had to be an extload, there's no harm in continuing
755   // to reduce the width.
756   return (OldSize < 32);
757 }
758 
759 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy, EVT CastTy,
760                                                    const SelectionDAG &DAG,
761                                                    const MachineMemOperand &MMO) const {
762 
763   assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
764 
765   if (LoadTy.getScalarType() == MVT::i32)
766     return false;
767 
768   unsigned LScalarSize = LoadTy.getScalarSizeInBits();
769   unsigned CastScalarSize = CastTy.getScalarSizeInBits();
770 
771   if ((LScalarSize >= CastScalarSize) && (CastScalarSize < 32))
772     return false;
773 
774   bool Fast = false;
775   return allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
776                                         CastTy, MMO, &Fast) &&
777          Fast;
778 }
779 
780 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
781 // profitable with the expansion for 64-bit since it's generally good to
782 // speculate things.
783 // FIXME: These should really have the size as a parameter.
784 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
785   return true;
786 }
787 
788 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
789   return true;
790 }
791 
792 bool AMDGPUTargetLowering::isSDNodeAlwaysUniform(const SDNode *N) const {
793   switch (N->getOpcode()) {
794   case ISD::EntryToken:
795   case ISD::TokenFactor:
796     return true;
797   case ISD::INTRINSIC_WO_CHAIN: {
798     unsigned IntrID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
799     switch (IntrID) {
800     case Intrinsic::amdgcn_readfirstlane:
801     case Intrinsic::amdgcn_readlane:
802       return true;
803     }
804     return false;
805   }
806   case ISD::LOAD:
807     if (cast<LoadSDNode>(N)->getMemOperand()->getAddrSpace() ==
808         AMDGPUAS::CONSTANT_ADDRESS_32BIT)
809       return true;
810     return false;
811   }
812   return false;
813 }
814 
815 SDValue AMDGPUTargetLowering::getNegatedExpression(
816     SDValue Op, SelectionDAG &DAG, bool LegalOperations, bool ForCodeSize,
817     NegatibleCost &Cost, unsigned Depth) const {
818 
819   switch (Op.getOpcode()) {
820   case ISD::FMA:
821   case ISD::FMAD: {
822     // Negating a fma is not free if it has users without source mods.
823     if (!allUsesHaveSourceMods(Op.getNode()))
824       return SDValue();
825     break;
826   }
827   default:
828     break;
829   }
830 
831   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
832                                               ForCodeSize, Cost, Depth);
833 }
834 
835 //===---------------------------------------------------------------------===//
836 // Target Properties
837 //===---------------------------------------------------------------------===//
838 
839 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
840   assert(VT.isFloatingPoint());
841 
842   // Packed operations do not have a fabs modifier.
843   return VT == MVT::f32 || VT == MVT::f64 ||
844          (Subtarget->has16BitInsts() && VT == MVT::f16);
845 }
846 
847 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
848   assert(VT.isFloatingPoint());
849   return VT == MVT::f32 || VT == MVT::f64 ||
850          (Subtarget->has16BitInsts() && VT == MVT::f16) ||
851          (Subtarget->hasVOP3PInsts() && VT == MVT::v2f16);
852 }
853 
854 bool AMDGPUTargetLowering:: storeOfVectorConstantIsCheap(EVT MemVT,
855                                                          unsigned NumElem,
856                                                          unsigned AS) const {
857   return true;
858 }
859 
860 bool AMDGPUTargetLowering::aggressivelyPreferBuildVectorSources(EVT VecVT) const {
861   // There are few operations which truly have vector input operands. Any vector
862   // operation is going to involve operations on each component, and a
863   // build_vector will be a copy per element, so it always makes sense to use a
864   // build_vector input in place of the extracted element to avoid a copy into a
865   // super register.
866   //
867   // We should probably only do this if all users are extracts only, but this
868   // should be the common case.
869   return true;
870 }
871 
872 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
873   // Truncate is just accessing a subregister.
874 
875   unsigned SrcSize = Source.getSizeInBits();
876   unsigned DestSize = Dest.getSizeInBits();
877 
878   return DestSize < SrcSize && DestSize % 32 == 0 ;
879 }
880 
881 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
882   // Truncate is just accessing a subregister.
883 
884   unsigned SrcSize = Source->getScalarSizeInBits();
885   unsigned DestSize = Dest->getScalarSizeInBits();
886 
887   if (DestSize== 16 && Subtarget->has16BitInsts())
888     return SrcSize >= 32;
889 
890   return DestSize < SrcSize && DestSize % 32 == 0;
891 }
892 
893 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
894   unsigned SrcSize = Src->getScalarSizeInBits();
895   unsigned DestSize = Dest->getScalarSizeInBits();
896 
897   if (SrcSize == 16 && Subtarget->has16BitInsts())
898     return DestSize >= 32;
899 
900   return SrcSize == 32 && DestSize == 64;
901 }
902 
903 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
904   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
905   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
906   // this will enable reducing 64-bit operations the 32-bit, which is always
907   // good.
908 
909   if (Src == MVT::i16)
910     return Dest == MVT::i32 ||Dest == MVT::i64 ;
911 
912   return Src == MVT::i32 && Dest == MVT::i64;
913 }
914 
915 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
916   return isZExtFree(Val.getValueType(), VT2);
917 }
918 
919 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
920   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
921   // limited number of native 64-bit operations. Shrinking an operation to fit
922   // in a single 32-bit register should always be helpful. As currently used,
923   // this is much less general than the name suggests, and is only used in
924   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
925   // not profitable, and may actually be harmful.
926   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
927 }
928 
929 //===---------------------------------------------------------------------===//
930 // TargetLowering Callbacks
931 //===---------------------------------------------------------------------===//
932 
933 CCAssignFn *AMDGPUCallLowering::CCAssignFnForCall(CallingConv::ID CC,
934                                                   bool IsVarArg) {
935   switch (CC) {
936   case CallingConv::AMDGPU_VS:
937   case CallingConv::AMDGPU_GS:
938   case CallingConv::AMDGPU_PS:
939   case CallingConv::AMDGPU_CS:
940   case CallingConv::AMDGPU_HS:
941   case CallingConv::AMDGPU_ES:
942   case CallingConv::AMDGPU_LS:
943     return CC_AMDGPU;
944   case CallingConv::C:
945   case CallingConv::Fast:
946   case CallingConv::Cold:
947     return CC_AMDGPU_Func;
948   case CallingConv::AMDGPU_Gfx:
949     return CC_SI_Gfx;
950   case CallingConv::AMDGPU_KERNEL:
951   case CallingConv::SPIR_KERNEL:
952   default:
953     report_fatal_error("Unsupported calling convention for call");
954   }
955 }
956 
957 CCAssignFn *AMDGPUCallLowering::CCAssignFnForReturn(CallingConv::ID CC,
958                                                     bool IsVarArg) {
959   switch (CC) {
960   case CallingConv::AMDGPU_KERNEL:
961   case CallingConv::SPIR_KERNEL:
962     llvm_unreachable("kernels should not be handled here");
963   case CallingConv::AMDGPU_VS:
964   case CallingConv::AMDGPU_GS:
965   case CallingConv::AMDGPU_PS:
966   case CallingConv::AMDGPU_CS:
967   case CallingConv::AMDGPU_HS:
968   case CallingConv::AMDGPU_ES:
969   case CallingConv::AMDGPU_LS:
970     return RetCC_SI_Shader;
971   case CallingConv::AMDGPU_Gfx:
972     return RetCC_SI_Gfx;
973   case CallingConv::C:
974   case CallingConv::Fast:
975   case CallingConv::Cold:
976     return RetCC_AMDGPU_Func;
977   default:
978     report_fatal_error("Unsupported calling convention.");
979   }
980 }
981 
982 /// The SelectionDAGBuilder will automatically promote function arguments
983 /// with illegal types.  However, this does not work for the AMDGPU targets
984 /// since the function arguments are stored in memory as these illegal types.
985 /// In order to handle this properly we need to get the original types sizes
986 /// from the LLVM IR Function and fixup the ISD:InputArg values before
987 /// passing them to AnalyzeFormalArguments()
988 
989 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
990 /// input values across multiple registers.  Each item in the Ins array
991 /// represents a single value that will be stored in registers.  Ins[x].VT is
992 /// the value type of the value that will be stored in the register, so
993 /// whatever SDNode we lower the argument to needs to be this type.
994 ///
995 /// In order to correctly lower the arguments we need to know the size of each
996 /// argument.  Since Ins[x].VT gives us the size of the register that will
997 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
998 /// for the orignal function argument so that we can deduce the correct memory
999 /// type to use for Ins[x].  In most cases the correct memory type will be
1000 /// Ins[x].ArgVT.  However, this will not always be the case.  If, for example,
1001 /// we have a kernel argument of type v8i8, this argument will be split into
1002 /// 8 parts and each part will be represented by its own item in the Ins array.
1003 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
1004 /// the argument before it was split.  From this, we deduce that the memory type
1005 /// for each individual part is i8.  We pass the memory type as LocVT to the
1006 /// calling convention analysis function and the register type (Ins[x].VT) as
1007 /// the ValVT.
1008 void AMDGPUTargetLowering::analyzeFormalArgumentsCompute(
1009   CCState &State,
1010   const SmallVectorImpl<ISD::InputArg> &Ins) const {
1011   const MachineFunction &MF = State.getMachineFunction();
1012   const Function &Fn = MF.getFunction();
1013   LLVMContext &Ctx = Fn.getParent()->getContext();
1014   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(MF);
1015   const unsigned ExplicitOffset = ST.getExplicitKernelArgOffset(Fn);
1016   CallingConv::ID CC = Fn.getCallingConv();
1017 
1018   Align MaxAlign = Align(1);
1019   uint64_t ExplicitArgOffset = 0;
1020   const DataLayout &DL = Fn.getParent()->getDataLayout();
1021 
1022   unsigned InIndex = 0;
1023 
1024   for (const Argument &Arg : Fn.args()) {
1025     const bool IsByRef = Arg.hasByRefAttr();
1026     Type *BaseArgTy = Arg.getType();
1027     Type *MemArgTy = IsByRef ? Arg.getParamByRefType() : BaseArgTy;
1028     MaybeAlign Alignment = IsByRef ? Arg.getParamAlign() : None;
1029     if (!Alignment)
1030       Alignment = DL.getABITypeAlign(MemArgTy);
1031     MaxAlign = max(Alignment, MaxAlign);
1032     uint64_t AllocSize = DL.getTypeAllocSize(MemArgTy);
1033 
1034     uint64_t ArgOffset = alignTo(ExplicitArgOffset, Alignment) + ExplicitOffset;
1035     ExplicitArgOffset = alignTo(ExplicitArgOffset, Alignment) + AllocSize;
1036 
1037     // We're basically throwing away everything passed into us and starting over
1038     // to get accurate in-memory offsets. The "PartOffset" is completely useless
1039     // to us as computed in Ins.
1040     //
1041     // We also need to figure out what type legalization is trying to do to get
1042     // the correct memory offsets.
1043 
1044     SmallVector<EVT, 16> ValueVTs;
1045     SmallVector<uint64_t, 16> Offsets;
1046     ComputeValueVTs(*this, DL, BaseArgTy, ValueVTs, &Offsets, ArgOffset);
1047 
1048     for (unsigned Value = 0, NumValues = ValueVTs.size();
1049          Value != NumValues; ++Value) {
1050       uint64_t BasePartOffset = Offsets[Value];
1051 
1052       EVT ArgVT = ValueVTs[Value];
1053       EVT MemVT = ArgVT;
1054       MVT RegisterVT = getRegisterTypeForCallingConv(Ctx, CC, ArgVT);
1055       unsigned NumRegs = getNumRegistersForCallingConv(Ctx, CC, ArgVT);
1056 
1057       if (NumRegs == 1) {
1058         // This argument is not split, so the IR type is the memory type.
1059         if (ArgVT.isExtended()) {
1060           // We have an extended type, like i24, so we should just use the
1061           // register type.
1062           MemVT = RegisterVT;
1063         } else {
1064           MemVT = ArgVT;
1065         }
1066       } else if (ArgVT.isVector() && RegisterVT.isVector() &&
1067                  ArgVT.getScalarType() == RegisterVT.getScalarType()) {
1068         assert(ArgVT.getVectorNumElements() > RegisterVT.getVectorNumElements());
1069         // We have a vector value which has been split into a vector with
1070         // the same scalar type, but fewer elements.  This should handle
1071         // all the floating-point vector types.
1072         MemVT = RegisterVT;
1073       } else if (ArgVT.isVector() &&
1074                  ArgVT.getVectorNumElements() == NumRegs) {
1075         // This arg has been split so that each element is stored in a separate
1076         // register.
1077         MemVT = ArgVT.getScalarType();
1078       } else if (ArgVT.isExtended()) {
1079         // We have an extended type, like i65.
1080         MemVT = RegisterVT;
1081       } else {
1082         unsigned MemoryBits = ArgVT.getStoreSizeInBits() / NumRegs;
1083         assert(ArgVT.getStoreSizeInBits() % NumRegs == 0);
1084         if (RegisterVT.isInteger()) {
1085           MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
1086         } else if (RegisterVT.isVector()) {
1087           assert(!RegisterVT.getScalarType().isFloatingPoint());
1088           unsigned NumElements = RegisterVT.getVectorNumElements();
1089           assert(MemoryBits % NumElements == 0);
1090           // This vector type has been split into another vector type with
1091           // a different elements size.
1092           EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
1093                                            MemoryBits / NumElements);
1094           MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
1095         } else {
1096           llvm_unreachable("cannot deduce memory type.");
1097         }
1098       }
1099 
1100       // Convert one element vectors to scalar.
1101       if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
1102         MemVT = MemVT.getScalarType();
1103 
1104       // Round up vec3/vec5 argument.
1105       if (MemVT.isVector() && !MemVT.isPow2VectorType()) {
1106         assert(MemVT.getVectorNumElements() == 3 ||
1107                MemVT.getVectorNumElements() == 5);
1108         MemVT = MemVT.getPow2VectorType(State.getContext());
1109       } else if (!MemVT.isSimple() && !MemVT.isVector()) {
1110         MemVT = MemVT.getRoundIntegerType(State.getContext());
1111       }
1112 
1113       unsigned PartOffset = 0;
1114       for (unsigned i = 0; i != NumRegs; ++i) {
1115         State.addLoc(CCValAssign::getCustomMem(InIndex++, RegisterVT,
1116                                                BasePartOffset + PartOffset,
1117                                                MemVT.getSimpleVT(),
1118                                                CCValAssign::Full));
1119         PartOffset += MemVT.getStoreSize();
1120       }
1121     }
1122   }
1123 }
1124 
1125 SDValue AMDGPUTargetLowering::LowerReturn(
1126   SDValue Chain, CallingConv::ID CallConv,
1127   bool isVarArg,
1128   const SmallVectorImpl<ISD::OutputArg> &Outs,
1129   const SmallVectorImpl<SDValue> &OutVals,
1130   const SDLoc &DL, SelectionDAG &DAG) const {
1131   // FIXME: Fails for r600 tests
1132   //assert(!isVarArg && Outs.empty() && OutVals.empty() &&
1133   // "wave terminate should not have return values");
1134   return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
1135 }
1136 
1137 //===---------------------------------------------------------------------===//
1138 // Target specific lowering
1139 //===---------------------------------------------------------------------===//
1140 
1141 /// Selects the correct CCAssignFn for a given CallingConvention value.
1142 CCAssignFn *AMDGPUTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1143                                                     bool IsVarArg) {
1144   return AMDGPUCallLowering::CCAssignFnForCall(CC, IsVarArg);
1145 }
1146 
1147 CCAssignFn *AMDGPUTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1148                                                       bool IsVarArg) {
1149   return AMDGPUCallLowering::CCAssignFnForReturn(CC, IsVarArg);
1150 }
1151 
1152 SDValue AMDGPUTargetLowering::addTokenForArgument(SDValue Chain,
1153                                                   SelectionDAG &DAG,
1154                                                   MachineFrameInfo &MFI,
1155                                                   int ClobberedFI) const {
1156   SmallVector<SDValue, 8> ArgChains;
1157   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
1158   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
1159 
1160   // Include the original chain at the beginning of the list. When this is
1161   // used by target LowerCall hooks, this helps legalize find the
1162   // CALLSEQ_BEGIN node.
1163   ArgChains.push_back(Chain);
1164 
1165   // Add a chain value for each stack argument corresponding
1166   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1167                             UE = DAG.getEntryNode().getNode()->use_end();
1168        U != UE; ++U) {
1169     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) {
1170       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) {
1171         if (FI->getIndex() < 0) {
1172           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
1173           int64_t InLastByte = InFirstByte;
1174           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
1175 
1176           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1177               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1178             ArgChains.push_back(SDValue(L, 1));
1179         }
1180       }
1181     }
1182   }
1183 
1184   // Build a tokenfactor for all the chains.
1185   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
1186 }
1187 
1188 SDValue AMDGPUTargetLowering::lowerUnhandledCall(CallLoweringInfo &CLI,
1189                                                  SmallVectorImpl<SDValue> &InVals,
1190                                                  StringRef Reason) const {
1191   SDValue Callee = CLI.Callee;
1192   SelectionDAG &DAG = CLI.DAG;
1193 
1194   const Function &Fn = DAG.getMachineFunction().getFunction();
1195 
1196   StringRef FuncName("<unknown>");
1197 
1198   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
1199     FuncName = G->getSymbol();
1200   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1201     FuncName = G->getGlobal()->getName();
1202 
1203   DiagnosticInfoUnsupported NoCalls(
1204     Fn, Reason + FuncName, CLI.DL.getDebugLoc());
1205   DAG.getContext()->diagnose(NoCalls);
1206 
1207   if (!CLI.IsTailCall) {
1208     for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
1209       InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
1210   }
1211 
1212   return DAG.getEntryNode();
1213 }
1214 
1215 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
1216                                         SmallVectorImpl<SDValue> &InVals) const {
1217   return lowerUnhandledCall(CLI, InVals, "unsupported call to function ");
1218 }
1219 
1220 SDValue AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1221                                                       SelectionDAG &DAG) const {
1222   const Function &Fn = DAG.getMachineFunction().getFunction();
1223 
1224   DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
1225                                             SDLoc(Op).getDebugLoc());
1226   DAG.getContext()->diagnose(NoDynamicAlloca);
1227   auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
1228   return DAG.getMergeValues(Ops, SDLoc());
1229 }
1230 
1231 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
1232                                              SelectionDAG &DAG) const {
1233   switch (Op.getOpcode()) {
1234   default:
1235     Op->print(errs(), &DAG);
1236     llvm_unreachable("Custom lowering code for this "
1237                      "instruction is not implemented yet!");
1238     break;
1239   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
1240   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
1241   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
1242   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
1243   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
1244   case ISD::FREM: return LowerFREM(Op, DAG);
1245   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
1246   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
1247   case ISD::FRINT: return LowerFRINT(Op, DAG);
1248   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
1249   case ISD::FROUND: return LowerFROUND(Op, DAG);
1250   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
1251   case ISD::FLOG:
1252     return LowerFLOG(Op, DAG, numbers::ln2f);
1253   case ISD::FLOG10:
1254     return LowerFLOG(Op, DAG, numbers::ln2f / numbers::ln10f);
1255   case ISD::FEXP:
1256     return lowerFEXP(Op, DAG);
1257   case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
1258   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
1259   case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
1260   case ISD::FP_TO_SINT:
1261   case ISD::FP_TO_UINT:
1262     return LowerFP_TO_INT(Op, DAG);
1263   case ISD::CTTZ:
1264   case ISD::CTTZ_ZERO_UNDEF:
1265   case ISD::CTLZ:
1266   case ISD::CTLZ_ZERO_UNDEF:
1267     return LowerCTLZ_CTTZ(Op, DAG);
1268   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1269   }
1270   return Op;
1271 }
1272 
1273 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
1274                                               SmallVectorImpl<SDValue> &Results,
1275                                               SelectionDAG &DAG) const {
1276   switch (N->getOpcode()) {
1277   case ISD::SIGN_EXTEND_INREG:
1278     // Different parts of legalization seem to interpret which type of
1279     // sign_extend_inreg is the one to check for custom lowering. The extended
1280     // from type is what really matters, but some places check for custom
1281     // lowering of the result type. This results in trying to use
1282     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
1283     // nothing here and let the illegal result integer be handled normally.
1284     return;
1285   default:
1286     return;
1287   }
1288 }
1289 
1290 bool AMDGPUTargetLowering::hasDefinedInitializer(const GlobalValue *GV) {
1291   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1292   if (!GVar || !GVar->hasInitializer())
1293     return false;
1294 
1295   return !isa<UndefValue>(GVar->getInitializer());
1296 }
1297 
1298 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
1299                                                  SDValue Op,
1300                                                  SelectionDAG &DAG) const {
1301 
1302   const DataLayout &DL = DAG.getDataLayout();
1303   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
1304   const GlobalValue *GV = G->getGlobal();
1305 
1306   if (G->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1307       G->getAddressSpace() == AMDGPUAS::REGION_ADDRESS) {
1308     if (!MFI->isModuleEntryFunction()) {
1309       SDLoc DL(Op);
1310       const Function &Fn = DAG.getMachineFunction().getFunction();
1311       DiagnosticInfoUnsupported BadLDSDecl(
1312         Fn, "local memory global used by non-kernel function",
1313         DL.getDebugLoc(), DS_Warning);
1314       DAG.getContext()->diagnose(BadLDSDecl);
1315 
1316       // We currently don't have a way to correctly allocate LDS objects that
1317       // aren't directly associated with a kernel. We do force inlining of
1318       // functions that use local objects. However, if these dead functions are
1319       // not eliminated, we don't want a compile time error. Just emit a warning
1320       // and a trap, since there should be no callable path here.
1321       SDValue Trap = DAG.getNode(ISD::TRAP, DL, MVT::Other, DAG.getEntryNode());
1322       SDValue OutputChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1323                                         Trap, DAG.getRoot());
1324       DAG.setRoot(OutputChain);
1325       return DAG.getUNDEF(Op.getValueType());
1326     }
1327 
1328     // XXX: What does the value of G->getOffset() mean?
1329     assert(G->getOffset() == 0 &&
1330          "Do not know what to do with an non-zero offset");
1331 
1332     // TODO: We could emit code to handle the initialization somewhere.
1333     if (!hasDefinedInitializer(GV)) {
1334       unsigned Offset = MFI->allocateLDSGlobal(DL, *cast<GlobalVariable>(GV));
1335       return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
1336     }
1337   }
1338 
1339   const Function &Fn = DAG.getMachineFunction().getFunction();
1340   DiagnosticInfoUnsupported BadInit(
1341       Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
1342   DAG.getContext()->diagnose(BadInit);
1343   return SDValue();
1344 }
1345 
1346 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
1347                                                   SelectionDAG &DAG) const {
1348   SmallVector<SDValue, 8> Args;
1349 
1350   EVT VT = Op.getValueType();
1351   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
1352     SDLoc SL(Op);
1353     SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(0));
1354     SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(1));
1355 
1356     SDValue BV = DAG.getBuildVector(MVT::v2i32, SL, { Lo, Hi });
1357     return DAG.getNode(ISD::BITCAST, SL, VT, BV);
1358   }
1359 
1360   for (const SDUse &U : Op->ops())
1361     DAG.ExtractVectorElements(U.get(), Args);
1362 
1363   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1364 }
1365 
1366 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
1367                                                      SelectionDAG &DAG) const {
1368 
1369   SmallVector<SDValue, 8> Args;
1370   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1371   EVT VT = Op.getValueType();
1372   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
1373                             VT.getVectorNumElements());
1374 
1375   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1376 }
1377 
1378 /// Generate Min/Max node
1379 SDValue AMDGPUTargetLowering::combineFMinMaxLegacy(const SDLoc &DL, EVT VT,
1380                                                    SDValue LHS, SDValue RHS,
1381                                                    SDValue True, SDValue False,
1382                                                    SDValue CC,
1383                                                    DAGCombinerInfo &DCI) const {
1384   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1385     return SDValue();
1386 
1387   SelectionDAG &DAG = DCI.DAG;
1388   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1389   switch (CCOpcode) {
1390   case ISD::SETOEQ:
1391   case ISD::SETONE:
1392   case ISD::SETUNE:
1393   case ISD::SETNE:
1394   case ISD::SETUEQ:
1395   case ISD::SETEQ:
1396   case ISD::SETFALSE:
1397   case ISD::SETFALSE2:
1398   case ISD::SETTRUE:
1399   case ISD::SETTRUE2:
1400   case ISD::SETUO:
1401   case ISD::SETO:
1402     break;
1403   case ISD::SETULE:
1404   case ISD::SETULT: {
1405     if (LHS == True)
1406       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1407     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1408   }
1409   case ISD::SETOLE:
1410   case ISD::SETOLT:
1411   case ISD::SETLE:
1412   case ISD::SETLT: {
1413     // Ordered. Assume ordered for undefined.
1414 
1415     // Only do this after legalization to avoid interfering with other combines
1416     // which might occur.
1417     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1418         !DCI.isCalledByLegalizer())
1419       return SDValue();
1420 
1421     // We need to permute the operands to get the correct NaN behavior. The
1422     // selected operand is the second one based on the failing compare with NaN,
1423     // so permute it based on the compare type the hardware uses.
1424     if (LHS == True)
1425       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1426     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1427   }
1428   case ISD::SETUGE:
1429   case ISD::SETUGT: {
1430     if (LHS == True)
1431       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1432     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1433   }
1434   case ISD::SETGT:
1435   case ISD::SETGE:
1436   case ISD::SETOGE:
1437   case ISD::SETOGT: {
1438     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1439         !DCI.isCalledByLegalizer())
1440       return SDValue();
1441 
1442     if (LHS == True)
1443       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1444     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1445   }
1446   case ISD::SETCC_INVALID:
1447     llvm_unreachable("Invalid setcc condcode!");
1448   }
1449   return SDValue();
1450 }
1451 
1452 std::pair<SDValue, SDValue>
1453 AMDGPUTargetLowering::split64BitValue(SDValue Op, SelectionDAG &DAG) const {
1454   SDLoc SL(Op);
1455 
1456   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1457 
1458   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1459   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1460 
1461   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1462   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1463 
1464   return std::make_pair(Lo, Hi);
1465 }
1466 
1467 SDValue AMDGPUTargetLowering::getLoHalf64(SDValue Op, SelectionDAG &DAG) const {
1468   SDLoc SL(Op);
1469 
1470   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1471   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1472   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1473 }
1474 
1475 SDValue AMDGPUTargetLowering::getHiHalf64(SDValue Op, SelectionDAG &DAG) const {
1476   SDLoc SL(Op);
1477 
1478   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1479   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1480   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1481 }
1482 
1483 // Split a vector type into two parts. The first part is a power of two vector.
1484 // The second part is whatever is left over, and is a scalar if it would
1485 // otherwise be a 1-vector.
1486 std::pair<EVT, EVT>
1487 AMDGPUTargetLowering::getSplitDestVTs(const EVT &VT, SelectionDAG &DAG) const {
1488   EVT LoVT, HiVT;
1489   EVT EltVT = VT.getVectorElementType();
1490   unsigned NumElts = VT.getVectorNumElements();
1491   unsigned LoNumElts = PowerOf2Ceil((NumElts + 1) / 2);
1492   LoVT = EVT::getVectorVT(*DAG.getContext(), EltVT, LoNumElts);
1493   HiVT = NumElts - LoNumElts == 1
1494              ? EltVT
1495              : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts - LoNumElts);
1496   return std::make_pair(LoVT, HiVT);
1497 }
1498 
1499 // Split a vector value into two parts of types LoVT and HiVT. HiVT could be
1500 // scalar.
1501 std::pair<SDValue, SDValue>
1502 AMDGPUTargetLowering::splitVector(const SDValue &N, const SDLoc &DL,
1503                                   const EVT &LoVT, const EVT &HiVT,
1504                                   SelectionDAG &DAG) const {
1505   assert(LoVT.getVectorNumElements() +
1506                  (HiVT.isVector() ? HiVT.getVectorNumElements() : 1) <=
1507              N.getValueType().getVectorNumElements() &&
1508          "More vector elements requested than available!");
1509   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
1510                            DAG.getVectorIdxConstant(0, DL));
1511   SDValue Hi = DAG.getNode(
1512       HiVT.isVector() ? ISD::EXTRACT_SUBVECTOR : ISD::EXTRACT_VECTOR_ELT, DL,
1513       HiVT, N, DAG.getVectorIdxConstant(LoVT.getVectorNumElements(), DL));
1514   return std::make_pair(Lo, Hi);
1515 }
1516 
1517 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1518                                               SelectionDAG &DAG) const {
1519   LoadSDNode *Load = cast<LoadSDNode>(Op);
1520   EVT VT = Op.getValueType();
1521   SDLoc SL(Op);
1522 
1523 
1524   // If this is a 2 element vector, we really want to scalarize and not create
1525   // weird 1 element vectors.
1526   if (VT.getVectorNumElements() == 2) {
1527     SDValue Ops[2];
1528     std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
1529     return DAG.getMergeValues(Ops, SL);
1530   }
1531 
1532   SDValue BasePtr = Load->getBasePtr();
1533   EVT MemVT = Load->getMemoryVT();
1534 
1535   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1536 
1537   EVT LoVT, HiVT;
1538   EVT LoMemVT, HiMemVT;
1539   SDValue Lo, Hi;
1540 
1541   std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1542   std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1543   std::tie(Lo, Hi) = splitVector(Op, SL, LoVT, HiVT, DAG);
1544 
1545   unsigned Size = LoMemVT.getStoreSize();
1546   unsigned BaseAlign = Load->getAlignment();
1547   unsigned HiAlign = MinAlign(BaseAlign, Size);
1548 
1549   SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1550                                   Load->getChain(), BasePtr, SrcValue, LoMemVT,
1551                                   BaseAlign, Load->getMemOperand()->getFlags());
1552   SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Size));
1553   SDValue HiLoad =
1554       DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1555                      HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1556                      HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1557 
1558   SDValue Join;
1559   if (LoVT == HiVT) {
1560     // This is the case that the vector is power of two so was evenly split.
1561     Join = DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad);
1562   } else {
1563     Join = DAG.getNode(ISD::INSERT_SUBVECTOR, SL, VT, DAG.getUNDEF(VT), LoLoad,
1564                        DAG.getVectorIdxConstant(0, SL));
1565     Join = DAG.getNode(
1566         HiVT.isVector() ? ISD::INSERT_SUBVECTOR : ISD::INSERT_VECTOR_ELT, SL,
1567         VT, Join, HiLoad,
1568         DAG.getVectorIdxConstant(LoVT.getVectorNumElements(), SL));
1569   }
1570 
1571   SDValue Ops[] = {Join, DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1572                                      LoLoad.getValue(1), HiLoad.getValue(1))};
1573 
1574   return DAG.getMergeValues(Ops, SL);
1575 }
1576 
1577 SDValue AMDGPUTargetLowering::WidenOrSplitVectorLoad(SDValue Op,
1578                                                      SelectionDAG &DAG) const {
1579   LoadSDNode *Load = cast<LoadSDNode>(Op);
1580   EVT VT = Op.getValueType();
1581   SDValue BasePtr = Load->getBasePtr();
1582   EVT MemVT = Load->getMemoryVT();
1583   SDLoc SL(Op);
1584   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1585   unsigned BaseAlign = Load->getAlignment();
1586   unsigned NumElements = MemVT.getVectorNumElements();
1587 
1588   // Widen from vec3 to vec4 when the load is at least 8-byte aligned
1589   // or 16-byte fully dereferenceable. Otherwise, split the vector load.
1590   if (NumElements != 3 ||
1591       (BaseAlign < 8 &&
1592        !SrcValue.isDereferenceable(16, *DAG.getContext(), DAG.getDataLayout())))
1593     return SplitVectorLoad(Op, DAG);
1594 
1595   assert(NumElements == 3);
1596 
1597   EVT WideVT =
1598       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
1599   EVT WideMemVT =
1600       EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 4);
1601   SDValue WideLoad = DAG.getExtLoad(
1602       Load->getExtensionType(), SL, WideVT, Load->getChain(), BasePtr, SrcValue,
1603       WideMemVT, BaseAlign, Load->getMemOperand()->getFlags());
1604   return DAG.getMergeValues(
1605       {DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, VT, WideLoad,
1606                    DAG.getVectorIdxConstant(0, SL)),
1607        WideLoad.getValue(1)},
1608       SL);
1609 }
1610 
1611 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1612                                                SelectionDAG &DAG) const {
1613   StoreSDNode *Store = cast<StoreSDNode>(Op);
1614   SDValue Val = Store->getValue();
1615   EVT VT = Val.getValueType();
1616 
1617   // If this is a 2 element vector, we really want to scalarize and not create
1618   // weird 1 element vectors.
1619   if (VT.getVectorNumElements() == 2)
1620     return scalarizeVectorStore(Store, DAG);
1621 
1622   EVT MemVT = Store->getMemoryVT();
1623   SDValue Chain = Store->getChain();
1624   SDValue BasePtr = Store->getBasePtr();
1625   SDLoc SL(Op);
1626 
1627   EVT LoVT, HiVT;
1628   EVT LoMemVT, HiMemVT;
1629   SDValue Lo, Hi;
1630 
1631   std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1632   std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1633   std::tie(Lo, Hi) = splitVector(Val, SL, LoVT, HiVT, DAG);
1634 
1635   SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, LoMemVT.getStoreSize());
1636 
1637   const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1638   unsigned BaseAlign = Store->getAlignment();
1639   unsigned Size = LoMemVT.getStoreSize();
1640   unsigned HiAlign = MinAlign(BaseAlign, Size);
1641 
1642   SDValue LoStore =
1643       DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1644                         Store->getMemOperand()->getFlags());
1645   SDValue HiStore =
1646       DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1647                         HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1648 
1649   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1650 }
1651 
1652 // This is a shortcut for integer division because we have fast i32<->f32
1653 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1654 // float is enough to accurately represent up to a 24-bit signed integer.
1655 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG,
1656                                             bool Sign) const {
1657   SDLoc DL(Op);
1658   EVT VT = Op.getValueType();
1659   SDValue LHS = Op.getOperand(0);
1660   SDValue RHS = Op.getOperand(1);
1661   MVT IntVT = MVT::i32;
1662   MVT FltVT = MVT::f32;
1663 
1664   unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1665   if (LHSSignBits < 9)
1666     return SDValue();
1667 
1668   unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1669   if (RHSSignBits < 9)
1670     return SDValue();
1671 
1672   unsigned BitSize = VT.getSizeInBits();
1673   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1674   unsigned DivBits = BitSize - SignBits;
1675   if (Sign)
1676     ++DivBits;
1677 
1678   ISD::NodeType ToFp = Sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1679   ISD::NodeType ToInt = Sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1680 
1681   SDValue jq = DAG.getConstant(1, DL, IntVT);
1682 
1683   if (Sign) {
1684     // char|short jq = ia ^ ib;
1685     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1686 
1687     // jq = jq >> (bitsize - 2)
1688     jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1689                      DAG.getConstant(BitSize - 2, DL, VT));
1690 
1691     // jq = jq | 0x1
1692     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1693   }
1694 
1695   // int ia = (int)LHS;
1696   SDValue ia = LHS;
1697 
1698   // int ib, (int)RHS;
1699   SDValue ib = RHS;
1700 
1701   // float fa = (float)ia;
1702   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1703 
1704   // float fb = (float)ib;
1705   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1706 
1707   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1708                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1709 
1710   // fq = trunc(fq);
1711   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1712 
1713   // float fqneg = -fq;
1714   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1715 
1716   MachineFunction &MF = DAG.getMachineFunction();
1717   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
1718 
1719   // float fr = mad(fqneg, fb, fa);
1720   unsigned OpCode = !Subtarget->hasMadMacF32Insts() ?
1721                     (unsigned)ISD::FMA :
1722                     !MFI->getMode().allFP32Denormals() ?
1723                     (unsigned)ISD::FMAD :
1724                     (unsigned)AMDGPUISD::FMAD_FTZ;
1725   SDValue fr = DAG.getNode(OpCode, DL, FltVT, fqneg, fb, fa);
1726 
1727   // int iq = (int)fq;
1728   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1729 
1730   // fr = fabs(fr);
1731   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1732 
1733   // fb = fabs(fb);
1734   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1735 
1736   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1737 
1738   // int cv = fr >= fb;
1739   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1740 
1741   // jq = (cv ? jq : 0);
1742   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1743 
1744   // dst = iq + jq;
1745   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1746 
1747   // Rem needs compensation, it's easier to recompute it
1748   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1749   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1750 
1751   // Truncate to number of bits this divide really is.
1752   if (Sign) {
1753     SDValue InRegSize
1754       = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1755     Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1756     Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1757   } else {
1758     SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1759     Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1760     Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1761   }
1762 
1763   return DAG.getMergeValues({ Div, Rem }, DL);
1764 }
1765 
1766 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1767                                       SelectionDAG &DAG,
1768                                       SmallVectorImpl<SDValue> &Results) const {
1769   SDLoc DL(Op);
1770   EVT VT = Op.getValueType();
1771 
1772   assert(VT == MVT::i64 && "LowerUDIVREM64 expects an i64");
1773 
1774   EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1775 
1776   SDValue One = DAG.getConstant(1, DL, HalfVT);
1777   SDValue Zero = DAG.getConstant(0, DL, HalfVT);
1778 
1779   //HiLo split
1780   SDValue LHS = Op.getOperand(0);
1781   SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1782   SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, One);
1783 
1784   SDValue RHS = Op.getOperand(1);
1785   SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1786   SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, One);
1787 
1788   if (DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1789       DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1790 
1791     SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1792                               LHS_Lo, RHS_Lo);
1793 
1794     SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), Zero});
1795     SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), Zero});
1796 
1797     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1798     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1799     return;
1800   }
1801 
1802   if (isTypeLegal(MVT::i64)) {
1803     MachineFunction &MF = DAG.getMachineFunction();
1804     const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1805 
1806     // Compute denominator reciprocal.
1807     unsigned FMAD = !Subtarget->hasMadMacF32Insts() ?
1808                     (unsigned)ISD::FMA :
1809                     !MFI->getMode().allFP32Denormals() ?
1810                     (unsigned)ISD::FMAD :
1811                     (unsigned)AMDGPUISD::FMAD_FTZ;
1812 
1813     SDValue Cvt_Lo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Lo);
1814     SDValue Cvt_Hi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Hi);
1815     SDValue Mad1 = DAG.getNode(FMAD, DL, MVT::f32, Cvt_Hi,
1816       DAG.getConstantFP(APInt(32, 0x4f800000).bitsToFloat(), DL, MVT::f32),
1817       Cvt_Lo);
1818     SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, DL, MVT::f32, Mad1);
1819     SDValue Mul1 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Rcp,
1820       DAG.getConstantFP(APInt(32, 0x5f7ffffc).bitsToFloat(), DL, MVT::f32));
1821     SDValue Mul2 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Mul1,
1822       DAG.getConstantFP(APInt(32, 0x2f800000).bitsToFloat(), DL, MVT::f32));
1823     SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, MVT::f32, Mul2);
1824     SDValue Mad2 = DAG.getNode(FMAD, DL, MVT::f32, Trunc,
1825       DAG.getConstantFP(APInt(32, 0xcf800000).bitsToFloat(), DL, MVT::f32),
1826       Mul1);
1827     SDValue Rcp_Lo = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Mad2);
1828     SDValue Rcp_Hi = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Trunc);
1829     SDValue Rcp64 = DAG.getBitcast(VT,
1830                         DAG.getBuildVector(MVT::v2i32, DL, {Rcp_Lo, Rcp_Hi}));
1831 
1832     SDValue Zero64 = DAG.getConstant(0, DL, VT);
1833     SDValue One64  = DAG.getConstant(1, DL, VT);
1834     SDValue Zero1 = DAG.getConstant(0, DL, MVT::i1);
1835     SDVTList HalfCarryVT = DAG.getVTList(HalfVT, MVT::i1);
1836 
1837     SDValue Neg_RHS = DAG.getNode(ISD::SUB, DL, VT, Zero64, RHS);
1838     SDValue Mullo1 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Rcp64);
1839     SDValue Mulhi1 = DAG.getNode(ISD::MULHU, DL, VT, Rcp64, Mullo1);
1840     SDValue Mulhi1_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1841                                     Zero);
1842     SDValue Mulhi1_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1843                                     One);
1844 
1845     SDValue Add1_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Lo,
1846                                   Mulhi1_Lo, Zero1);
1847     SDValue Add1_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Hi,
1848                                   Mulhi1_Hi, Add1_Lo.getValue(1));
1849     SDValue Add1_HiNc = DAG.getNode(ISD::ADD, DL, HalfVT, Rcp_Hi, Mulhi1_Hi);
1850     SDValue Add1 = DAG.getBitcast(VT,
1851                         DAG.getBuildVector(MVT::v2i32, DL, {Add1_Lo, Add1_Hi}));
1852 
1853     SDValue Mullo2 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Add1);
1854     SDValue Mulhi2 = DAG.getNode(ISD::MULHU, DL, VT, Add1, Mullo2);
1855     SDValue Mulhi2_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1856                                     Zero);
1857     SDValue Mulhi2_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1858                                     One);
1859 
1860     SDValue Add2_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_Lo,
1861                                   Mulhi2_Lo, Zero1);
1862     SDValue Add2_HiC = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_HiNc,
1863                                    Mulhi2_Hi, Add1_Lo.getValue(1));
1864     SDValue Add2_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add2_HiC,
1865                                   Zero, Add2_Lo.getValue(1));
1866     SDValue Add2 = DAG.getBitcast(VT,
1867                         DAG.getBuildVector(MVT::v2i32, DL, {Add2_Lo, Add2_Hi}));
1868     SDValue Mulhi3 = DAG.getNode(ISD::MULHU, DL, VT, LHS, Add2);
1869 
1870     SDValue Mul3 = DAG.getNode(ISD::MUL, DL, VT, RHS, Mulhi3);
1871 
1872     SDValue Mul3_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, Zero);
1873     SDValue Mul3_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, One);
1874     SDValue Sub1_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Lo,
1875                                   Mul3_Lo, Zero1);
1876     SDValue Sub1_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Hi,
1877                                   Mul3_Hi, Sub1_Lo.getValue(1));
1878     SDValue Sub1_Mi = DAG.getNode(ISD::SUB, DL, HalfVT, LHS_Hi, Mul3_Hi);
1879     SDValue Sub1 = DAG.getBitcast(VT,
1880                         DAG.getBuildVector(MVT::v2i32, DL, {Sub1_Lo, Sub1_Hi}));
1881 
1882     SDValue MinusOne = DAG.getConstant(0xffffffffu, DL, HalfVT);
1883     SDValue C1 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, MinusOne, Zero,
1884                                  ISD::SETUGE);
1885     SDValue C2 = DAG.getSelectCC(DL, Sub1_Lo, RHS_Lo, MinusOne, Zero,
1886                                  ISD::SETUGE);
1887     SDValue C3 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, C2, C1, ISD::SETEQ);
1888 
1889     // TODO: Here and below portions of the code can be enclosed into if/endif.
1890     // Currently control flow is unconditional and we have 4 selects after
1891     // potential endif to substitute PHIs.
1892 
1893     // if C3 != 0 ...
1894     SDValue Sub2_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Lo,
1895                                   RHS_Lo, Zero1);
1896     SDValue Sub2_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Mi,
1897                                   RHS_Hi, Sub1_Lo.getValue(1));
1898     SDValue Sub2_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1899                                   Zero, Sub2_Lo.getValue(1));
1900     SDValue Sub2 = DAG.getBitcast(VT,
1901                         DAG.getBuildVector(MVT::v2i32, DL, {Sub2_Lo, Sub2_Hi}));
1902 
1903     SDValue Add3 = DAG.getNode(ISD::ADD, DL, VT, Mulhi3, One64);
1904 
1905     SDValue C4 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, MinusOne, Zero,
1906                                  ISD::SETUGE);
1907     SDValue C5 = DAG.getSelectCC(DL, Sub2_Lo, RHS_Lo, MinusOne, Zero,
1908                                  ISD::SETUGE);
1909     SDValue C6 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, C5, C4, ISD::SETEQ);
1910 
1911     // if (C6 != 0)
1912     SDValue Add4 = DAG.getNode(ISD::ADD, DL, VT, Add3, One64);
1913 
1914     SDValue Sub3_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Lo,
1915                                   RHS_Lo, Zero1);
1916     SDValue Sub3_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1917                                   RHS_Hi, Sub2_Lo.getValue(1));
1918     SDValue Sub3_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub3_Mi,
1919                                   Zero, Sub3_Lo.getValue(1));
1920     SDValue Sub3 = DAG.getBitcast(VT,
1921                         DAG.getBuildVector(MVT::v2i32, DL, {Sub3_Lo, Sub3_Hi}));
1922 
1923     // endif C6
1924     // endif C3
1925 
1926     SDValue Sel1 = DAG.getSelectCC(DL, C6, Zero, Add4, Add3, ISD::SETNE);
1927     SDValue Div  = DAG.getSelectCC(DL, C3, Zero, Sel1, Mulhi3, ISD::SETNE);
1928 
1929     SDValue Sel2 = DAG.getSelectCC(DL, C6, Zero, Sub3, Sub2, ISD::SETNE);
1930     SDValue Rem  = DAG.getSelectCC(DL, C3, Zero, Sel2, Sub1, ISD::SETNE);
1931 
1932     Results.push_back(Div);
1933     Results.push_back(Rem);
1934 
1935     return;
1936   }
1937 
1938   // r600 expandion.
1939   // Get Speculative values
1940   SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1941   SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1942 
1943   SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, Zero, REM_Part, LHS_Hi, ISD::SETEQ);
1944   SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, Zero});
1945   REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1946 
1947   SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, Zero, DIV_Part, Zero, ISD::SETEQ);
1948   SDValue DIV_Lo = Zero;
1949 
1950   const unsigned halfBitWidth = HalfVT.getSizeInBits();
1951 
1952   for (unsigned i = 0; i < halfBitWidth; ++i) {
1953     const unsigned bitPos = halfBitWidth - i - 1;
1954     SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1955     // Get value of high bit
1956     SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1957     HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, One);
1958     HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1959 
1960     // Shift
1961     REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1962     // Add LHS high bit
1963     REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1964 
1965     SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1966     SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, Zero, ISD::SETUGE);
1967 
1968     DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1969 
1970     // Update REM
1971     SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1972     REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1973   }
1974 
1975   SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1976   DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1977   Results.push_back(DIV);
1978   Results.push_back(REM);
1979 }
1980 
1981 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1982                                            SelectionDAG &DAG) const {
1983   SDLoc DL(Op);
1984   EVT VT = Op.getValueType();
1985 
1986   if (VT == MVT::i64) {
1987     SmallVector<SDValue, 2> Results;
1988     LowerUDIVREM64(Op, DAG, Results);
1989     return DAG.getMergeValues(Results, DL);
1990   }
1991 
1992   if (VT == MVT::i32) {
1993     if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1994       return Res;
1995   }
1996 
1997   SDValue X = Op.getOperand(0);
1998   SDValue Y = Op.getOperand(1);
1999 
2000   // See AMDGPUCodeGenPrepare::expandDivRem32 for a description of the
2001   // algorithm used here.
2002 
2003   // Initial estimate of inv(y).
2004   SDValue Z = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Y);
2005 
2006   // One round of UNR.
2007   SDValue NegY = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Y);
2008   SDValue NegYZ = DAG.getNode(ISD::MUL, DL, VT, NegY, Z);
2009   Z = DAG.getNode(ISD::ADD, DL, VT, Z,
2010                   DAG.getNode(ISD::MULHU, DL, VT, Z, NegYZ));
2011 
2012   // Quotient/remainder estimate.
2013   SDValue Q = DAG.getNode(ISD::MULHU, DL, VT, X, Z);
2014   SDValue R =
2015       DAG.getNode(ISD::SUB, DL, VT, X, DAG.getNode(ISD::MUL, DL, VT, Q, Y));
2016 
2017   // First quotient/remainder refinement.
2018   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2019   SDValue One = DAG.getConstant(1, DL, VT);
2020   SDValue Cond = DAG.getSetCC(DL, CCVT, R, Y, ISD::SETUGE);
2021   Q = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2022                   DAG.getNode(ISD::ADD, DL, VT, Q, One), Q);
2023   R = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2024                   DAG.getNode(ISD::SUB, DL, VT, R, Y), R);
2025 
2026   // Second quotient/remainder refinement.
2027   Cond = DAG.getSetCC(DL, CCVT, R, Y, ISD::SETUGE);
2028   Q = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2029                   DAG.getNode(ISD::ADD, DL, VT, Q, One), Q);
2030   R = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2031                   DAG.getNode(ISD::SUB, DL, VT, R, Y), R);
2032 
2033   return DAG.getMergeValues({Q, R}, DL);
2034 }
2035 
2036 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
2037                                            SelectionDAG &DAG) const {
2038   SDLoc DL(Op);
2039   EVT VT = Op.getValueType();
2040 
2041   SDValue LHS = Op.getOperand(0);
2042   SDValue RHS = Op.getOperand(1);
2043 
2044   SDValue Zero = DAG.getConstant(0, DL, VT);
2045   SDValue NegOne = DAG.getConstant(-1, DL, VT);
2046 
2047   if (VT == MVT::i32) {
2048     if (SDValue Res = LowerDIVREM24(Op, DAG, true))
2049       return Res;
2050   }
2051 
2052   if (VT == MVT::i64 &&
2053       DAG.ComputeNumSignBits(LHS) > 32 &&
2054       DAG.ComputeNumSignBits(RHS) > 32) {
2055     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
2056 
2057     //HiLo split
2058     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
2059     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
2060     SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
2061                                  LHS_Lo, RHS_Lo);
2062     SDValue Res[2] = {
2063       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
2064       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
2065     };
2066     return DAG.getMergeValues(Res, DL);
2067   }
2068 
2069   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
2070   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
2071   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
2072   SDValue RSign = LHSign; // Remainder sign is the same as LHS
2073 
2074   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
2075   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
2076 
2077   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
2078   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
2079 
2080   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
2081   SDValue Rem = Div.getValue(1);
2082 
2083   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
2084   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
2085 
2086   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
2087   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
2088 
2089   SDValue Res[2] = {
2090     Div,
2091     Rem
2092   };
2093   return DAG.getMergeValues(Res, DL);
2094 }
2095 
2096 // (frem x, y) -> (fma (fneg (ftrunc (fdiv x, y))), y, x)
2097 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
2098   SDLoc SL(Op);
2099   EVT VT = Op.getValueType();
2100   auto Flags = Op->getFlags();
2101   SDValue X = Op.getOperand(0);
2102   SDValue Y = Op.getOperand(1);
2103 
2104   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y, Flags);
2105   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, VT, Div, Flags);
2106   SDValue Neg = DAG.getNode(ISD::FNEG, SL, VT, Trunc, Flags);
2107   // TODO: For f32 use FMAD instead if !hasFastFMA32?
2108   return DAG.getNode(ISD::FMA, SL, VT, Neg, Y, X, Flags);
2109 }
2110 
2111 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
2112   SDLoc SL(Op);
2113   SDValue Src = Op.getOperand(0);
2114 
2115   // result = trunc(src)
2116   // if (src > 0.0 && src != result)
2117   //   result += 1.0
2118 
2119   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2120 
2121   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2122   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
2123 
2124   EVT SetCCVT =
2125       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2126 
2127   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
2128   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2129   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2130 
2131   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
2132   // TODO: Should this propagate fast-math-flags?
2133   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2134 }
2135 
2136 static SDValue extractF64Exponent(SDValue Hi, const SDLoc &SL,
2137                                   SelectionDAG &DAG) {
2138   const unsigned FractBits = 52;
2139   const unsigned ExpBits = 11;
2140 
2141   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
2142                                 Hi,
2143                                 DAG.getConstant(FractBits - 32, SL, MVT::i32),
2144                                 DAG.getConstant(ExpBits, SL, MVT::i32));
2145   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
2146                             DAG.getConstant(1023, SL, MVT::i32));
2147 
2148   return Exp;
2149 }
2150 
2151 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
2152   SDLoc SL(Op);
2153   SDValue Src = Op.getOperand(0);
2154 
2155   assert(Op.getValueType() == MVT::f64);
2156 
2157   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2158   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2159 
2160   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2161 
2162   // Extract the upper half, since this is where we will find the sign and
2163   // exponent.
2164   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
2165 
2166   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2167 
2168   const unsigned FractBits = 52;
2169 
2170   // Extract the sign bit.
2171   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
2172   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
2173 
2174   // Extend back to 64-bits.
2175   SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
2176   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
2177 
2178   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
2179   const SDValue FractMask
2180     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
2181 
2182   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
2183   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
2184   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
2185 
2186   EVT SetCCVT =
2187       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
2188 
2189   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
2190 
2191   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2192   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2193 
2194   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
2195   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
2196 
2197   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
2198 }
2199 
2200 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
2201   SDLoc SL(Op);
2202   SDValue Src = Op.getOperand(0);
2203 
2204   assert(Op.getValueType() == MVT::f64);
2205 
2206   APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
2207   SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
2208   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
2209 
2210   // TODO: Should this propagate fast-math-flags?
2211 
2212   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
2213   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
2214 
2215   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
2216 
2217   APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
2218   SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
2219 
2220   EVT SetCCVT =
2221       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2222   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
2223 
2224   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
2225 }
2226 
2227 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
2228   // FNEARBYINT and FRINT are the same, except in their handling of FP
2229   // exceptions. Those aren't really meaningful for us, and OpenCL only has
2230   // rint, so just treat them as equivalent.
2231   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
2232 }
2233 
2234 // XXX - May require not supporting f32 denormals?
2235 
2236 // Don't handle v2f16. The extra instructions to scalarize and repack around the
2237 // compare and vselect end up producing worse code than scalarizing the whole
2238 // operation.
2239 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2240   SDLoc SL(Op);
2241   SDValue X = Op.getOperand(0);
2242   EVT VT = Op.getValueType();
2243 
2244   SDValue T = DAG.getNode(ISD::FTRUNC, SL, VT, X);
2245 
2246   // TODO: Should this propagate fast-math-flags?
2247 
2248   SDValue Diff = DAG.getNode(ISD::FSUB, SL, VT, X, T);
2249 
2250   SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, VT, Diff);
2251 
2252   const SDValue Zero = DAG.getConstantFP(0.0, SL, VT);
2253   const SDValue One = DAG.getConstantFP(1.0, SL, VT);
2254   const SDValue Half = DAG.getConstantFP(0.5, SL, VT);
2255 
2256   SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, VT, One, X);
2257 
2258   EVT SetCCVT =
2259       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2260 
2261   SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
2262 
2263   SDValue Sel = DAG.getNode(ISD::SELECT, SL, VT, Cmp, SignOne, Zero);
2264 
2265   return DAG.getNode(ISD::FADD, SL, VT, T, Sel);
2266 }
2267 
2268 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
2269   SDLoc SL(Op);
2270   SDValue Src = Op.getOperand(0);
2271 
2272   // result = trunc(src);
2273   // if (src < 0.0 && src != result)
2274   //   result += -1.0.
2275 
2276   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2277 
2278   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2279   const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
2280 
2281   EVT SetCCVT =
2282       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2283 
2284   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
2285   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2286   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2287 
2288   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
2289   // TODO: Should this propagate fast-math-flags?
2290   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2291 }
2292 
2293 SDValue AMDGPUTargetLowering::LowerFLOG(SDValue Op, SelectionDAG &DAG,
2294                                         double Log2BaseInverted) const {
2295   EVT VT = Op.getValueType();
2296 
2297   SDLoc SL(Op);
2298   SDValue Operand = Op.getOperand(0);
2299   SDValue Log2Operand = DAG.getNode(ISD::FLOG2, SL, VT, Operand);
2300   SDValue Log2BaseInvertedOperand = DAG.getConstantFP(Log2BaseInverted, SL, VT);
2301 
2302   return DAG.getNode(ISD::FMUL, SL, VT, Log2Operand, Log2BaseInvertedOperand);
2303 }
2304 
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);
2310 
2311   const SDValue K = DAG.getConstantFP(numbers::log2e, 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());
2314 }
2315 
2316 static bool isCtlzOpc(unsigned Opc) {
2317   return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2318 }
2319 
2320 static bool isCttzOpc(unsigned Opc) {
2321   return Opc == ISD::CTTZ || Opc == ISD::CTTZ_ZERO_UNDEF;
2322 }
2323 
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;
2329 
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!!!");
2339 
2340 
2341   if (ZeroUndef && Src.getValueType() == MVT::i32)
2342     return DAG.getNode(NewOpc, SL, MVT::i32, Src);
2343 
2344   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2345 
2346   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2347   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2348 
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);
2351 
2352   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2353                                    *DAG.getContext(), MVT::i32);
2354 
2355   SDValue HiOrLo = isCtlzOpc(Op.getOpcode()) ? Hi : Lo;
2356   SDValue Hi0orLo0 = DAG.getSetCC(SL, SetCCVT, HiOrLo, Zero, ISD::SETEQ);
2357 
2358   SDValue OprLo = DAG.getNode(ISDOpc, SL, MVT::i32, Lo);
2359   SDValue OprHi = DAG.getNode(ISDOpc, SL, MVT::i32, Hi);
2360 
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);
2371   }
2372 
2373   if (!ZeroUndef) {
2374     // Test if the full 64-bit input is zero.
2375 
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);
2381 
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);
2386 
2387     const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
2388 
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);
2393   }
2394 
2395   return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewOpr);
2396 }
2397 
2398 SDValue AMDGPUTargetLowering::LowerINT_TO_FP32(SDValue Op, SelectionDAG &DAG,
2399                                                bool Signed) const {
2400   // Unsigned
2401   // cul2f(ulong u)
2402   //{
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);
2410   //}
2411   // Signed
2412   // cl2f(long l)
2413   //{
2414   //  long s = l >> 63;
2415   //  float r = cul2f((l + s) ^ s);
2416   //  return s ? -r : r;
2417   //}
2418 
2419   SDLoc SL(Op);
2420   SDValue Src = Op.getOperand(0);
2421   SDValue L = Src;
2422 
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);
2427 
2428     SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
2429     L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
2430   }
2431 
2432   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2433                                    *DAG.getContext(), MVT::f32);
2434 
2435 
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);
2440 
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);
2446 
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));
2450 
2451   SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
2452                           DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
2453 
2454   SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
2455                              U, DAG.getConstant(40, SL, MVT::i64));
2456 
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));
2460 
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);
2464 
2465   SDValue One = DAG.getConstant(1, SL, MVT::i32);
2466 
2467   SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
2468 
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);
2475 
2476   if (!Signed)
2477     return R;
2478 
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);
2481 }
2482 
2483 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
2484                                                bool Signed) const {
2485   SDLoc SL(Op);
2486   SDValue Src = Op.getOperand(0);
2487 
2488   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2489 
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));
2494 
2495   SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2496                               SL, MVT::f64, Hi);
2497 
2498   SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2499 
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);
2504 }
2505 
2506 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
2507                                                SelectionDAG &DAG) const {
2508   // TODO: Factor out code common with LowerSINT_TO_FP.
2509   EVT DestVT = Op.getValueType();
2510   SDValue Src = Op.getOperand(0);
2511   EVT SrcVT = Src.getValueType();
2512 
2513   if (SrcVT == MVT::i16) {
2514     if (DestVT == MVT::f16)
2515       return Op;
2516     SDLoc DL(Op);
2517 
2518     // Promote src to i32
2519     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Src);
2520     return DAG.getNode(ISD::UINT_TO_FP, DL, DestVT, Ext);
2521   }
2522 
2523   assert(SrcVT == MVT::i64 && "operation should be legal");
2524 
2525   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2526     SDLoc DL(Op);
2527 
2528     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2529     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2530     SDValue FPRound =
2531         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2532 
2533     return FPRound;
2534   }
2535 
2536   if (DestVT == MVT::f32)
2537     return LowerINT_TO_FP32(Op, DAG, false);
2538 
2539   assert(DestVT == MVT::f64);
2540   return LowerINT_TO_FP64(Op, DAG, false);
2541 }
2542 
2543 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
2544                                               SelectionDAG &DAG) const {
2545   EVT DestVT = Op.getValueType();
2546 
2547   SDValue Src = Op.getOperand(0);
2548   EVT SrcVT = Src.getValueType();
2549 
2550   if (SrcVT == MVT::i16) {
2551     if (DestVT == MVT::f16)
2552       return Op;
2553 
2554     SDLoc DL(Op);
2555     // Promote src to i32
2556     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32, Src);
2557     return DAG.getNode(ISD::SINT_TO_FP, DL, DestVT, Ext);
2558   }
2559 
2560   assert(SrcVT == MVT::i64 && "operation should be legal");
2561 
2562   // TODO: Factor out code common with LowerUINT_TO_FP.
2563 
2564   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2565     SDLoc DL(Op);
2566     SDValue Src = Op.getOperand(0);
2567 
2568     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2569     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2570     SDValue FPRound =
2571         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2572 
2573     return FPRound;
2574   }
2575 
2576   if (DestVT == MVT::f32)
2577     return LowerINT_TO_FP32(Op, DAG, true);
2578 
2579   assert(DestVT == MVT::f64);
2580   return LowerINT_TO_FP64(Op, DAG, true);
2581 }
2582 
2583 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2584                                                bool Signed) const {
2585   SDLoc SL(Op);
2586 
2587   SDValue Src = Op.getOperand(0);
2588 
2589   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2590 
2591   SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2592                                  MVT::f64);
2593   SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2594                                  MVT::f64);
2595   // TODO: Should this propagate fast-math-flags?
2596   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2597 
2598   SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2599 
2600 
2601   SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2602 
2603   SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2604                            MVT::i32, FloorMul);
2605   SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2606 
2607   SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2608 
2609   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2610 }
2611 
2612 SDValue AMDGPUTargetLowering::LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) const {
2613   SDLoc DL(Op);
2614   SDValue N0 = Op.getOperand(0);
2615 
2616   // Convert to target node to get known bits
2617   if (N0.getValueType() == MVT::f32)
2618     return DAG.getNode(AMDGPUISD::FP_TO_FP16, DL, Op.getValueType(), N0);
2619 
2620   if (getTargetMachine().Options.UnsafeFPMath) {
2621     // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2622     return SDValue();
2623   }
2624 
2625   assert(N0.getSimpleValueType() == MVT::f64);
2626 
2627   // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2628   const unsigned ExpMask = 0x7ff;
2629   const unsigned ExpBiasf64 = 1023;
2630   const unsigned ExpBiasf16 = 15;
2631   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2632   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2633   SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2634   SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2635                            DAG.getConstant(32, DL, MVT::i64));
2636   UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2637   U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2638   SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2639                           DAG.getConstant(20, DL, MVT::i64));
2640   E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2641                   DAG.getConstant(ExpMask, DL, MVT::i32));
2642   // Subtract the fp64 exponent bias (1023) to get the real exponent and
2643   // add the f16 bias (15) to get the biased exponent for the f16 format.
2644   E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2645                   DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2646 
2647   SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2648                           DAG.getConstant(8, DL, MVT::i32));
2649   M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2650                   DAG.getConstant(0xffe, DL, MVT::i32));
2651 
2652   SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2653                                   DAG.getConstant(0x1ff, DL, MVT::i32));
2654   MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2655 
2656   SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2657   M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2658 
2659   // (M != 0 ? 0x0200 : 0) | 0x7c00;
2660   SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2661       DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2662                       Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2663 
2664   // N = M | (E << 12);
2665   SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2666       DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2667                   DAG.getConstant(12, DL, MVT::i32)));
2668 
2669   // B = clamp(1-E, 0, 13);
2670   SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2671                                   One, E);
2672   SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2673   B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2674                   DAG.getConstant(13, DL, MVT::i32));
2675 
2676   SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2677                                    DAG.getConstant(0x1000, DL, MVT::i32));
2678 
2679   SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2680   SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2681   SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2682   D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2683 
2684   SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2685   SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2686                               DAG.getConstant(0x7, DL, MVT::i32));
2687   V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2688                   DAG.getConstant(2, DL, MVT::i32));
2689   SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2690                                One, Zero, ISD::SETEQ);
2691   SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2692                                One, Zero, ISD::SETGT);
2693   V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2694   V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2695 
2696   V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2697                       DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2698   V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2699                       I, V, ISD::SETEQ);
2700 
2701   // Extract the sign bit.
2702   SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2703                             DAG.getConstant(16, DL, MVT::i32));
2704   Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2705                      DAG.getConstant(0x8000, DL, MVT::i32));
2706 
2707   V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2708   return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2709 }
2710 
2711 SDValue AMDGPUTargetLowering::LowerFP_TO_INT(SDValue Op,
2712                                              SelectionDAG &DAG) const {
2713   SDValue Src = Op.getOperand(0);
2714   unsigned OpOpcode = Op.getOpcode();
2715   EVT SrcVT = Src.getValueType();
2716   EVT DestVT = Op.getValueType();
2717 
2718   // Will be selected natively
2719   if (SrcVT == MVT::f16 && DestVT == MVT::i16)
2720     return Op;
2721 
2722   // Promote i16 to i32
2723   if (DestVT == MVT::i16 && (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
2724     SDLoc DL(Op);
2725 
2726     SDValue FpToInt32 = DAG.getNode(OpOpcode, DL, MVT::i32, Src);
2727     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToInt32);
2728   }
2729 
2730   if (SrcVT == MVT::f16 ||
2731       (SrcVT == MVT::f32 && Src.getOpcode() == ISD::FP16_TO_FP)) {
2732     SDLoc DL(Op);
2733 
2734     SDValue FpToInt32 = DAG.getNode(OpOpcode, DL, MVT::i32, Src);
2735     unsigned Ext =
2736         OpOpcode == ISD::FP_TO_SINT ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2737     return DAG.getNode(Ext, DL, MVT::i64, FpToInt32);
2738   }
2739 
2740   if (DestVT == MVT::i64 && SrcVT == MVT::f64)
2741     return LowerFP64_TO_INT(Op, DAG, OpOpcode == ISD::FP_TO_SINT);
2742 
2743   return SDValue();
2744 }
2745 
2746 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2747                                                      SelectionDAG &DAG) const {
2748   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2749   MVT VT = Op.getSimpleValueType();
2750   MVT ScalarVT = VT.getScalarType();
2751 
2752   assert(VT.isVector());
2753 
2754   SDValue Src = Op.getOperand(0);
2755   SDLoc DL(Op);
2756 
2757   // TODO: Don't scalarize on Evergreen?
2758   unsigned NElts = VT.getVectorNumElements();
2759   SmallVector<SDValue, 8> Args;
2760   DAG.ExtractVectorElements(Src, Args, 0, NElts);
2761 
2762   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2763   for (unsigned I = 0; I < NElts; ++I)
2764     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2765 
2766   return DAG.getBuildVector(VT, DL, Args);
2767 }
2768 
2769 //===----------------------------------------------------------------------===//
2770 // Custom DAG optimizations
2771 //===----------------------------------------------------------------------===//
2772 
2773 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2774   return AMDGPUTargetLowering::numBitsUnsigned(Op, DAG) <= 24;
2775 }
2776 
2777 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2778   EVT VT = Op.getValueType();
2779   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2780                                      // as unsigned 24-bit values.
2781     AMDGPUTargetLowering::numBitsSigned(Op, DAG) < 24;
2782 }
2783 
2784 static SDValue simplifyMul24(SDNode *Node24,
2785                              TargetLowering::DAGCombinerInfo &DCI) {
2786   SelectionDAG &DAG = DCI.DAG;
2787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2788   bool IsIntrin = Node24->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
2789 
2790   SDValue LHS = IsIntrin ? Node24->getOperand(1) : Node24->getOperand(0);
2791   SDValue RHS = IsIntrin ? Node24->getOperand(2) : Node24->getOperand(1);
2792   unsigned NewOpcode = Node24->getOpcode();
2793   if (IsIntrin) {
2794     unsigned IID = cast<ConstantSDNode>(Node24->getOperand(0))->getZExtValue();
2795     NewOpcode = IID == Intrinsic::amdgcn_mul_i24 ?
2796       AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2797   }
2798 
2799   APInt Demanded = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 24);
2800 
2801   // First try to simplify using SimplifyMultipleUseDemandedBits which allows
2802   // the operands to have other uses, but will only perform simplifications that
2803   // involve bypassing some nodes for this user.
2804   SDValue DemandedLHS = TLI.SimplifyMultipleUseDemandedBits(LHS, Demanded, DAG);
2805   SDValue DemandedRHS = TLI.SimplifyMultipleUseDemandedBits(RHS, Demanded, DAG);
2806   if (DemandedLHS || DemandedRHS)
2807     return DAG.getNode(NewOpcode, SDLoc(Node24), Node24->getVTList(),
2808                        DemandedLHS ? DemandedLHS : LHS,
2809                        DemandedRHS ? DemandedRHS : RHS);
2810 
2811   // Now try SimplifyDemandedBits which can simplify the nodes used by our
2812   // operands if this node is the only user.
2813   if (TLI.SimplifyDemandedBits(LHS, Demanded, DCI))
2814     return SDValue(Node24, 0);
2815   if (TLI.SimplifyDemandedBits(RHS, Demanded, DCI))
2816     return SDValue(Node24, 0);
2817 
2818   return SDValue();
2819 }
2820 
2821 template <typename IntTy>
2822 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0, uint32_t Offset,
2823                                uint32_t Width, const SDLoc &DL) {
2824   if (Width + Offset < 32) {
2825     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2826     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2827     return DAG.getConstant(Result, DL, MVT::i32);
2828   }
2829 
2830   return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2831 }
2832 
2833 static bool hasVolatileUser(SDNode *Val) {
2834   for (SDNode *U : Val->uses()) {
2835     if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2836       if (M->isVolatile())
2837         return true;
2838     }
2839   }
2840 
2841   return false;
2842 }
2843 
2844 bool AMDGPUTargetLowering::shouldCombineMemoryType(EVT VT) const {
2845   // i32 vectors are the canonical memory type.
2846   if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2847     return false;
2848 
2849   if (!VT.isByteSized())
2850     return false;
2851 
2852   unsigned Size = VT.getStoreSize();
2853 
2854   if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2855     return false;
2856 
2857   if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2858     return false;
2859 
2860   return true;
2861 }
2862 
2863 // Replace load of an illegal type with a store of a bitcast to a friendlier
2864 // type.
2865 SDValue AMDGPUTargetLowering::performLoadCombine(SDNode *N,
2866                                                  DAGCombinerInfo &DCI) const {
2867   if (!DCI.isBeforeLegalize())
2868     return SDValue();
2869 
2870   LoadSDNode *LN = cast<LoadSDNode>(N);
2871   if (!LN->isSimple() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2872     return SDValue();
2873 
2874   SDLoc SL(N);
2875   SelectionDAG &DAG = DCI.DAG;
2876   EVT VT = LN->getMemoryVT();
2877 
2878   unsigned Size = VT.getStoreSize();
2879   Align Alignment = LN->getAlign();
2880   if (Alignment < Size && isTypeLegal(VT)) {
2881     bool IsFast;
2882     unsigned AS = LN->getAddressSpace();
2883 
2884     // Expand unaligned loads earlier than legalization. Due to visitation order
2885     // problems during legalization, the emitted instructions to pack and unpack
2886     // the bytes again are not eliminated in the case of an unaligned copy.
2887     if (!allowsMisalignedMemoryAccesses(
2888             VT, AS, Alignment, LN->getMemOperand()->getFlags(), &IsFast)) {
2889       SDValue Ops[2];
2890 
2891       if (VT.isVector())
2892         std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(LN, DAG);
2893       else
2894         std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2895 
2896       return DAG.getMergeValues(Ops, SDLoc(N));
2897     }
2898 
2899     if (!IsFast)
2900       return SDValue();
2901   }
2902 
2903   if (!shouldCombineMemoryType(VT))
2904     return SDValue();
2905 
2906   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2907 
2908   SDValue NewLoad
2909     = DAG.getLoad(NewVT, SL, LN->getChain(),
2910                   LN->getBasePtr(), LN->getMemOperand());
2911 
2912   SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2913   DCI.CombineTo(N, BC, NewLoad.getValue(1));
2914   return SDValue(N, 0);
2915 }
2916 
2917 // Replace store of an illegal type with a store of a bitcast to a friendlier
2918 // type.
2919 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2920                                                   DAGCombinerInfo &DCI) const {
2921   if (!DCI.isBeforeLegalize())
2922     return SDValue();
2923 
2924   StoreSDNode *SN = cast<StoreSDNode>(N);
2925   if (!SN->isSimple() || !ISD::isNormalStore(SN))
2926     return SDValue();
2927 
2928   EVT VT = SN->getMemoryVT();
2929   unsigned Size = VT.getStoreSize();
2930 
2931   SDLoc SL(N);
2932   SelectionDAG &DAG = DCI.DAG;
2933   Align Alignment = SN->getAlign();
2934   if (Alignment < Size && isTypeLegal(VT)) {
2935     bool IsFast;
2936     unsigned AS = SN->getAddressSpace();
2937 
2938     // Expand unaligned stores earlier than legalization. Due to visitation
2939     // order problems during legalization, the emitted instructions to pack and
2940     // unpack the bytes again are not eliminated in the case of an unaligned
2941     // copy.
2942     if (!allowsMisalignedMemoryAccesses(
2943             VT, AS, Alignment, SN->getMemOperand()->getFlags(), &IsFast)) {
2944       if (VT.isVector())
2945         return scalarizeVectorStore(SN, DAG);
2946 
2947       return expandUnalignedStore(SN, DAG);
2948     }
2949 
2950     if (!IsFast)
2951       return SDValue();
2952   }
2953 
2954   if (!shouldCombineMemoryType(VT))
2955     return SDValue();
2956 
2957   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2958   SDValue Val = SN->getValue();
2959 
2960   //DCI.AddToWorklist(Val.getNode());
2961 
2962   bool OtherUses = !Val.hasOneUse();
2963   SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2964   if (OtherUses) {
2965     SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
2966     DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
2967   }
2968 
2969   return DAG.getStore(SN->getChain(), SL, CastVal,
2970                       SN->getBasePtr(), SN->getMemOperand());
2971 }
2972 
2973 // FIXME: This should go in generic DAG combiner with an isTruncateFree check,
2974 // but isTruncateFree is inaccurate for i16 now because of SALU vs. VALU
2975 // issues.
2976 SDValue AMDGPUTargetLowering::performAssertSZExtCombine(SDNode *N,
2977                                                         DAGCombinerInfo &DCI) const {
2978   SelectionDAG &DAG = DCI.DAG;
2979   SDValue N0 = N->getOperand(0);
2980 
2981   // (vt2 (assertzext (truncate vt0:x), vt1)) ->
2982   //     (vt2 (truncate (assertzext vt0:x, vt1)))
2983   if (N0.getOpcode() == ISD::TRUNCATE) {
2984     SDValue N1 = N->getOperand(1);
2985     EVT ExtVT = cast<VTSDNode>(N1)->getVT();
2986     SDLoc SL(N);
2987 
2988     SDValue Src = N0.getOperand(0);
2989     EVT SrcVT = Src.getValueType();
2990     if (SrcVT.bitsGE(ExtVT)) {
2991       SDValue NewInReg = DAG.getNode(N->getOpcode(), SL, SrcVT, Src, N1);
2992       return DAG.getNode(ISD::TRUNCATE, SL, N->getValueType(0), NewInReg);
2993     }
2994   }
2995 
2996   return SDValue();
2997 }
2998 
2999 SDValue AMDGPUTargetLowering::performIntrinsicWOChainCombine(
3000   SDNode *N, DAGCombinerInfo &DCI) const {
3001   unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3002   switch (IID) {
3003   case Intrinsic::amdgcn_mul_i24:
3004   case Intrinsic::amdgcn_mul_u24:
3005     return simplifyMul24(N, DCI);
3006   case Intrinsic::amdgcn_fract:
3007   case Intrinsic::amdgcn_rsq:
3008   case Intrinsic::amdgcn_rcp_legacy:
3009   case Intrinsic::amdgcn_rsq_legacy:
3010   case Intrinsic::amdgcn_rsq_clamp:
3011   case Intrinsic::amdgcn_ldexp: {
3012     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
3013     SDValue Src = N->getOperand(1);
3014     return Src.isUndef() ? Src : SDValue();
3015   }
3016   default:
3017     return SDValue();
3018   }
3019 }
3020 
3021 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
3022 /// binary operation \p Opc to it with the corresponding constant operands.
3023 SDValue AMDGPUTargetLowering::splitBinaryBitConstantOpImpl(
3024   DAGCombinerInfo &DCI, const SDLoc &SL,
3025   unsigned Opc, SDValue LHS,
3026   uint32_t ValLo, uint32_t ValHi) const {
3027   SelectionDAG &DAG = DCI.DAG;
3028   SDValue Lo, Hi;
3029   std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
3030 
3031   SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
3032   SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
3033 
3034   SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
3035   SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
3036 
3037   // Re-visit the ands. It's possible we eliminated one of them and it could
3038   // simplify the vector.
3039   DCI.AddToWorklist(Lo.getNode());
3040   DCI.AddToWorklist(Hi.getNode());
3041 
3042   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
3043   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3044 }
3045 
3046 SDValue AMDGPUTargetLowering::performShlCombine(SDNode *N,
3047                                                 DAGCombinerInfo &DCI) const {
3048   EVT VT = N->getValueType(0);
3049 
3050   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3051   if (!RHS)
3052     return SDValue();
3053 
3054   SDValue LHS = N->getOperand(0);
3055   unsigned RHSVal = RHS->getZExtValue();
3056   if (!RHSVal)
3057     return LHS;
3058 
3059   SDLoc SL(N);
3060   SelectionDAG &DAG = DCI.DAG;
3061 
3062   switch (LHS->getOpcode()) {
3063   default:
3064     break;
3065   case ISD::ZERO_EXTEND:
3066   case ISD::SIGN_EXTEND:
3067   case ISD::ANY_EXTEND: {
3068     SDValue X = LHS->getOperand(0);
3069 
3070     if (VT == MVT::i32 && RHSVal == 16 && X.getValueType() == MVT::i16 &&
3071         isOperationLegal(ISD::BUILD_VECTOR, MVT::v2i16)) {
3072       // Prefer build_vector as the canonical form if packed types are legal.
3073       // (shl ([asz]ext i16:x), 16 -> build_vector 0, x
3074       SDValue Vec = DAG.getBuildVector(MVT::v2i16, SL,
3075        { DAG.getConstant(0, SL, MVT::i16), LHS->getOperand(0) });
3076       return DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3077     }
3078 
3079     // shl (ext x) => zext (shl x), if shift does not overflow int
3080     if (VT != MVT::i64)
3081       break;
3082     KnownBits Known = DAG.computeKnownBits(X);
3083     unsigned LZ = Known.countMinLeadingZeros();
3084     if (LZ < RHSVal)
3085       break;
3086     EVT XVT = X.getValueType();
3087     SDValue Shl = DAG.getNode(ISD::SHL, SL, XVT, X, SDValue(RHS, 0));
3088     return DAG.getZExtOrTrunc(Shl, SL, VT);
3089   }
3090   }
3091 
3092   if (VT != MVT::i64)
3093     return SDValue();
3094 
3095   // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
3096 
3097   // On some subtargets, 64-bit shift is a quarter rate instruction. In the
3098   // common case, splitting this into a move and a 32-bit shift is faster and
3099   // the same code size.
3100   if (RHSVal < 32)
3101     return SDValue();
3102 
3103   SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
3104 
3105   SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
3106   SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
3107 
3108   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3109 
3110   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
3111   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3112 }
3113 
3114 SDValue AMDGPUTargetLowering::performSraCombine(SDNode *N,
3115                                                 DAGCombinerInfo &DCI) const {
3116   if (N->getValueType(0) != MVT::i64)
3117     return SDValue();
3118 
3119   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3120   if (!RHS)
3121     return SDValue();
3122 
3123   SelectionDAG &DAG = DCI.DAG;
3124   SDLoc SL(N);
3125   unsigned RHSVal = RHS->getZExtValue();
3126 
3127   // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
3128   if (RHSVal == 32) {
3129     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3130     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3131                                    DAG.getConstant(31, SL, MVT::i32));
3132 
3133     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
3134     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3135   }
3136 
3137   // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
3138   if (RHSVal == 63) {
3139     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3140     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3141                                    DAG.getConstant(31, SL, MVT::i32));
3142     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
3143     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3144   }
3145 
3146   return SDValue();
3147 }
3148 
3149 SDValue AMDGPUTargetLowering::performSrlCombine(SDNode *N,
3150                                                 DAGCombinerInfo &DCI) const {
3151   auto *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3152   if (!RHS)
3153     return SDValue();
3154 
3155   EVT VT = N->getValueType(0);
3156   SDValue LHS = N->getOperand(0);
3157   unsigned ShiftAmt = RHS->getZExtValue();
3158   SelectionDAG &DAG = DCI.DAG;
3159   SDLoc SL(N);
3160 
3161   // fold (srl (and x, c1 << c2), c2) -> (and (srl(x, c2), c1)
3162   // this improves the ability to match BFE patterns in isel.
3163   if (LHS.getOpcode() == ISD::AND) {
3164     if (auto *Mask = dyn_cast<ConstantSDNode>(LHS.getOperand(1))) {
3165       if (Mask->getAPIntValue().isShiftedMask() &&
3166           Mask->getAPIntValue().countTrailingZeros() == ShiftAmt) {
3167         return DAG.getNode(
3168             ISD::AND, SL, VT,
3169             DAG.getNode(ISD::SRL, SL, VT, LHS.getOperand(0), N->getOperand(1)),
3170             DAG.getNode(ISD::SRL, SL, VT, LHS.getOperand(1), N->getOperand(1)));
3171       }
3172     }
3173   }
3174 
3175   if (VT != MVT::i64)
3176     return SDValue();
3177 
3178   if (ShiftAmt < 32)
3179     return SDValue();
3180 
3181   // srl i64:x, C for C >= 32
3182   // =>
3183   //   build_pair (srl hi_32(x), C - 32), 0
3184   SDValue One = DAG.getConstant(1, SL, MVT::i32);
3185   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3186 
3187   SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, LHS);
3188   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecOp, One);
3189 
3190   SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
3191   SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
3192 
3193   SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
3194 
3195   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
3196 }
3197 
3198 SDValue AMDGPUTargetLowering::performTruncateCombine(
3199   SDNode *N, DAGCombinerInfo &DCI) const {
3200   SDLoc SL(N);
3201   SelectionDAG &DAG = DCI.DAG;
3202   EVT VT = N->getValueType(0);
3203   SDValue Src = N->getOperand(0);
3204 
3205   // vt1 (truncate (bitcast (build_vector vt0:x, ...))) -> vt1 (bitcast vt0:x)
3206   if (Src.getOpcode() == ISD::BITCAST && !VT.isVector()) {
3207     SDValue Vec = Src.getOperand(0);
3208     if (Vec.getOpcode() == ISD::BUILD_VECTOR) {
3209       SDValue Elt0 = Vec.getOperand(0);
3210       EVT EltVT = Elt0.getValueType();
3211       if (VT.getFixedSizeInBits() <= EltVT.getFixedSizeInBits()) {
3212         if (EltVT.isFloatingPoint()) {
3213           Elt0 = DAG.getNode(ISD::BITCAST, SL,
3214                              EltVT.changeTypeToInteger(), Elt0);
3215         }
3216 
3217         return DAG.getNode(ISD::TRUNCATE, SL, VT, Elt0);
3218       }
3219     }
3220   }
3221 
3222   // Equivalent of above for accessing the high element of a vector as an
3223   // integer operation.
3224   // trunc (srl (bitcast (build_vector x, y))), 16 -> trunc (bitcast y)
3225   if (Src.getOpcode() == ISD::SRL && !VT.isVector()) {
3226     if (auto K = isConstOrConstSplat(Src.getOperand(1))) {
3227       if (2 * K->getZExtValue() == Src.getValueType().getScalarSizeInBits()) {
3228         SDValue BV = stripBitcast(Src.getOperand(0));
3229         if (BV.getOpcode() == ISD::BUILD_VECTOR &&
3230             BV.getValueType().getVectorNumElements() == 2) {
3231           SDValue SrcElt = BV.getOperand(1);
3232           EVT SrcEltVT = SrcElt.getValueType();
3233           if (SrcEltVT.isFloatingPoint()) {
3234             SrcElt = DAG.getNode(ISD::BITCAST, SL,
3235                                  SrcEltVT.changeTypeToInteger(), SrcElt);
3236           }
3237 
3238           return DAG.getNode(ISD::TRUNCATE, SL, VT, SrcElt);
3239         }
3240       }
3241     }
3242   }
3243 
3244   // Partially shrink 64-bit shifts to 32-bit if reduced to 16-bit.
3245   //
3246   // i16 (trunc (srl i64:x, K)), K <= 16 ->
3247   //     i16 (trunc (srl (i32 (trunc x), K)))
3248   if (VT.getScalarSizeInBits() < 32) {
3249     EVT SrcVT = Src.getValueType();
3250     if (SrcVT.getScalarSizeInBits() > 32 &&
3251         (Src.getOpcode() == ISD::SRL ||
3252          Src.getOpcode() == ISD::SRA ||
3253          Src.getOpcode() == ISD::SHL)) {
3254       SDValue Amt = Src.getOperand(1);
3255       KnownBits Known = DAG.computeKnownBits(Amt);
3256       unsigned Size = VT.getScalarSizeInBits();
3257       if ((Known.isConstant() && Known.getConstant().ule(Size)) ||
3258           (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size))) {
3259         EVT MidVT = VT.isVector() ?
3260           EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3261                            VT.getVectorNumElements()) : MVT::i32;
3262 
3263         EVT NewShiftVT = getShiftAmountTy(MidVT, DAG.getDataLayout());
3264         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MidVT,
3265                                     Src.getOperand(0));
3266         DCI.AddToWorklist(Trunc.getNode());
3267 
3268         if (Amt.getValueType() != NewShiftVT) {
3269           Amt = DAG.getZExtOrTrunc(Amt, SL, NewShiftVT);
3270           DCI.AddToWorklist(Amt.getNode());
3271         }
3272 
3273         SDValue ShrunkShift = DAG.getNode(Src.getOpcode(), SL, MidVT,
3274                                           Trunc, Amt);
3275         return DAG.getNode(ISD::TRUNCATE, SL, VT, ShrunkShift);
3276       }
3277     }
3278   }
3279 
3280   return SDValue();
3281 }
3282 
3283 // We need to specifically handle i64 mul here to avoid unnecessary conversion
3284 // instructions. If we only match on the legalized i64 mul expansion,
3285 // SimplifyDemandedBits will be unable to remove them because there will be
3286 // multiple uses due to the separate mul + mulh[su].
3287 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
3288                         SDValue N0, SDValue N1, unsigned Size, bool Signed) {
3289   if (Size <= 32) {
3290     unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3291     return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
3292   }
3293 
3294   unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3295   unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
3296 
3297   SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
3298   SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
3299 
3300   return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64, MulLo, MulHi);
3301 }
3302 
3303 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
3304                                                 DAGCombinerInfo &DCI) const {
3305   EVT VT = N->getValueType(0);
3306 
3307   // Don't generate 24-bit multiplies on values that are in SGPRs, since
3308   // we only have a 32-bit scalar multiply (avoid values being moved to VGPRs
3309   // unnecessarily). isDivergent() is used as an approximation of whether the
3310   // value is in an SGPR.
3311   if (!N->isDivergent())
3312     return SDValue();
3313 
3314   unsigned Size = VT.getSizeInBits();
3315   if (VT.isVector() || Size > 64)
3316     return SDValue();
3317 
3318   // There are i16 integer mul/mad.
3319   if (Subtarget->has16BitInsts() && VT.getScalarType().bitsLE(MVT::i16))
3320     return SDValue();
3321 
3322   SelectionDAG &DAG = DCI.DAG;
3323   SDLoc DL(N);
3324 
3325   SDValue N0 = N->getOperand(0);
3326   SDValue N1 = N->getOperand(1);
3327 
3328   // SimplifyDemandedBits has the annoying habit of turning useful zero_extends
3329   // in the source into any_extends if the result of the mul is truncated. Since
3330   // we can assume the high bits are whatever we want, use the underlying value
3331   // to avoid the unknown high bits from interfering.
3332   if (N0.getOpcode() == ISD::ANY_EXTEND)
3333     N0 = N0.getOperand(0);
3334 
3335   if (N1.getOpcode() == ISD::ANY_EXTEND)
3336     N1 = N1.getOperand(0);
3337 
3338   SDValue Mul;
3339 
3340   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
3341     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3342     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3343     Mul = getMul24(DAG, DL, N0, N1, Size, false);
3344   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
3345     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3346     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3347     Mul = getMul24(DAG, DL, N0, N1, Size, true);
3348   } else {
3349     return SDValue();
3350   }
3351 
3352   // We need to use sext even for MUL_U24, because MUL_U24 is used
3353   // for signed multiply of 8 and 16-bit types.
3354   return DAG.getSExtOrTrunc(Mul, DL, VT);
3355 }
3356 
3357 SDValue AMDGPUTargetLowering::performMulhsCombine(SDNode *N,
3358                                                   DAGCombinerInfo &DCI) const {
3359   EVT VT = N->getValueType(0);
3360 
3361   if (!Subtarget->hasMulI24() || VT.isVector())
3362     return SDValue();
3363 
3364   SelectionDAG &DAG = DCI.DAG;
3365   SDLoc DL(N);
3366 
3367   SDValue N0 = N->getOperand(0);
3368   SDValue N1 = N->getOperand(1);
3369 
3370   if (!isI24(N0, DAG) || !isI24(N1, DAG))
3371     return SDValue();
3372 
3373   N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3374   N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3375 
3376   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
3377   DCI.AddToWorklist(Mulhi.getNode());
3378   return DAG.getSExtOrTrunc(Mulhi, DL, VT);
3379 }
3380 
3381 SDValue AMDGPUTargetLowering::performMulhuCombine(SDNode *N,
3382                                                   DAGCombinerInfo &DCI) const {
3383   EVT VT = N->getValueType(0);
3384 
3385   if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
3386     return SDValue();
3387 
3388   SelectionDAG &DAG = DCI.DAG;
3389   SDLoc DL(N);
3390 
3391   SDValue N0 = N->getOperand(0);
3392   SDValue N1 = N->getOperand(1);
3393 
3394   if (!isU24(N0, DAG) || !isU24(N1, DAG))
3395     return SDValue();
3396 
3397   N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3398   N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3399 
3400   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
3401   DCI.AddToWorklist(Mulhi.getNode());
3402   return DAG.getZExtOrTrunc(Mulhi, DL, VT);
3403 }
3404 
3405 static bool isNegativeOne(SDValue Val) {
3406   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
3407     return C->isAllOnesValue();
3408   return false;
3409 }
3410 
3411 SDValue AMDGPUTargetLowering::getFFBX_U32(SelectionDAG &DAG,
3412                                           SDValue Op,
3413                                           const SDLoc &DL,
3414                                           unsigned Opc) const {
3415   EVT VT = Op.getValueType();
3416   EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
3417   if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
3418                               LegalVT != MVT::i16))
3419     return SDValue();
3420 
3421   if (VT != MVT::i32)
3422     Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
3423 
3424   SDValue FFBX = DAG.getNode(Opc, DL, MVT::i32, Op);
3425   if (VT != MVT::i32)
3426     FFBX = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBX);
3427 
3428   return FFBX;
3429 }
3430 
3431 // The native instructions return -1 on 0 input. Optimize out a select that
3432 // produces -1 on 0.
3433 //
3434 // TODO: If zero is not undef, we could also do this if the output is compared
3435 // against the bitwidth.
3436 //
3437 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
3438 SDValue AMDGPUTargetLowering::performCtlz_CttzCombine(const SDLoc &SL, SDValue Cond,
3439                                                  SDValue LHS, SDValue RHS,
3440                                                  DAGCombinerInfo &DCI) const {
3441   ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3442   if (!CmpRhs || !CmpRhs->isNullValue())
3443     return SDValue();
3444 
3445   SelectionDAG &DAG = DCI.DAG;
3446   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
3447   SDValue CmpLHS = Cond.getOperand(0);
3448 
3449   // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
3450   // select (setcc x, 0, eq), -1, (cttz_zero_undef x) -> ffbl_u32 x
3451   if (CCOpcode == ISD::SETEQ &&
3452       (isCtlzOpc(RHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3453       RHS.getOperand(0) == CmpLHS && isNegativeOne(LHS)) {
3454     unsigned Opc =
3455         isCttzOpc(RHS.getOpcode()) ? AMDGPUISD::FFBL_B32 : AMDGPUISD::FFBH_U32;
3456     return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3457   }
3458 
3459   // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
3460   // select (setcc x, 0, ne), (cttz_zero_undef x), -1 -> ffbl_u32 x
3461   if (CCOpcode == ISD::SETNE &&
3462       (isCtlzOpc(LHS.getOpcode()) || isCttzOpc(LHS.getOpcode())) &&
3463       LHS.getOperand(0) == CmpLHS && isNegativeOne(RHS)) {
3464     unsigned Opc =
3465         isCttzOpc(LHS.getOpcode()) ? AMDGPUISD::FFBL_B32 : AMDGPUISD::FFBH_U32;
3466 
3467     return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3468   }
3469 
3470   return SDValue();
3471 }
3472 
3473 static SDValue distributeOpThroughSelect(TargetLowering::DAGCombinerInfo &DCI,
3474                                          unsigned Op,
3475                                          const SDLoc &SL,
3476                                          SDValue Cond,
3477                                          SDValue N1,
3478                                          SDValue N2) {
3479   SelectionDAG &DAG = DCI.DAG;
3480   EVT VT = N1.getValueType();
3481 
3482   SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
3483                                   N1.getOperand(0), N2.getOperand(0));
3484   DCI.AddToWorklist(NewSelect.getNode());
3485   return DAG.getNode(Op, SL, VT, NewSelect);
3486 }
3487 
3488 // Pull a free FP operation out of a select so it may fold into uses.
3489 //
3490 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
3491 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
3492 //
3493 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
3494 // select c, (fabs x), +k -> fabs (select c, x, k)
3495 static SDValue foldFreeOpFromSelect(TargetLowering::DAGCombinerInfo &DCI,
3496                                     SDValue N) {
3497   SelectionDAG &DAG = DCI.DAG;
3498   SDValue Cond = N.getOperand(0);
3499   SDValue LHS = N.getOperand(1);
3500   SDValue RHS = N.getOperand(2);
3501 
3502   EVT VT = N.getValueType();
3503   if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
3504       (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
3505     return distributeOpThroughSelect(DCI, LHS.getOpcode(),
3506                                      SDLoc(N), Cond, LHS, RHS);
3507   }
3508 
3509   bool Inv = false;
3510   if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
3511     std::swap(LHS, RHS);
3512     Inv = true;
3513   }
3514 
3515   // TODO: Support vector constants.
3516   ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
3517   if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
3518     SDLoc SL(N);
3519     // If one side is an fneg/fabs and the other is a constant, we can push the
3520     // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
3521     SDValue NewLHS = LHS.getOperand(0);
3522     SDValue NewRHS = RHS;
3523 
3524     // Careful: if the neg can be folded up, don't try to pull it back down.
3525     bool ShouldFoldNeg = true;
3526 
3527     if (NewLHS.hasOneUse()) {
3528       unsigned Opc = NewLHS.getOpcode();
3529       if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
3530         ShouldFoldNeg = false;
3531       if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
3532         ShouldFoldNeg = false;
3533     }
3534 
3535     if (ShouldFoldNeg) {
3536       if (LHS.getOpcode() == ISD::FNEG)
3537         NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3538       else if (CRHS->isNegative())
3539         return SDValue();
3540 
3541       if (Inv)
3542         std::swap(NewLHS, NewRHS);
3543 
3544       SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
3545                                       Cond, NewLHS, NewRHS);
3546       DCI.AddToWorklist(NewSelect.getNode());
3547       return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
3548     }
3549   }
3550 
3551   return SDValue();
3552 }
3553 
3554 
3555 SDValue AMDGPUTargetLowering::performSelectCombine(SDNode *N,
3556                                                    DAGCombinerInfo &DCI) const {
3557   if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
3558     return Folded;
3559 
3560   SDValue Cond = N->getOperand(0);
3561   if (Cond.getOpcode() != ISD::SETCC)
3562     return SDValue();
3563 
3564   EVT VT = N->getValueType(0);
3565   SDValue LHS = Cond.getOperand(0);
3566   SDValue RHS = Cond.getOperand(1);
3567   SDValue CC = Cond.getOperand(2);
3568 
3569   SDValue True = N->getOperand(1);
3570   SDValue False = N->getOperand(2);
3571 
3572   if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
3573     SelectionDAG &DAG = DCI.DAG;
3574     if (DAG.isConstantValueOfAnyType(True) &&
3575         !DAG.isConstantValueOfAnyType(False)) {
3576       // Swap cmp + select pair to move constant to false input.
3577       // This will allow using VOPC cndmasks more often.
3578       // select (setcc x, y), k, x -> select (setccinv x, y), x, k
3579 
3580       SDLoc SL(N);
3581       ISD::CondCode NewCC =
3582           getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), LHS.getValueType());
3583 
3584       SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
3585       return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
3586     }
3587 
3588     if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
3589       SDValue MinMax
3590         = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
3591       // Revisit this node so we can catch min3/max3/med3 patterns.
3592       //DCI.AddToWorklist(MinMax.getNode());
3593       return MinMax;
3594     }
3595   }
3596 
3597   // There's no reason to not do this if the condition has other uses.
3598   return performCtlz_CttzCombine(SDLoc(N), Cond, True, False, DCI);
3599 }
3600 
3601 static bool isInv2Pi(const APFloat &APF) {
3602   static const APFloat KF16(APFloat::IEEEhalf(), APInt(16, 0x3118));
3603   static const APFloat KF32(APFloat::IEEEsingle(), APInt(32, 0x3e22f983));
3604   static const APFloat KF64(APFloat::IEEEdouble(), APInt(64, 0x3fc45f306dc9c882));
3605 
3606   return APF.bitwiseIsEqual(KF16) ||
3607          APF.bitwiseIsEqual(KF32) ||
3608          APF.bitwiseIsEqual(KF64);
3609 }
3610 
3611 // 0 and 1.0 / (0.5 * pi) do not have inline immmediates, so there is an
3612 // additional cost to negate them.
3613 bool AMDGPUTargetLowering::isConstantCostlierToNegate(SDValue N) const {
3614   if (const ConstantFPSDNode *C = isConstOrConstSplatFP(N)) {
3615     if (C->isZero() && !C->isNegative())
3616       return true;
3617 
3618     if (Subtarget->hasInv2PiInlineImm() && isInv2Pi(C->getValueAPF()))
3619       return true;
3620   }
3621 
3622   return false;
3623 }
3624 
3625 static unsigned inverseMinMax(unsigned Opc) {
3626   switch (Opc) {
3627   case ISD::FMAXNUM:
3628     return ISD::FMINNUM;
3629   case ISD::FMINNUM:
3630     return ISD::FMAXNUM;
3631   case ISD::FMAXNUM_IEEE:
3632     return ISD::FMINNUM_IEEE;
3633   case ISD::FMINNUM_IEEE:
3634     return ISD::FMAXNUM_IEEE;
3635   case AMDGPUISD::FMAX_LEGACY:
3636     return AMDGPUISD::FMIN_LEGACY;
3637   case AMDGPUISD::FMIN_LEGACY:
3638     return  AMDGPUISD::FMAX_LEGACY;
3639   default:
3640     llvm_unreachable("invalid min/max opcode");
3641   }
3642 }
3643 
3644 SDValue AMDGPUTargetLowering::performFNegCombine(SDNode *N,
3645                                                  DAGCombinerInfo &DCI) const {
3646   SelectionDAG &DAG = DCI.DAG;
3647   SDValue N0 = N->getOperand(0);
3648   EVT VT = N->getValueType(0);
3649 
3650   unsigned Opc = N0.getOpcode();
3651 
3652   // If the input has multiple uses and we can either fold the negate down, or
3653   // the other uses cannot, give up. This both prevents unprofitable
3654   // transformations and infinite loops: we won't repeatedly try to fold around
3655   // a negate that has no 'good' form.
3656   if (N0.hasOneUse()) {
3657     // This may be able to fold into the source, but at a code size cost. Don't
3658     // fold if the fold into the user is free.
3659     if (allUsesHaveSourceMods(N, 0))
3660       return SDValue();
3661   } else {
3662     if (fnegFoldsIntoOp(Opc) &&
3663         (allUsesHaveSourceMods(N) || !allUsesHaveSourceMods(N0.getNode())))
3664       return SDValue();
3665   }
3666 
3667   SDLoc SL(N);
3668   switch (Opc) {
3669   case ISD::FADD: {
3670     if (!mayIgnoreSignedZero(N0))
3671       return SDValue();
3672 
3673     // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
3674     SDValue LHS = N0.getOperand(0);
3675     SDValue RHS = N0.getOperand(1);
3676 
3677     if (LHS.getOpcode() != ISD::FNEG)
3678       LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3679     else
3680       LHS = LHS.getOperand(0);
3681 
3682     if (RHS.getOpcode() != ISD::FNEG)
3683       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3684     else
3685       RHS = RHS.getOperand(0);
3686 
3687     SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
3688     if (Res.getOpcode() != ISD::FADD)
3689       return SDValue(); // Op got folded away.
3690     if (!N0.hasOneUse())
3691       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3692     return Res;
3693   }
3694   case ISD::FMUL:
3695   case AMDGPUISD::FMUL_LEGACY: {
3696     // (fneg (fmul x, y)) -> (fmul x, (fneg y))
3697     // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
3698     SDValue LHS = N0.getOperand(0);
3699     SDValue RHS = N0.getOperand(1);
3700 
3701     if (LHS.getOpcode() == ISD::FNEG)
3702       LHS = LHS.getOperand(0);
3703     else if (RHS.getOpcode() == ISD::FNEG)
3704       RHS = RHS.getOperand(0);
3705     else
3706       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3707 
3708     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
3709     if (Res.getOpcode() != Opc)
3710       return SDValue(); // Op got folded away.
3711     if (!N0.hasOneUse())
3712       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3713     return Res;
3714   }
3715   case ISD::FMA:
3716   case ISD::FMAD: {
3717     // TODO: handle llvm.amdgcn.fma.legacy
3718     if (!mayIgnoreSignedZero(N0))
3719       return SDValue();
3720 
3721     // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
3722     SDValue LHS = N0.getOperand(0);
3723     SDValue MHS = N0.getOperand(1);
3724     SDValue RHS = N0.getOperand(2);
3725 
3726     if (LHS.getOpcode() == ISD::FNEG)
3727       LHS = LHS.getOperand(0);
3728     else if (MHS.getOpcode() == ISD::FNEG)
3729       MHS = MHS.getOperand(0);
3730     else
3731       MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
3732 
3733     if (RHS.getOpcode() != ISD::FNEG)
3734       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3735     else
3736       RHS = RHS.getOperand(0);
3737 
3738     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
3739     if (Res.getOpcode() != Opc)
3740       return SDValue(); // Op got folded away.
3741     if (!N0.hasOneUse())
3742       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3743     return Res;
3744   }
3745   case ISD::FMAXNUM:
3746   case ISD::FMINNUM:
3747   case ISD::FMAXNUM_IEEE:
3748   case ISD::FMINNUM_IEEE:
3749   case AMDGPUISD::FMAX_LEGACY:
3750   case AMDGPUISD::FMIN_LEGACY: {
3751     // fneg (fmaxnum x, y) -> fminnum (fneg x), (fneg y)
3752     // fneg (fminnum x, y) -> fmaxnum (fneg x), (fneg y)
3753     // fneg (fmax_legacy x, y) -> fmin_legacy (fneg x), (fneg y)
3754     // fneg (fmin_legacy x, y) -> fmax_legacy (fneg x), (fneg y)
3755 
3756     SDValue LHS = N0.getOperand(0);
3757     SDValue RHS = N0.getOperand(1);
3758 
3759     // 0 doesn't have a negated inline immediate.
3760     // TODO: This constant check should be generalized to other operations.
3761     if (isConstantCostlierToNegate(RHS))
3762       return SDValue();
3763 
3764     SDValue NegLHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3765     SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3766     unsigned Opposite = inverseMinMax(Opc);
3767 
3768     SDValue Res = DAG.getNode(Opposite, SL, VT, NegLHS, NegRHS, N0->getFlags());
3769     if (Res.getOpcode() != Opposite)
3770       return SDValue(); // Op got folded away.
3771     if (!N0.hasOneUse())
3772       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3773     return Res;
3774   }
3775   case AMDGPUISD::FMED3: {
3776     SDValue Ops[3];
3777     for (unsigned I = 0; I < 3; ++I)
3778       Ops[I] = DAG.getNode(ISD::FNEG, SL, VT, N0->getOperand(I), N0->getFlags());
3779 
3780     SDValue Res = DAG.getNode(AMDGPUISD::FMED3, SL, VT, Ops, N0->getFlags());
3781     if (Res.getOpcode() != AMDGPUISD::FMED3)
3782       return SDValue(); // Op got folded away.
3783 
3784     if (!N0.hasOneUse()) {
3785       SDValue Neg = DAG.getNode(ISD::FNEG, SL, VT, Res);
3786       DAG.ReplaceAllUsesWith(N0, Neg);
3787 
3788       for (SDNode *U : Neg->uses())
3789         DCI.AddToWorklist(U);
3790     }
3791 
3792     return Res;
3793   }
3794   case ISD::FP_EXTEND:
3795   case ISD::FTRUNC:
3796   case ISD::FRINT:
3797   case ISD::FNEARBYINT: // XXX - Should fround be handled?
3798   case ISD::FSIN:
3799   case ISD::FCANONICALIZE:
3800   case AMDGPUISD::RCP:
3801   case AMDGPUISD::RCP_LEGACY:
3802   case AMDGPUISD::RCP_IFLAG:
3803   case AMDGPUISD::SIN_HW: {
3804     SDValue CvtSrc = N0.getOperand(0);
3805     if (CvtSrc.getOpcode() == ISD::FNEG) {
3806       // (fneg (fp_extend (fneg x))) -> (fp_extend x)
3807       // (fneg (rcp (fneg x))) -> (rcp x)
3808       return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
3809     }
3810 
3811     if (!N0.hasOneUse())
3812       return SDValue();
3813 
3814     // (fneg (fp_extend x)) -> (fp_extend (fneg x))
3815     // (fneg (rcp x)) -> (rcp (fneg x))
3816     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3817     return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
3818   }
3819   case ISD::FP_ROUND: {
3820     SDValue CvtSrc = N0.getOperand(0);
3821 
3822     if (CvtSrc.getOpcode() == ISD::FNEG) {
3823       // (fneg (fp_round (fneg x))) -> (fp_round x)
3824       return DAG.getNode(ISD::FP_ROUND, SL, VT,
3825                          CvtSrc.getOperand(0), N0.getOperand(1));
3826     }
3827 
3828     if (!N0.hasOneUse())
3829       return SDValue();
3830 
3831     // (fneg (fp_round x)) -> (fp_round (fneg x))
3832     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3833     return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
3834   }
3835   case ISD::FP16_TO_FP: {
3836     // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
3837     // f16, but legalization of f16 fneg ends up pulling it out of the source.
3838     // Put the fneg back as a legal source operation that can be matched later.
3839     SDLoc SL(N);
3840 
3841     SDValue Src = N0.getOperand(0);
3842     EVT SrcVT = Src.getValueType();
3843 
3844     // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
3845     SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
3846                                   DAG.getConstant(0x8000, SL, SrcVT));
3847     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
3848   }
3849   default:
3850     return SDValue();
3851   }
3852 }
3853 
3854 SDValue AMDGPUTargetLowering::performFAbsCombine(SDNode *N,
3855                                                  DAGCombinerInfo &DCI) const {
3856   SelectionDAG &DAG = DCI.DAG;
3857   SDValue N0 = N->getOperand(0);
3858 
3859   if (!N0.hasOneUse())
3860     return SDValue();
3861 
3862   switch (N0.getOpcode()) {
3863   case ISD::FP16_TO_FP: {
3864     assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3865     SDLoc SL(N);
3866     SDValue Src = N0.getOperand(0);
3867     EVT SrcVT = Src.getValueType();
3868 
3869     // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3870     SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3871                                   DAG.getConstant(0x7fff, SL, SrcVT));
3872     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3873   }
3874   default:
3875     return SDValue();
3876   }
3877 }
3878 
3879 SDValue AMDGPUTargetLowering::performRcpCombine(SDNode *N,
3880                                                 DAGCombinerInfo &DCI) const {
3881   const auto *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3882   if (!CFP)
3883     return SDValue();
3884 
3885   // XXX - Should this flush denormals?
3886   const APFloat &Val = CFP->getValueAPF();
3887   APFloat One(Val.getSemantics(), "1.0");
3888   return DCI.DAG.getConstantFP(One / Val, SDLoc(N), N->getValueType(0));
3889 }
3890 
3891 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
3892                                                 DAGCombinerInfo &DCI) const {
3893   SelectionDAG &DAG = DCI.DAG;
3894   SDLoc DL(N);
3895 
3896   switch(N->getOpcode()) {
3897   default:
3898     break;
3899   case ISD::BITCAST: {
3900     EVT DestVT = N->getValueType(0);
3901 
3902     // Push casts through vector builds. This helps avoid emitting a large
3903     // number of copies when materializing floating point vector constants.
3904     //
3905     // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3906     //   vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3907     if (DestVT.isVector()) {
3908       SDValue Src = N->getOperand(0);
3909       if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3910         EVT SrcVT = Src.getValueType();
3911         unsigned NElts = DestVT.getVectorNumElements();
3912 
3913         if (SrcVT.getVectorNumElements() == NElts) {
3914           EVT DestEltVT = DestVT.getVectorElementType();
3915 
3916           SmallVector<SDValue, 8> CastedElts;
3917           SDLoc SL(N);
3918           for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3919             SDValue Elt = Src.getOperand(I);
3920             CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3921           }
3922 
3923           return DAG.getBuildVector(DestVT, SL, CastedElts);
3924         }
3925       }
3926     }
3927 
3928     if (DestVT.getSizeInBits() != 64 || !DestVT.isVector())
3929       break;
3930 
3931     // Fold bitcasts of constants.
3932     //
3933     // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3934     // TODO: Generalize and move to DAGCombiner
3935     SDValue Src = N->getOperand(0);
3936     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3937       SDLoc SL(N);
3938       uint64_t CVal = C->getZExtValue();
3939       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3940                                DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3941                                DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3942       return DAG.getNode(ISD::BITCAST, SL, DestVT, BV);
3943     }
3944 
3945     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3946       const APInt &Val = C->getValueAPF().bitcastToAPInt();
3947       SDLoc SL(N);
3948       uint64_t CVal = Val.getZExtValue();
3949       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3950                                 DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3951                                 DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3952 
3953       return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3954     }
3955 
3956     break;
3957   }
3958   case ISD::SHL: {
3959     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3960       break;
3961 
3962     return performShlCombine(N, DCI);
3963   }
3964   case ISD::SRL: {
3965     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3966       break;
3967 
3968     return performSrlCombine(N, DCI);
3969   }
3970   case ISD::SRA: {
3971     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3972       break;
3973 
3974     return performSraCombine(N, DCI);
3975   }
3976   case ISD::TRUNCATE:
3977     return performTruncateCombine(N, DCI);
3978   case ISD::MUL:
3979     return performMulCombine(N, DCI);
3980   case ISD::MULHS:
3981     return performMulhsCombine(N, DCI);
3982   case ISD::MULHU:
3983     return performMulhuCombine(N, DCI);
3984   case AMDGPUISD::MUL_I24:
3985   case AMDGPUISD::MUL_U24:
3986   case AMDGPUISD::MULHI_I24:
3987   case AMDGPUISD::MULHI_U24:
3988     return simplifyMul24(N, DCI);
3989   case ISD::SELECT:
3990     return performSelectCombine(N, DCI);
3991   case ISD::FNEG:
3992     return performFNegCombine(N, DCI);
3993   case ISD::FABS:
3994     return performFAbsCombine(N, DCI);
3995   case AMDGPUISD::BFE_I32:
3996   case AMDGPUISD::BFE_U32: {
3997     assert(!N->getValueType(0).isVector() &&
3998            "Vector handling of BFE not implemented");
3999     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
4000     if (!Width)
4001       break;
4002 
4003     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
4004     if (WidthVal == 0)
4005       return DAG.getConstant(0, DL, MVT::i32);
4006 
4007     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
4008     if (!Offset)
4009       break;
4010 
4011     SDValue BitsFrom = N->getOperand(0);
4012     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
4013 
4014     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
4015 
4016     if (OffsetVal == 0) {
4017       // This is already sign / zero extended, so try to fold away extra BFEs.
4018       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
4019 
4020       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
4021       if (OpSignBits >= SignBits)
4022         return BitsFrom;
4023 
4024       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
4025       if (Signed) {
4026         // This is a sign_extend_inreg. Replace it to take advantage of existing
4027         // DAG Combines. If not eliminated, we will match back to BFE during
4028         // selection.
4029 
4030         // TODO: The sext_inreg of extended types ends, although we can could
4031         // handle them in a single BFE.
4032         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
4033                            DAG.getValueType(SmallVT));
4034       }
4035 
4036       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
4037     }
4038 
4039     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
4040       if (Signed) {
4041         return constantFoldBFE<int32_t>(DAG,
4042                                         CVal->getSExtValue(),
4043                                         OffsetVal,
4044                                         WidthVal,
4045                                         DL);
4046       }
4047 
4048       return constantFoldBFE<uint32_t>(DAG,
4049                                        CVal->getZExtValue(),
4050                                        OffsetVal,
4051                                        WidthVal,
4052                                        DL);
4053     }
4054 
4055     if ((OffsetVal + WidthVal) >= 32 &&
4056         !(Subtarget->hasSDWA() && OffsetVal == 16 && WidthVal == 16)) {
4057       SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
4058       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
4059                          BitsFrom, ShiftVal);
4060     }
4061 
4062     if (BitsFrom.hasOneUse()) {
4063       APInt Demanded = APInt::getBitsSet(32,
4064                                          OffsetVal,
4065                                          OffsetVal + WidthVal);
4066 
4067       KnownBits Known;
4068       TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4069                                             !DCI.isBeforeLegalizeOps());
4070       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4071       if (TLI.ShrinkDemandedConstant(BitsFrom, Demanded, TLO) ||
4072           TLI.SimplifyDemandedBits(BitsFrom, Demanded, Known, TLO)) {
4073         DCI.CommitTargetLoweringOpt(TLO);
4074       }
4075     }
4076 
4077     break;
4078   }
4079   case ISD::LOAD:
4080     return performLoadCombine(N, DCI);
4081   case ISD::STORE:
4082     return performStoreCombine(N, DCI);
4083   case AMDGPUISD::RCP:
4084   case AMDGPUISD::RCP_IFLAG:
4085     return performRcpCombine(N, DCI);
4086   case ISD::AssertZext:
4087   case ISD::AssertSext:
4088     return performAssertSZExtCombine(N, DCI);
4089   case ISD::INTRINSIC_WO_CHAIN:
4090     return performIntrinsicWOChainCombine(N, DCI);
4091   }
4092   return SDValue();
4093 }
4094 
4095 //===----------------------------------------------------------------------===//
4096 // Helper functions
4097 //===----------------------------------------------------------------------===//
4098 
4099 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4100                                                    const TargetRegisterClass *RC,
4101                                                    Register Reg, EVT VT,
4102                                                    const SDLoc &SL,
4103                                                    bool RawReg) const {
4104   MachineFunction &MF = DAG.getMachineFunction();
4105   MachineRegisterInfo &MRI = MF.getRegInfo();
4106   Register VReg;
4107 
4108   if (!MRI.isLiveIn(Reg)) {
4109     VReg = MRI.createVirtualRegister(RC);
4110     MRI.addLiveIn(Reg, VReg);
4111   } else {
4112     VReg = MRI.getLiveInVirtReg(Reg);
4113   }
4114 
4115   if (RawReg)
4116     return DAG.getRegister(VReg, VT);
4117 
4118   return DAG.getCopyFromReg(DAG.getEntryNode(), SL, VReg, VT);
4119 }
4120 
4121 // This may be called multiple times, and nothing prevents creating multiple
4122 // objects at the same offset. See if we already defined this object.
4123 static int getOrCreateFixedStackObject(MachineFrameInfo &MFI, unsigned Size,
4124                                        int64_t Offset) {
4125   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
4126     if (MFI.getObjectOffset(I) == Offset) {
4127       assert(MFI.getObjectSize(I) == Size);
4128       return I;
4129     }
4130   }
4131 
4132   return MFI.CreateFixedObject(Size, Offset, true);
4133 }
4134 
4135 SDValue AMDGPUTargetLowering::loadStackInputValue(SelectionDAG &DAG,
4136                                                   EVT VT,
4137                                                   const SDLoc &SL,
4138                                                   int64_t Offset) const {
4139   MachineFunction &MF = DAG.getMachineFunction();
4140   MachineFrameInfo &MFI = MF.getFrameInfo();
4141   int FI = getOrCreateFixedStackObject(MFI, VT.getStoreSize(), Offset);
4142 
4143   auto SrcPtrInfo = MachinePointerInfo::getStack(MF, Offset);
4144   SDValue Ptr = DAG.getFrameIndex(FI, MVT::i32);
4145 
4146   return DAG.getLoad(VT, SL, DAG.getEntryNode(), Ptr, SrcPtrInfo, Align(4),
4147                      MachineMemOperand::MODereferenceable |
4148                          MachineMemOperand::MOInvariant);
4149 }
4150 
4151 SDValue AMDGPUTargetLowering::storeStackInputValue(SelectionDAG &DAG,
4152                                                    const SDLoc &SL,
4153                                                    SDValue Chain,
4154                                                    SDValue ArgVal,
4155                                                    int64_t Offset) const {
4156   MachineFunction &MF = DAG.getMachineFunction();
4157   MachinePointerInfo DstInfo = MachinePointerInfo::getStack(MF, Offset);
4158 
4159   SDValue Ptr = DAG.getConstant(Offset, SL, MVT::i32);
4160   SDValue Store = DAG.getStore(Chain, SL, ArgVal, Ptr, DstInfo, Align(4),
4161                                MachineMemOperand::MODereferenceable);
4162   return Store;
4163 }
4164 
4165 SDValue AMDGPUTargetLowering::loadInputValue(SelectionDAG &DAG,
4166                                              const TargetRegisterClass *RC,
4167                                              EVT VT, const SDLoc &SL,
4168                                              const ArgDescriptor &Arg) const {
4169   assert(Arg && "Attempting to load missing argument");
4170 
4171   SDValue V = Arg.isRegister() ?
4172     CreateLiveInRegister(DAG, RC, Arg.getRegister(), VT, SL) :
4173     loadStackInputValue(DAG, VT, SL, Arg.getStackOffset());
4174 
4175   if (!Arg.isMasked())
4176     return V;
4177 
4178   unsigned Mask = Arg.getMask();
4179   unsigned Shift = countTrailingZeros<unsigned>(Mask);
4180   V = DAG.getNode(ISD::SRL, SL, VT, V,
4181                   DAG.getShiftAmountConstant(Shift, VT, SL));
4182   return DAG.getNode(ISD::AND, SL, VT, V,
4183                      DAG.getConstant(Mask >> Shift, SL, VT));
4184 }
4185 
4186 uint32_t AMDGPUTargetLowering::getImplicitParameterOffset(
4187     const MachineFunction &MF, const ImplicitParameter Param) const {
4188   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
4189   const AMDGPUSubtarget &ST =
4190       AMDGPUSubtarget::get(getTargetMachine(), MF.getFunction());
4191   unsigned ExplicitArgOffset = ST.getExplicitKernelArgOffset(MF.getFunction());
4192   const Align Alignment = ST.getAlignmentForImplicitArgPtr();
4193   uint64_t ArgOffset = alignTo(MFI->getExplicitKernArgSize(), Alignment) +
4194                        ExplicitArgOffset;
4195   switch (Param) {
4196   case GRID_DIM:
4197     return ArgOffset;
4198   case GRID_OFFSET:
4199     return ArgOffset + 4;
4200   }
4201   llvm_unreachable("unexpected implicit parameter type");
4202 }
4203 
4204 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
4205 
4206 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
4207   switch ((AMDGPUISD::NodeType)Opcode) {
4208   case AMDGPUISD::FIRST_NUMBER: break;
4209   // AMDIL DAG nodes
4210   NODE_NAME_CASE(UMUL);
4211   NODE_NAME_CASE(BRANCH_COND);
4212 
4213   // AMDGPU DAG nodes
4214   NODE_NAME_CASE(IF)
4215   NODE_NAME_CASE(ELSE)
4216   NODE_NAME_CASE(LOOP)
4217   NODE_NAME_CASE(CALL)
4218   NODE_NAME_CASE(TC_RETURN)
4219   NODE_NAME_CASE(TRAP)
4220   NODE_NAME_CASE(RET_FLAG)
4221   NODE_NAME_CASE(RETURN_TO_EPILOG)
4222   NODE_NAME_CASE(ENDPGM)
4223   NODE_NAME_CASE(DWORDADDR)
4224   NODE_NAME_CASE(FRACT)
4225   NODE_NAME_CASE(SETCC)
4226   NODE_NAME_CASE(SETREG)
4227   NODE_NAME_CASE(DENORM_MODE)
4228   NODE_NAME_CASE(FMA_W_CHAIN)
4229   NODE_NAME_CASE(FMUL_W_CHAIN)
4230   NODE_NAME_CASE(CLAMP)
4231   NODE_NAME_CASE(COS_HW)
4232   NODE_NAME_CASE(SIN_HW)
4233   NODE_NAME_CASE(FMAX_LEGACY)
4234   NODE_NAME_CASE(FMIN_LEGACY)
4235   NODE_NAME_CASE(FMAX3)
4236   NODE_NAME_CASE(SMAX3)
4237   NODE_NAME_CASE(UMAX3)
4238   NODE_NAME_CASE(FMIN3)
4239   NODE_NAME_CASE(SMIN3)
4240   NODE_NAME_CASE(UMIN3)
4241   NODE_NAME_CASE(FMED3)
4242   NODE_NAME_CASE(SMED3)
4243   NODE_NAME_CASE(UMED3)
4244   NODE_NAME_CASE(FDOT2)
4245   NODE_NAME_CASE(URECIP)
4246   NODE_NAME_CASE(DIV_SCALE)
4247   NODE_NAME_CASE(DIV_FMAS)
4248   NODE_NAME_CASE(DIV_FIXUP)
4249   NODE_NAME_CASE(FMAD_FTZ)
4250   NODE_NAME_CASE(RCP)
4251   NODE_NAME_CASE(RSQ)
4252   NODE_NAME_CASE(RCP_LEGACY)
4253   NODE_NAME_CASE(RCP_IFLAG)
4254   NODE_NAME_CASE(FMUL_LEGACY)
4255   NODE_NAME_CASE(RSQ_CLAMP)
4256   NODE_NAME_CASE(LDEXP)
4257   NODE_NAME_CASE(FP_CLASS)
4258   NODE_NAME_CASE(DOT4)
4259   NODE_NAME_CASE(CARRY)
4260   NODE_NAME_CASE(BORROW)
4261   NODE_NAME_CASE(BFE_U32)
4262   NODE_NAME_CASE(BFE_I32)
4263   NODE_NAME_CASE(BFI)
4264   NODE_NAME_CASE(BFM)
4265   NODE_NAME_CASE(FFBH_U32)
4266   NODE_NAME_CASE(FFBH_I32)
4267   NODE_NAME_CASE(FFBL_B32)
4268   NODE_NAME_CASE(MUL_U24)
4269   NODE_NAME_CASE(MUL_I24)
4270   NODE_NAME_CASE(MULHI_U24)
4271   NODE_NAME_CASE(MULHI_I24)
4272   NODE_NAME_CASE(MAD_U24)
4273   NODE_NAME_CASE(MAD_I24)
4274   NODE_NAME_CASE(MAD_I64_I32)
4275   NODE_NAME_CASE(MAD_U64_U32)
4276   NODE_NAME_CASE(PERM)
4277   NODE_NAME_CASE(TEXTURE_FETCH)
4278   NODE_NAME_CASE(R600_EXPORT)
4279   NODE_NAME_CASE(CONST_ADDRESS)
4280   NODE_NAME_CASE(REGISTER_LOAD)
4281   NODE_NAME_CASE(REGISTER_STORE)
4282   NODE_NAME_CASE(SAMPLE)
4283   NODE_NAME_CASE(SAMPLEB)
4284   NODE_NAME_CASE(SAMPLED)
4285   NODE_NAME_CASE(SAMPLEL)
4286   NODE_NAME_CASE(CVT_F32_UBYTE0)
4287   NODE_NAME_CASE(CVT_F32_UBYTE1)
4288   NODE_NAME_CASE(CVT_F32_UBYTE2)
4289   NODE_NAME_CASE(CVT_F32_UBYTE3)
4290   NODE_NAME_CASE(CVT_PKRTZ_F16_F32)
4291   NODE_NAME_CASE(CVT_PKNORM_I16_F32)
4292   NODE_NAME_CASE(CVT_PKNORM_U16_F32)
4293   NODE_NAME_CASE(CVT_PK_I16_I32)
4294   NODE_NAME_CASE(CVT_PK_U16_U32)
4295   NODE_NAME_CASE(FP_TO_FP16)
4296   NODE_NAME_CASE(FP16_ZEXT)
4297   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
4298   NODE_NAME_CASE(CONST_DATA_PTR)
4299   NODE_NAME_CASE(PC_ADD_REL_OFFSET)
4300   NODE_NAME_CASE(LDS)
4301   NODE_NAME_CASE(DUMMY_CHAIN)
4302   case AMDGPUISD::FIRST_MEM_OPCODE_NUMBER: break;
4303   NODE_NAME_CASE(LOAD_D16_HI)
4304   NODE_NAME_CASE(LOAD_D16_LO)
4305   NODE_NAME_CASE(LOAD_D16_HI_I8)
4306   NODE_NAME_CASE(LOAD_D16_HI_U8)
4307   NODE_NAME_CASE(LOAD_D16_LO_I8)
4308   NODE_NAME_CASE(LOAD_D16_LO_U8)
4309   NODE_NAME_CASE(STORE_MSKOR)
4310   NODE_NAME_CASE(LOAD_CONSTANT)
4311   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
4312   NODE_NAME_CASE(TBUFFER_STORE_FORMAT_D16)
4313   NODE_NAME_CASE(TBUFFER_LOAD_FORMAT)
4314   NODE_NAME_CASE(TBUFFER_LOAD_FORMAT_D16)
4315   NODE_NAME_CASE(DS_ORDERED_COUNT)
4316   NODE_NAME_CASE(ATOMIC_CMP_SWAP)
4317   NODE_NAME_CASE(ATOMIC_INC)
4318   NODE_NAME_CASE(ATOMIC_DEC)
4319   NODE_NAME_CASE(ATOMIC_LOAD_FMIN)
4320   NODE_NAME_CASE(ATOMIC_LOAD_FMAX)
4321   NODE_NAME_CASE(BUFFER_LOAD)
4322   NODE_NAME_CASE(BUFFER_LOAD_UBYTE)
4323   NODE_NAME_CASE(BUFFER_LOAD_USHORT)
4324   NODE_NAME_CASE(BUFFER_LOAD_BYTE)
4325   NODE_NAME_CASE(BUFFER_LOAD_SHORT)
4326   NODE_NAME_CASE(BUFFER_LOAD_FORMAT)
4327   NODE_NAME_CASE(BUFFER_LOAD_FORMAT_D16)
4328   NODE_NAME_CASE(SBUFFER_LOAD)
4329   NODE_NAME_CASE(BUFFER_STORE)
4330   NODE_NAME_CASE(BUFFER_STORE_BYTE)
4331   NODE_NAME_CASE(BUFFER_STORE_SHORT)
4332   NODE_NAME_CASE(BUFFER_STORE_FORMAT)
4333   NODE_NAME_CASE(BUFFER_STORE_FORMAT_D16)
4334   NODE_NAME_CASE(BUFFER_ATOMIC_SWAP)
4335   NODE_NAME_CASE(BUFFER_ATOMIC_ADD)
4336   NODE_NAME_CASE(BUFFER_ATOMIC_SUB)
4337   NODE_NAME_CASE(BUFFER_ATOMIC_SMIN)
4338   NODE_NAME_CASE(BUFFER_ATOMIC_UMIN)
4339   NODE_NAME_CASE(BUFFER_ATOMIC_SMAX)
4340   NODE_NAME_CASE(BUFFER_ATOMIC_UMAX)
4341   NODE_NAME_CASE(BUFFER_ATOMIC_AND)
4342   NODE_NAME_CASE(BUFFER_ATOMIC_OR)
4343   NODE_NAME_CASE(BUFFER_ATOMIC_XOR)
4344   NODE_NAME_CASE(BUFFER_ATOMIC_INC)
4345   NODE_NAME_CASE(BUFFER_ATOMIC_DEC)
4346   NODE_NAME_CASE(BUFFER_ATOMIC_CMPSWAP)
4347   NODE_NAME_CASE(BUFFER_ATOMIC_CSUB)
4348   NODE_NAME_CASE(BUFFER_ATOMIC_FADD)
4349   NODE_NAME_CASE(BUFFER_ATOMIC_FMIN)
4350   NODE_NAME_CASE(BUFFER_ATOMIC_FMAX)
4351 
4352   case AMDGPUISD::LAST_AMDGPU_ISD_NUMBER: break;
4353   }
4354   return nullptr;
4355 }
4356 
4357 SDValue AMDGPUTargetLowering::getSqrtEstimate(SDValue Operand,
4358                                               SelectionDAG &DAG, int Enabled,
4359                                               int &RefinementSteps,
4360                                               bool &UseOneConstNR,
4361                                               bool Reciprocal) const {
4362   EVT VT = Operand.getValueType();
4363 
4364   if (VT == MVT::f32) {
4365     RefinementSteps = 0;
4366     return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
4367   }
4368 
4369   // TODO: There is also f64 rsq instruction, but the documentation is less
4370   // clear on its precision.
4371 
4372   return SDValue();
4373 }
4374 
4375 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
4376                                                SelectionDAG &DAG, int Enabled,
4377                                                int &RefinementSteps) const {
4378   EVT VT = Operand.getValueType();
4379 
4380   if (VT == MVT::f32) {
4381     // Reciprocal, < 1 ulp error.
4382     //
4383     // This reciprocal approximation converges to < 0.5 ulp error with one
4384     // newton rhapson performed with two fused multiple adds (FMAs).
4385 
4386     RefinementSteps = 0;
4387     return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
4388   }
4389 
4390   // TODO: There is also f64 rcp instruction, but the documentation is less
4391   // clear on its precision.
4392 
4393   return SDValue();
4394 }
4395 
4396 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
4397     const SDValue Op, KnownBits &Known,
4398     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
4399 
4400   Known.resetAll(); // Don't know anything.
4401 
4402   unsigned Opc = Op.getOpcode();
4403 
4404   switch (Opc) {
4405   default:
4406     break;
4407   case AMDGPUISD::CARRY:
4408   case AMDGPUISD::BORROW: {
4409     Known.Zero = APInt::getHighBitsSet(32, 31);
4410     break;
4411   }
4412 
4413   case AMDGPUISD::BFE_I32:
4414   case AMDGPUISD::BFE_U32: {
4415     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4416     if (!CWidth)
4417       return;
4418 
4419     uint32_t Width = CWidth->getZExtValue() & 0x1f;
4420 
4421     if (Opc == AMDGPUISD::BFE_U32)
4422       Known.Zero = APInt::getHighBitsSet(32, 32 - Width);
4423 
4424     break;
4425   }
4426   case AMDGPUISD::FP_TO_FP16:
4427   case AMDGPUISD::FP16_ZEXT: {
4428     unsigned BitWidth = Known.getBitWidth();
4429 
4430     // High bits are zero.
4431     Known.Zero = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
4432     break;
4433   }
4434   case AMDGPUISD::MUL_U24:
4435   case AMDGPUISD::MUL_I24: {
4436     KnownBits LHSKnown = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
4437     KnownBits RHSKnown = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
4438     unsigned TrailZ = LHSKnown.countMinTrailingZeros() +
4439                       RHSKnown.countMinTrailingZeros();
4440     Known.Zero.setLowBits(std::min(TrailZ, 32u));
4441     // Skip extra check if all bits are known zeros.
4442     if (TrailZ >= 32)
4443       break;
4444 
4445     // Truncate to 24 bits.
4446     LHSKnown = LHSKnown.trunc(24);
4447     RHSKnown = RHSKnown.trunc(24);
4448 
4449     if (Opc == AMDGPUISD::MUL_I24) {
4450       unsigned LHSValBits = 24 - LHSKnown.countMinSignBits();
4451       unsigned RHSValBits = 24 - RHSKnown.countMinSignBits();
4452       unsigned MaxValBits = std::min(LHSValBits + RHSValBits, 32u);
4453       if (MaxValBits >= 32)
4454         break;
4455       bool LHSNegative = LHSKnown.isNegative();
4456       bool LHSNonNegative = LHSKnown.isNonNegative();
4457       bool LHSPositive = LHSKnown.isStrictlyPositive();
4458       bool RHSNegative = RHSKnown.isNegative();
4459       bool RHSNonNegative = RHSKnown.isNonNegative();
4460       bool RHSPositive = RHSKnown.isStrictlyPositive();
4461 
4462       if ((LHSNonNegative && RHSNonNegative) || (LHSNegative && RHSNegative))
4463         Known.Zero.setHighBits(32 - MaxValBits);
4464       else if ((LHSNegative && RHSPositive) || (LHSPositive && RHSNegative))
4465         Known.One.setHighBits(32 - MaxValBits);
4466     } else {
4467       unsigned LHSValBits = 24 - LHSKnown.countMinLeadingZeros();
4468       unsigned RHSValBits = 24 - RHSKnown.countMinLeadingZeros();
4469       unsigned MaxValBits = std::min(LHSValBits + RHSValBits, 32u);
4470       if (MaxValBits >= 32)
4471         break;
4472       Known.Zero.setHighBits(32 - MaxValBits);
4473     }
4474     break;
4475   }
4476   case AMDGPUISD::PERM: {
4477     ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4478     if (!CMask)
4479       return;
4480 
4481     KnownBits LHSKnown = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
4482     KnownBits RHSKnown = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
4483     unsigned Sel = CMask->getZExtValue();
4484 
4485     for (unsigned I = 0; I < 32; I += 8) {
4486       unsigned SelBits = Sel & 0xff;
4487       if (SelBits < 4) {
4488         SelBits *= 8;
4489         Known.One |= ((RHSKnown.One.getZExtValue() >> SelBits) & 0xff) << I;
4490         Known.Zero |= ((RHSKnown.Zero.getZExtValue() >> SelBits) & 0xff) << I;
4491       } else if (SelBits < 7) {
4492         SelBits = (SelBits & 3) * 8;
4493         Known.One |= ((LHSKnown.One.getZExtValue() >> SelBits) & 0xff) << I;
4494         Known.Zero |= ((LHSKnown.Zero.getZExtValue() >> SelBits) & 0xff) << I;
4495       } else if (SelBits == 0x0c) {
4496         Known.Zero |= 0xFFull << I;
4497       } else if (SelBits > 0x0c) {
4498         Known.One |= 0xFFull << I;
4499       }
4500       Sel >>= 8;
4501     }
4502     break;
4503   }
4504   case AMDGPUISD::BUFFER_LOAD_UBYTE:  {
4505     Known.Zero.setHighBits(24);
4506     break;
4507   }
4508   case AMDGPUISD::BUFFER_LOAD_USHORT: {
4509     Known.Zero.setHighBits(16);
4510     break;
4511   }
4512   case AMDGPUISD::LDS: {
4513     auto GA = cast<GlobalAddressSDNode>(Op.getOperand(0).getNode());
4514     Align Alignment = GA->getGlobal()->getPointerAlignment(DAG.getDataLayout());
4515 
4516     Known.Zero.setHighBits(16);
4517     Known.Zero.setLowBits(Log2(Alignment));
4518     break;
4519   }
4520   case ISD::INTRINSIC_WO_CHAIN: {
4521     unsigned IID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4522     switch (IID) {
4523     case Intrinsic::amdgcn_mbcnt_lo:
4524     case Intrinsic::amdgcn_mbcnt_hi: {
4525       const GCNSubtarget &ST =
4526           DAG.getMachineFunction().getSubtarget<GCNSubtarget>();
4527       // These return at most the wavefront size - 1.
4528       unsigned Size = Op.getValueType().getSizeInBits();
4529       Known.Zero.setHighBits(Size - ST.getWavefrontSizeLog2());
4530       break;
4531     }
4532     default:
4533       break;
4534     }
4535   }
4536   }
4537 }
4538 
4539 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
4540     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4541     unsigned Depth) const {
4542   switch (Op.getOpcode()) {
4543   case AMDGPUISD::BFE_I32: {
4544     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4545     if (!Width)
4546       return 1;
4547 
4548     unsigned SignBits = 32 - Width->getZExtValue() + 1;
4549     if (!isNullConstant(Op.getOperand(1)))
4550       return SignBits;
4551 
4552     // TODO: Could probably figure something out with non-0 offsets.
4553     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4554     return std::max(SignBits, Op0SignBits);
4555   }
4556 
4557   case AMDGPUISD::BFE_U32: {
4558     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4559     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
4560   }
4561 
4562   case AMDGPUISD::CARRY:
4563   case AMDGPUISD::BORROW:
4564     return 31;
4565   case AMDGPUISD::BUFFER_LOAD_BYTE:
4566     return 25;
4567   case AMDGPUISD::BUFFER_LOAD_SHORT:
4568     return 17;
4569   case AMDGPUISD::BUFFER_LOAD_UBYTE:
4570     return 24;
4571   case AMDGPUISD::BUFFER_LOAD_USHORT:
4572     return 16;
4573   case AMDGPUISD::FP_TO_FP16:
4574   case AMDGPUISD::FP16_ZEXT:
4575     return 16;
4576   default:
4577     return 1;
4578   }
4579 }
4580 
4581 unsigned AMDGPUTargetLowering::computeNumSignBitsForTargetInstr(
4582   GISelKnownBits &Analysis, Register R,
4583   const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4584   unsigned Depth) const {
4585   const MachineInstr *MI = MRI.getVRegDef(R);
4586   if (!MI)
4587     return 1;
4588 
4589   // TODO: Check range metadata on MMO.
4590   switch (MI->getOpcode()) {
4591   case AMDGPU::G_AMDGPU_BUFFER_LOAD_SBYTE:
4592     return 25;
4593   case AMDGPU::G_AMDGPU_BUFFER_LOAD_SSHORT:
4594     return 17;
4595   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
4596     return 24;
4597   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
4598     return 16;
4599   default:
4600     return 1;
4601   }
4602 }
4603 
4604 bool AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
4605                                                         const SelectionDAG &DAG,
4606                                                         bool SNaN,
4607                                                         unsigned Depth) const {
4608   unsigned Opcode = Op.getOpcode();
4609   switch (Opcode) {
4610   case AMDGPUISD::FMIN_LEGACY:
4611   case AMDGPUISD::FMAX_LEGACY: {
4612     if (SNaN)
4613       return true;
4614 
4615     // TODO: Can check no nans on one of the operands for each one, but which
4616     // one?
4617     return false;
4618   }
4619   case AMDGPUISD::FMUL_LEGACY:
4620   case AMDGPUISD::CVT_PKRTZ_F16_F32: {
4621     if (SNaN)
4622       return true;
4623     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4624            DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4625   }
4626   case AMDGPUISD::FMED3:
4627   case AMDGPUISD::FMIN3:
4628   case AMDGPUISD::FMAX3:
4629   case AMDGPUISD::FMAD_FTZ: {
4630     if (SNaN)
4631       return true;
4632     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4633            DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4634            DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4635   }
4636   case AMDGPUISD::CVT_F32_UBYTE0:
4637   case AMDGPUISD::CVT_F32_UBYTE1:
4638   case AMDGPUISD::CVT_F32_UBYTE2:
4639   case AMDGPUISD::CVT_F32_UBYTE3:
4640     return true;
4641 
4642   case AMDGPUISD::RCP:
4643   case AMDGPUISD::RSQ:
4644   case AMDGPUISD::RCP_LEGACY:
4645   case AMDGPUISD::RSQ_CLAMP: {
4646     if (SNaN)
4647       return true;
4648 
4649     // TODO: Need is known positive check.
4650     return false;
4651   }
4652   case AMDGPUISD::LDEXP:
4653   case AMDGPUISD::FRACT: {
4654     if (SNaN)
4655       return true;
4656     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4657   }
4658   case AMDGPUISD::DIV_SCALE:
4659   case AMDGPUISD::DIV_FMAS:
4660   case AMDGPUISD::DIV_FIXUP:
4661     // TODO: Refine on operands.
4662     return SNaN;
4663   case AMDGPUISD::SIN_HW:
4664   case AMDGPUISD::COS_HW: {
4665     // TODO: Need check for infinity
4666     return SNaN;
4667   }
4668   case ISD::INTRINSIC_WO_CHAIN: {
4669     unsigned IntrinsicID
4670       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4671     // TODO: Handle more intrinsics
4672     switch (IntrinsicID) {
4673     case Intrinsic::amdgcn_cubeid:
4674       return true;
4675 
4676     case Intrinsic::amdgcn_frexp_mant: {
4677       if (SNaN)
4678         return true;
4679       return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4680     }
4681     case Intrinsic::amdgcn_cvt_pkrtz: {
4682       if (SNaN)
4683         return true;
4684       return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4685              DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4686     }
4687     case Intrinsic::amdgcn_rcp:
4688     case Intrinsic::amdgcn_rsq:
4689     case Intrinsic::amdgcn_rcp_legacy:
4690     case Intrinsic::amdgcn_rsq_legacy:
4691     case Intrinsic::amdgcn_rsq_clamp: {
4692       if (SNaN)
4693         return true;
4694 
4695       // TODO: Need is known positive check.
4696       return false;
4697     }
4698     case Intrinsic::amdgcn_trig_preop:
4699     case Intrinsic::amdgcn_fdot2:
4700       // TODO: Refine on operand
4701       return SNaN;
4702     case Intrinsic::amdgcn_fma_legacy:
4703       if (SNaN)
4704         return true;
4705       return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4706              DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1) &&
4707              DAG.isKnownNeverNaN(Op.getOperand(3), SNaN, Depth + 1);
4708     default:
4709       return false;
4710     }
4711   }
4712   default:
4713     return false;
4714   }
4715 }
4716 
4717 TargetLowering::AtomicExpansionKind
4718 AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
4719   switch (RMW->getOperation()) {
4720   case AtomicRMWInst::Nand:
4721   case AtomicRMWInst::FAdd:
4722   case AtomicRMWInst::FSub:
4723     return AtomicExpansionKind::CmpXChg;
4724   default:
4725     return AtomicExpansionKind::None;
4726   }
4727 }
4728