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