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