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