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