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