1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief This is the parent TargetLowering class for hardware code gen
12 /// targets.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPUISelLowering.h"
17 #include "AMDGPU.h"
18 #include "AMDGPUCallLowering.h"
19 #include "AMDGPUFrameLowering.h"
20 #include "AMDGPUIntrinsicInfo.h"
21 #include "AMDGPURegisterInfo.h"
22 #include "AMDGPUSubtarget.h"
23 #include "R600MachineFunctionInfo.h"
24 #include "SIMachineFunctionInfo.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "SIInstrInfo.h"
33 using namespace llvm;
34 
35 static bool allocateKernArg(unsigned ValNo, MVT ValVT, MVT LocVT,
36                             CCValAssign::LocInfo LocInfo,
37                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
38   MachineFunction &MF = State.getMachineFunction();
39   AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
40 
41   uint64_t Offset = MFI->allocateKernArg(LocVT.getStoreSize(),
42                                          ArgFlags.getOrigAlign());
43   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
44   return true;
45 }
46 
47 #include "AMDGPUGenCallingConv.inc"
48 
49 // Find a larger type to do a load / store of a vector with.
50 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
51   unsigned StoreSize = VT.getStoreSizeInBits();
52   if (StoreSize <= 32)
53     return EVT::getIntegerVT(Ctx, StoreSize);
54 
55   assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
56   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
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::v4f32, Promote);
71   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
72 
73   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
74   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
75 
76   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
77   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
78 
79   setOperationAction(ISD::LOAD, MVT::i64, Promote);
80   AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
81 
82   setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
83   AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
84 
85   setOperationAction(ISD::LOAD, MVT::f64, Promote);
86   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::v2i32);
87 
88   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
89   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v4i32);
90 
91   // There are no 64-bit extloads. These should be done as a 32-bit extload and
92   // an extension to 64-bit.
93   for (MVT VT : MVT::integer_valuetypes()) {
94     setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
95     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
96     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
97   }
98 
99   for (MVT VT : MVT::integer_valuetypes()) {
100     if (VT == MVT::i64)
101       continue;
102 
103     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
104     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
105     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
106     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
107 
108     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
109     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
110     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
111     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
112 
113     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
114     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
115     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
116     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
117   }
118 
119   for (MVT VT : MVT::integer_vector_valuetypes()) {
120     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
121     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
122     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
123     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
124     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
125     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
126     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
127     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
128     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
129     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
130     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
131     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
132   }
133 
134   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
135   setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
136   setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
137   setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
138 
139   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
140   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
141   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Expand);
142   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f32, Expand);
143 
144   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
145   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
146   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
147   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
148 
149   setOperationAction(ISD::STORE, MVT::f32, Promote);
150   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
151 
152   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
153   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
154 
155   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
156   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
157 
158   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
159   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
160 
161   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
162   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
163 
164   setOperationAction(ISD::STORE, MVT::i64, Promote);
165   AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
166 
167   setOperationAction(ISD::STORE, MVT::v2i64, Promote);
168   AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
169 
170   setOperationAction(ISD::STORE, MVT::f64, Promote);
171   AddPromotedToType(ISD::STORE, MVT::f64, MVT::v2i32);
172 
173   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
174   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v4i32);
175 
176   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
177   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
178   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
179   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
180 
181   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
182   setTruncStoreAction(MVT::v2i64, MVT::v2i8, Expand);
183   setTruncStoreAction(MVT::v2i64, MVT::v2i16, Expand);
184   setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
185 
186   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
187   setTruncStoreAction(MVT::v2f32, MVT::v2f16, Expand);
188   setTruncStoreAction(MVT::v4f32, MVT::v4f16, Expand);
189   setTruncStoreAction(MVT::v8f32, MVT::v8f16, Expand);
190 
191   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
192   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
193 
194   setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
195   setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
196 
197   setTruncStoreAction(MVT::v4f64, MVT::v4f32, Expand);
198   setTruncStoreAction(MVT::v4f64, MVT::v4f16, Expand);
199 
200   setTruncStoreAction(MVT::v8f64, MVT::v8f32, Expand);
201   setTruncStoreAction(MVT::v8f64, MVT::v8f16, Expand);
202 
203 
204   setOperationAction(ISD::Constant, MVT::i32, Legal);
205   setOperationAction(ISD::Constant, MVT::i64, Legal);
206   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
207   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
208 
209   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
210   setOperationAction(ISD::BRIND, MVT::Other, Expand);
211 
212   // This is totally unsupported, just custom lower to produce an error.
213   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
214 
215   // We need to custom lower some of the intrinsics
216   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
217   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
218 
219   // Library functions.  These default to Expand, but we have instructions
220   // for them.
221   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
222   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
223   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
224   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
225   setOperationAction(ISD::FABS,   MVT::f32, Legal);
226   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
227   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
228   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
229   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
230   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
231 
232   setOperationAction(ISD::FROUND, MVT::f32, Custom);
233   setOperationAction(ISD::FROUND, MVT::f64, Custom);
234 
235   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
236   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
237 
238   setOperationAction(ISD::FREM, MVT::f32, Custom);
239   setOperationAction(ISD::FREM, MVT::f64, Custom);
240 
241   // v_mad_f32 does not support denormals according to some sources.
242   if (!Subtarget->hasFP32Denormals())
243     setOperationAction(ISD::FMAD, MVT::f32, Legal);
244 
245   // Expand to fneg + fadd.
246   setOperationAction(ISD::FSUB, MVT::f64, Expand);
247 
248   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
249   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
250   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
251   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
252   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
253   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
254   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
255   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
256   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
257   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
258 
259   if (Subtarget->getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
260     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
261     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
262     setOperationAction(ISD::FRINT, MVT::f64, Custom);
263     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
264   }
265 
266   if (!Subtarget->hasBFI()) {
267     // fcopysign can be done in a single instruction with BFI.
268     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
269     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
270   }
271 
272   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
273   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Custom);
274 
275   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
276   for (MVT VT : ScalarIntVTs) {
277     // These should use [SU]DIVREM, so set them to expand
278     setOperationAction(ISD::SDIV, VT, Expand);
279     setOperationAction(ISD::UDIV, VT, Expand);
280     setOperationAction(ISD::SREM, VT, Expand);
281     setOperationAction(ISD::UREM, VT, Expand);
282 
283     // GPU does not have divrem function for signed or unsigned.
284     setOperationAction(ISD::SDIVREM, VT, Custom);
285     setOperationAction(ISD::UDIVREM, VT, Custom);
286 
287     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
288     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
289     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
290 
291     setOperationAction(ISD::BSWAP, VT, Expand);
292     setOperationAction(ISD::CTTZ, VT, Expand);
293     setOperationAction(ISD::CTLZ, VT, Expand);
294   }
295 
296   if (!Subtarget->hasBCNT(32))
297     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
298 
299   if (!Subtarget->hasBCNT(64))
300     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
301 
302   // The hardware supports 32-bit ROTR, but not ROTL.
303   setOperationAction(ISD::ROTL, MVT::i32, Expand);
304   setOperationAction(ISD::ROTL, MVT::i64, Expand);
305   setOperationAction(ISD::ROTR, MVT::i64, Expand);
306 
307   setOperationAction(ISD::MUL, MVT::i64, Expand);
308   setOperationAction(ISD::MULHU, MVT::i64, Expand);
309   setOperationAction(ISD::MULHS, MVT::i64, Expand);
310   setOperationAction(ISD::UDIV, MVT::i32, Expand);
311   setOperationAction(ISD::UREM, MVT::i32, Expand);
312   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
313   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
314   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
315   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
316   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
317 
318   setOperationAction(ISD::SMIN, MVT::i32, Legal);
319   setOperationAction(ISD::UMIN, MVT::i32, Legal);
320   setOperationAction(ISD::SMAX, MVT::i32, Legal);
321   setOperationAction(ISD::UMAX, MVT::i32, Legal);
322 
323   if (Subtarget->hasFFBH())
324     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
325 
326   if (Subtarget->hasFFBL())
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Legal);
328 
329   setOperationAction(ISD::CTLZ, MVT::i64, Custom);
330   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
331 
332   // We only really have 32-bit BFE instructions (and 16-bit on VI).
333   //
334   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
335   // effort to match them now. We want this to be false for i64 cases when the
336   // extraction isn't restricted to the upper or lower half. Ideally we would
337   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
338   // span the midpoint are probably relatively rare, so don't worry about them
339   // for now.
340   if (Subtarget->hasBFE())
341     setHasExtractBitsInsn(true);
342 
343   static const MVT::SimpleValueType VectorIntTypes[] = {
344     MVT::v2i32, MVT::v4i32
345   };
346 
347   for (MVT VT : VectorIntTypes) {
348     // Expand the following operations for the current type by default.
349     setOperationAction(ISD::ADD,  VT, Expand);
350     setOperationAction(ISD::AND,  VT, Expand);
351     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
352     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
353     setOperationAction(ISD::MUL,  VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::MULHS, VT, Expand);
356     setOperationAction(ISD::OR,   VT, Expand);
357     setOperationAction(ISD::SHL,  VT, Expand);
358     setOperationAction(ISD::SRA,  VT, Expand);
359     setOperationAction(ISD::SRL,  VT, Expand);
360     setOperationAction(ISD::ROTL, VT, Expand);
361     setOperationAction(ISD::ROTR, VT, Expand);
362     setOperationAction(ISD::SUB,  VT, Expand);
363     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
364     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
365     setOperationAction(ISD::SDIV, VT, Expand);
366     setOperationAction(ISD::UDIV, VT, Expand);
367     setOperationAction(ISD::SREM, VT, Expand);
368     setOperationAction(ISD::UREM, VT, Expand);
369     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
370     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
371     setOperationAction(ISD::SDIVREM, VT, Custom);
372     setOperationAction(ISD::UDIVREM, VT, Expand);
373     setOperationAction(ISD::ADDC, VT, Expand);
374     setOperationAction(ISD::SUBC, VT, Expand);
375     setOperationAction(ISD::ADDE, VT, Expand);
376     setOperationAction(ISD::SUBE, VT, Expand);
377     setOperationAction(ISD::SELECT, VT, Expand);
378     setOperationAction(ISD::VSELECT, VT, Expand);
379     setOperationAction(ISD::SELECT_CC, VT, Expand);
380     setOperationAction(ISD::XOR,  VT, Expand);
381     setOperationAction(ISD::BSWAP, VT, Expand);
382     setOperationAction(ISD::CTPOP, VT, Expand);
383     setOperationAction(ISD::CTTZ, VT, Expand);
384     setOperationAction(ISD::CTLZ, VT, Expand);
385     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
386   }
387 
388   static const MVT::SimpleValueType FloatVectorTypes[] = {
389     MVT::v2f32, MVT::v4f32
390   };
391 
392   for (MVT VT : FloatVectorTypes) {
393     setOperationAction(ISD::FABS, VT, Expand);
394     setOperationAction(ISD::FMINNUM, VT, Expand);
395     setOperationAction(ISD::FMAXNUM, VT, Expand);
396     setOperationAction(ISD::FADD, VT, Expand);
397     setOperationAction(ISD::FCEIL, VT, Expand);
398     setOperationAction(ISD::FCOS, VT, Expand);
399     setOperationAction(ISD::FDIV, VT, Expand);
400     setOperationAction(ISD::FEXP2, VT, Expand);
401     setOperationAction(ISD::FLOG2, VT, Expand);
402     setOperationAction(ISD::FREM, VT, Expand);
403     setOperationAction(ISD::FPOW, VT, Expand);
404     setOperationAction(ISD::FFLOOR, VT, Expand);
405     setOperationAction(ISD::FTRUNC, VT, Expand);
406     setOperationAction(ISD::FMUL, VT, Expand);
407     setOperationAction(ISD::FMA, VT, Expand);
408     setOperationAction(ISD::FRINT, VT, Expand);
409     setOperationAction(ISD::FNEARBYINT, VT, Expand);
410     setOperationAction(ISD::FSQRT, VT, Expand);
411     setOperationAction(ISD::FSIN, VT, Expand);
412     setOperationAction(ISD::FSUB, VT, Expand);
413     setOperationAction(ISD::FNEG, VT, Expand);
414     setOperationAction(ISD::VSELECT, VT, Expand);
415     setOperationAction(ISD::SELECT_CC, VT, Expand);
416     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
417     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
418   }
419 
420   // This causes using an unrolled select operation rather than expansion with
421   // bit operations. This is in general better, but the alternative using BFI
422   // instructions may be better if the select sources are SGPRs.
423   setOperationAction(ISD::SELECT, MVT::v2f32, Promote);
424   AddPromotedToType(ISD::SELECT, MVT::v2f32, MVT::v2i32);
425 
426   setOperationAction(ISD::SELECT, MVT::v4f32, Promote);
427   AddPromotedToType(ISD::SELECT, MVT::v4f32, MVT::v4i32);
428 
429   // There are no libcalls of any kind.
430   for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
431     setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
432 
433   setBooleanContents(ZeroOrNegativeOneBooleanContent);
434   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
435 
436   setSchedulingPreference(Sched::RegPressure);
437   setJumpIsExpensive(true);
438 
439   // FIXME: This is only partially true. If we have to do vector compares, any
440   // SGPR pair can be a condition register. If we have a uniform condition, we
441   // are better off doing SALU operations, where there is only one SCC. For now,
442   // we don't have a way of knowing during instruction selection if a condition
443   // will be uniform and we always use vector compares. Assume we are using
444   // vector compares until that is fixed.
445   setHasMultipleConditionRegisters(true);
446 
447   // SI at least has hardware support for floating point exceptions, but no way
448   // of using or handling them is implemented. They are also optional in OpenCL
449   // (Section 7.3)
450   setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
451 
452   PredictableSelectIsExpensive = false;
453 
454   // We want to find all load dependencies for long chains of stores to enable
455   // merging into very wide vectors. The problem is with vectors with > 4
456   // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
457   // vectors are a legal type, even though we have to split the loads
458   // usually. When we can more precisely specify load legality per address
459   // space, we should be able to make FindBetterChain/MergeConsecutiveStores
460   // smarter so that they can figure out what to do in 2 iterations without all
461   // N > 4 stores on the same chain.
462   GatherAllAliasesMaxDepth = 16;
463 
464   // FIXME: Need to really handle these.
465   MaxStoresPerMemcpy  = 4096;
466   MaxStoresPerMemmove = 4096;
467   MaxStoresPerMemset  = 4096;
468 
469   setTargetDAGCombine(ISD::BITCAST);
470   setTargetDAGCombine(ISD::SHL);
471   setTargetDAGCombine(ISD::SRA);
472   setTargetDAGCombine(ISD::SRL);
473   setTargetDAGCombine(ISD::MUL);
474   setTargetDAGCombine(ISD::MULHU);
475   setTargetDAGCombine(ISD::MULHS);
476   setTargetDAGCombine(ISD::SELECT);
477   setTargetDAGCombine(ISD::SELECT_CC);
478   setTargetDAGCombine(ISD::STORE);
479   setTargetDAGCombine(ISD::FADD);
480   setTargetDAGCombine(ISD::FSUB);
481   setTargetDAGCombine(ISD::FNEG);
482   setTargetDAGCombine(ISD::FABS);
483 }
484 
485 //===----------------------------------------------------------------------===//
486 // Target Information
487 //===----------------------------------------------------------------------===//
488 
489 static bool fnegFoldsIntoOp(unsigned Opc) {
490   switch (Opc) {
491   case ISD::FADD:
492   case ISD::FSUB:
493   case ISD::FMUL:
494   case ISD::FMA:
495   case ISD::FMAD:
496   case ISD::FSIN:
497   case ISD::FTRUNC:
498   case ISD::FRINT:
499   case ISD::FNEARBYINT:
500   case AMDGPUISD::RCP:
501   case AMDGPUISD::RCP_LEGACY:
502   case AMDGPUISD::SIN_HW:
503   case AMDGPUISD::FMUL_LEGACY:
504     return true;
505   default:
506     return false;
507   }
508 }
509 
510 MVT AMDGPUTargetLowering::getVectorIdxTy(const DataLayout &) const {
511   return MVT::i32;
512 }
513 
514 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
515   return true;
516 }
517 
518 // The backend supports 32 and 64 bit floating point immediates.
519 // FIXME: Why are we reporting vectors of FP immediates as legal?
520 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
521   EVT ScalarVT = VT.getScalarType();
522   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
523          (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
524 }
525 
526 // We don't want to shrink f64 / f32 constants.
527 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
528   EVT ScalarVT = VT.getScalarType();
529   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
530 }
531 
532 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
533                                                  ISD::LoadExtType,
534                                                  EVT NewVT) const {
535 
536   unsigned NewSize = NewVT.getStoreSizeInBits();
537 
538   // If we are reducing to a 32-bit load, this is always better.
539   if (NewSize == 32)
540     return true;
541 
542   EVT OldVT = N->getValueType(0);
543   unsigned OldSize = OldVT.getStoreSizeInBits();
544 
545   // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
546   // extloads, so doing one requires using a buffer_load. In cases where we
547   // still couldn't use a scalar load, using the wider load shouldn't really
548   // hurt anything.
549 
550   // If the old size already had to be an extload, there's no harm in continuing
551   // to reduce the width.
552   return (OldSize < 32);
553 }
554 
555 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
556                                                    EVT CastTy) const {
557 
558   assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
559 
560   if (LoadTy.getScalarType() == MVT::i32)
561     return false;
562 
563   unsigned LScalarSize = LoadTy.getScalarSizeInBits();
564   unsigned CastScalarSize = CastTy.getScalarSizeInBits();
565 
566   return (LScalarSize < CastScalarSize) ||
567          (CastScalarSize >= 32);
568 }
569 
570 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
571 // profitable with the expansion for 64-bit since it's generally good to
572 // speculate things.
573 // FIXME: These should really have the size as a parameter.
574 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
575   return true;
576 }
577 
578 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
579   return true;
580 }
581 
582 //===---------------------------------------------------------------------===//
583 // Target Properties
584 //===---------------------------------------------------------------------===//
585 
586 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
587   assert(VT.isFloatingPoint());
588   return VT == MVT::f32 || VT == MVT::f64 || (Subtarget->has16BitInsts() &&
589                                               VT == MVT::f16);
590 }
591 
592 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
593   return isFAbsFree(VT);
594 }
595 
596 bool AMDGPUTargetLowering:: storeOfVectorConstantIsCheap(EVT MemVT,
597                                                          unsigned NumElem,
598                                                          unsigned AS) const {
599   return true;
600 }
601 
602 bool AMDGPUTargetLowering::aggressivelyPreferBuildVectorSources(EVT VecVT) const {
603   // There are few operations which truly have vector input operands. Any vector
604   // operation is going to involve operations on each component, and a
605   // build_vector will be a copy per element, so it always makes sense to use a
606   // build_vector input in place of the extracted element to avoid a copy into a
607   // super register.
608   //
609   // We should probably only do this if all users are extracts only, but this
610   // should be the common case.
611   return true;
612 }
613 
614 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
615   // Truncate is just accessing a subregister.
616 
617   unsigned SrcSize = Source.getSizeInBits();
618   unsigned DestSize = Dest.getSizeInBits();
619 
620   return DestSize < SrcSize && DestSize % 32 == 0 ;
621 }
622 
623 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
624   // Truncate is just accessing a subregister.
625 
626   unsigned SrcSize = Source->getScalarSizeInBits();
627   unsigned DestSize = Dest->getScalarSizeInBits();
628 
629   if (DestSize== 16 && Subtarget->has16BitInsts())
630     return SrcSize >= 32;
631 
632   return DestSize < SrcSize && DestSize % 32 == 0;
633 }
634 
635 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
636   unsigned SrcSize = Src->getScalarSizeInBits();
637   unsigned DestSize = Dest->getScalarSizeInBits();
638 
639   if (SrcSize == 16 && Subtarget->has16BitInsts())
640     return DestSize >= 32;
641 
642   return SrcSize == 32 && DestSize == 64;
643 }
644 
645 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
646   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
647   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
648   // this will enable reducing 64-bit operations the 32-bit, which is always
649   // good.
650 
651   if (Src == MVT::i16)
652     return Dest == MVT::i32 ||Dest == MVT::i64 ;
653 
654   return Src == MVT::i32 && Dest == MVT::i64;
655 }
656 
657 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
658   return isZExtFree(Val.getValueType(), VT2);
659 }
660 
661 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
662   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
663   // limited number of native 64-bit operations. Shrinking an operation to fit
664   // in a single 32-bit register should always be helpful. As currently used,
665   // this is much less general than the name suggests, and is only used in
666   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
667   // not profitable, and may actually be harmful.
668   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
669 }
670 
671 //===---------------------------------------------------------------------===//
672 // TargetLowering Callbacks
673 //===---------------------------------------------------------------------===//
674 
675 CCAssignFn *AMDGPUCallLowering::CCAssignFnForCall(CallingConv::ID CC,
676                                                   bool IsVarArg) const {
677   return CC_AMDGPU;
678 }
679 
680 /// The SelectionDAGBuilder will automatically promote function arguments
681 /// with illegal types.  However, this does not work for the AMDGPU targets
682 /// since the function arguments are stored in memory as these illegal types.
683 /// In order to handle this properly we need to get the original types sizes
684 /// from the LLVM IR Function and fixup the ISD:InputArg values before
685 /// passing them to AnalyzeFormalArguments()
686 
687 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
688 /// input values across multiple registers.  Each item in the Ins array
689 /// represents a single value that will be stored in regsters.  Ins[x].VT is
690 /// the value type of the value that will be stored in the register, so
691 /// whatever SDNode we lower the argument to needs to be this type.
692 ///
693 /// In order to correctly lower the arguments we need to know the size of each
694 /// argument.  Since Ins[x].VT gives us the size of the register that will
695 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
696 /// for the orignal function argument so that we can deduce the correct memory
697 /// type to use for Ins[x].  In most cases the correct memory type will be
698 /// Ins[x].ArgVT.  However, this will not always be the case.  If, for example,
699 /// we have a kernel argument of type v8i8, this argument will be split into
700 /// 8 parts and each part will be represented by its own item in the Ins array.
701 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
702 /// the argument before it was split.  From this, we deduce that the memory type
703 /// for each individual part is i8.  We pass the memory type as LocVT to the
704 /// calling convention analysis function and the register type (Ins[x].VT) as
705 /// the ValVT.
706 void AMDGPUTargetLowering::analyzeFormalArgumentsCompute(CCState &State,
707                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
708   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
709     const ISD::InputArg &In = Ins[i];
710     EVT MemVT;
711 
712     unsigned NumRegs = getNumRegisters(State.getContext(), In.ArgVT);
713 
714     if (!Subtarget->isAmdHsaOS() &&
715         (In.ArgVT == MVT::i16 || In.ArgVT == MVT::i8 || In.ArgVT == MVT::f16)) {
716       // The ABI says the caller will extend these values to 32-bits.
717       MemVT = In.ArgVT.isInteger() ? MVT::i32 : MVT::f32;
718     } else if (NumRegs == 1) {
719       // This argument is not split, so the IR type is the memory type.
720       assert(!In.Flags.isSplit());
721       if (In.ArgVT.isExtended()) {
722         // We have an extended type, like i24, so we should just use the register type
723         MemVT = In.VT;
724       } else {
725         MemVT = In.ArgVT;
726       }
727     } else if (In.ArgVT.isVector() && In.VT.isVector() &&
728                In.ArgVT.getScalarType() == In.VT.getScalarType()) {
729       assert(In.ArgVT.getVectorNumElements() > In.VT.getVectorNumElements());
730       // We have a vector value which has been split into a vector with
731       // the same scalar type, but fewer elements.  This should handle
732       // all the floating-point vector types.
733       MemVT = In.VT;
734     } else if (In.ArgVT.isVector() &&
735                In.ArgVT.getVectorNumElements() == NumRegs) {
736       // This arg has been split so that each element is stored in a separate
737       // register.
738       MemVT = In.ArgVT.getScalarType();
739     } else if (In.ArgVT.isExtended()) {
740       // We have an extended type, like i65.
741       MemVT = In.VT;
742     } else {
743       unsigned MemoryBits = In.ArgVT.getStoreSizeInBits() / NumRegs;
744       assert(In.ArgVT.getStoreSizeInBits() % NumRegs == 0);
745       if (In.VT.isInteger()) {
746         MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
747       } else if (In.VT.isVector()) {
748         assert(!In.VT.getScalarType().isFloatingPoint());
749         unsigned NumElements = In.VT.getVectorNumElements();
750         assert(MemoryBits % NumElements == 0);
751         // This vector type has been split into another vector type with
752         // a different elements size.
753         EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
754                                          MemoryBits / NumElements);
755         MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
756       } else {
757         llvm_unreachable("cannot deduce memory type.");
758       }
759     }
760 
761     // Convert one element vectors to scalar.
762     if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
763       MemVT = MemVT.getScalarType();
764 
765     if (MemVT.isExtended()) {
766       // This should really only happen if we have vec3 arguments
767       assert(MemVT.isVector() && MemVT.getVectorNumElements() == 3);
768       MemVT = MemVT.getPow2VectorType(State.getContext());
769     }
770 
771     assert(MemVT.isSimple());
772     allocateKernArg(i, In.VT, MemVT.getSimpleVT(), CCValAssign::Full, In.Flags,
773                     State);
774   }
775 }
776 
777 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
778                               const SmallVectorImpl<ISD::InputArg> &Ins) const {
779   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
780 }
781 
782 void AMDGPUTargetLowering::AnalyzeReturn(CCState &State,
783                            const SmallVectorImpl<ISD::OutputArg> &Outs) const {
784 
785   State.AnalyzeReturn(Outs, RetCC_SI);
786 }
787 
788 SDValue
789 AMDGPUTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
790                                   bool isVarArg,
791                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
792                                   const SmallVectorImpl<SDValue> &OutVals,
793                                   const SDLoc &DL, SelectionDAG &DAG) const {
794   return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
795 }
796 
797 //===---------------------------------------------------------------------===//
798 // Target specific lowering
799 //===---------------------------------------------------------------------===//
800 
801 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
802                                         SmallVectorImpl<SDValue> &InVals) const {
803   SDValue Callee = CLI.Callee;
804   SelectionDAG &DAG = CLI.DAG;
805 
806   const Function &Fn = *DAG.getMachineFunction().getFunction();
807 
808   StringRef FuncName("<unknown>");
809 
810   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
811     FuncName = G->getSymbol();
812   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
813     FuncName = G->getGlobal()->getName();
814 
815   DiagnosticInfoUnsupported NoCalls(
816       Fn, "unsupported call to function " + FuncName, CLI.DL.getDebugLoc());
817   DAG.getContext()->diagnose(NoCalls);
818 
819   if (!CLI.IsTailCall) {
820     for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
821       InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
822   }
823 
824   return DAG.getEntryNode();
825 }
826 
827 SDValue AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
828                                                       SelectionDAG &DAG) const {
829   const Function &Fn = *DAG.getMachineFunction().getFunction();
830 
831   DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
832                                             SDLoc(Op).getDebugLoc());
833   DAG.getContext()->diagnose(NoDynamicAlloca);
834   auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
835   return DAG.getMergeValues(Ops, SDLoc());
836 }
837 
838 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
839                                              SelectionDAG &DAG) const {
840   switch (Op.getOpcode()) {
841   default:
842     Op->print(errs(), &DAG);
843     llvm_unreachable("Custom lowering code for this"
844                      "instruction is not implemented yet!");
845     break;
846   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
847   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
848   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
849   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
850   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
851   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
852   case ISD::FREM: return LowerFREM(Op, DAG);
853   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
854   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
855   case ISD::FRINT: return LowerFRINT(Op, DAG);
856   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
857   case ISD::FROUND: return LowerFROUND(Op, DAG);
858   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
859   case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
860   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
861   case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
862   case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
863   case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
864   case ISD::CTLZ:
865   case ISD::CTLZ_ZERO_UNDEF:
866     return LowerCTLZ(Op, DAG);
867   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
868   }
869   return Op;
870 }
871 
872 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
873                                               SmallVectorImpl<SDValue> &Results,
874                                               SelectionDAG &DAG) const {
875   switch (N->getOpcode()) {
876   case ISD::SIGN_EXTEND_INREG:
877     // Different parts of legalization seem to interpret which type of
878     // sign_extend_inreg is the one to check for custom lowering. The extended
879     // from type is what really matters, but some places check for custom
880     // lowering of the result type. This results in trying to use
881     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
882     // nothing here and let the illegal result integer be handled normally.
883     return;
884   default:
885     return;
886   }
887 }
888 
889 static bool hasDefinedInitializer(const GlobalValue *GV) {
890   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
891   if (!GVar || !GVar->hasInitializer())
892     return false;
893 
894   return !isa<UndefValue>(GVar->getInitializer());
895 }
896 
897 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
898                                                  SDValue Op,
899                                                  SelectionDAG &DAG) const {
900 
901   const DataLayout &DL = DAG.getDataLayout();
902   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
903   const GlobalValue *GV = G->getGlobal();
904 
905   switch (G->getAddressSpace()) {
906   case AMDGPUAS::LOCAL_ADDRESS: {
907     // XXX: What does the value of G->getOffset() mean?
908     assert(G->getOffset() == 0 &&
909          "Do not know what to do with an non-zero offset");
910 
911     // TODO: We could emit code to handle the initialization somewhere.
912     if (hasDefinedInitializer(GV))
913       break;
914 
915     unsigned Offset = MFI->allocateLDSGlobal(DL, *GV);
916     return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
917   }
918   }
919 
920   const Function &Fn = *DAG.getMachineFunction().getFunction();
921   DiagnosticInfoUnsupported BadInit(
922       Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
923   DAG.getContext()->diagnose(BadInit);
924   return SDValue();
925 }
926 
927 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
928                                                   SelectionDAG &DAG) const {
929   SmallVector<SDValue, 8> Args;
930 
931   for (const SDUse &U : Op->ops())
932     DAG.ExtractVectorElements(U.get(), Args);
933 
934   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
935 }
936 
937 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
938                                                      SelectionDAG &DAG) const {
939 
940   SmallVector<SDValue, 8> Args;
941   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
942   EVT VT = Op.getValueType();
943   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
944                             VT.getVectorNumElements());
945 
946   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
947 }
948 
949 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
950     SelectionDAG &DAG) const {
951   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
952   SDLoc DL(Op);
953   EVT VT = Op.getValueType();
954 
955   switch (IntrinsicID) {
956     default: return Op;
957     case AMDGPUIntrinsic::AMDGPU_clamp: // Legacy name.
958       return DAG.getNode(AMDGPUISD::CLAMP, DL, VT,
959                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
960 
961     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
962       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
963                          Op.getOperand(1),
964                          Op.getOperand(2),
965                          Op.getOperand(3));
966 
967     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
968       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
969                          Op.getOperand(1),
970                          Op.getOperand(2),
971                          Op.getOperand(3));
972   }
973 }
974 
975 /// \brief Generate Min/Max node
976 SDValue AMDGPUTargetLowering::combineFMinMaxLegacy(const SDLoc &DL, EVT VT,
977                                                    SDValue LHS, SDValue RHS,
978                                                    SDValue True, SDValue False,
979                                                    SDValue CC,
980                                                    DAGCombinerInfo &DCI) const {
981   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
982     return SDValue();
983 
984   SelectionDAG &DAG = DCI.DAG;
985   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
986   switch (CCOpcode) {
987   case ISD::SETOEQ:
988   case ISD::SETONE:
989   case ISD::SETUNE:
990   case ISD::SETNE:
991   case ISD::SETUEQ:
992   case ISD::SETEQ:
993   case ISD::SETFALSE:
994   case ISD::SETFALSE2:
995   case ISD::SETTRUE:
996   case ISD::SETTRUE2:
997   case ISD::SETUO:
998   case ISD::SETO:
999     break;
1000   case ISD::SETULE:
1001   case ISD::SETULT: {
1002     if (LHS == True)
1003       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1004     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1005   }
1006   case ISD::SETOLE:
1007   case ISD::SETOLT:
1008   case ISD::SETLE:
1009   case ISD::SETLT: {
1010     // Ordered. Assume ordered for undefined.
1011 
1012     // Only do this after legalization to avoid interfering with other combines
1013     // which might occur.
1014     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1015         !DCI.isCalledByLegalizer())
1016       return SDValue();
1017 
1018     // We need to permute the operands to get the correct NaN behavior. The
1019     // selected operand is the second one based on the failing compare with NaN,
1020     // so permute it based on the compare type the hardware uses.
1021     if (LHS == True)
1022       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1023     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1024   }
1025   case ISD::SETUGE:
1026   case ISD::SETUGT: {
1027     if (LHS == True)
1028       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1029     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1030   }
1031   case ISD::SETGT:
1032   case ISD::SETGE:
1033   case ISD::SETOGE:
1034   case ISD::SETOGT: {
1035     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1036         !DCI.isCalledByLegalizer())
1037       return SDValue();
1038 
1039     if (LHS == True)
1040       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1041     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1042   }
1043   case ISD::SETCC_INVALID:
1044     llvm_unreachable("Invalid setcc condcode!");
1045   }
1046   return SDValue();
1047 }
1048 
1049 std::pair<SDValue, SDValue>
1050 AMDGPUTargetLowering::split64BitValue(SDValue Op, SelectionDAG &DAG) const {
1051   SDLoc SL(Op);
1052 
1053   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1054 
1055   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1056   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1057 
1058   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1059   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1060 
1061   return std::make_pair(Lo, Hi);
1062 }
1063 
1064 SDValue AMDGPUTargetLowering::getLoHalf64(SDValue Op, SelectionDAG &DAG) const {
1065   SDLoc SL(Op);
1066 
1067   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1068   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1069   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1070 }
1071 
1072 SDValue AMDGPUTargetLowering::getHiHalf64(SDValue Op, SelectionDAG &DAG) const {
1073   SDLoc SL(Op);
1074 
1075   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1076   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1077   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1078 }
1079 
1080 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1081                                               SelectionDAG &DAG) const {
1082   LoadSDNode *Load = cast<LoadSDNode>(Op);
1083   EVT VT = Op.getValueType();
1084 
1085 
1086   // If this is a 2 element vector, we really want to scalarize and not create
1087   // weird 1 element vectors.
1088   if (VT.getVectorNumElements() == 2)
1089     return scalarizeVectorLoad(Load, DAG);
1090 
1091   SDValue BasePtr = Load->getBasePtr();
1092   EVT PtrVT = BasePtr.getValueType();
1093   EVT MemVT = Load->getMemoryVT();
1094   SDLoc SL(Op);
1095 
1096   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1097 
1098   EVT LoVT, HiVT;
1099   EVT LoMemVT, HiMemVT;
1100   SDValue Lo, Hi;
1101 
1102   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1103   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1104   std::tie(Lo, Hi) = DAG.SplitVector(Op, SL, LoVT, HiVT);
1105 
1106   unsigned Size = LoMemVT.getStoreSize();
1107   unsigned BaseAlign = Load->getAlignment();
1108   unsigned HiAlign = MinAlign(BaseAlign, Size);
1109 
1110   SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1111                                   Load->getChain(), BasePtr, SrcValue, LoMemVT,
1112                                   BaseAlign, Load->getMemOperand()->getFlags());
1113   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1114                               DAG.getConstant(Size, SL, PtrVT));
1115   SDValue HiLoad =
1116       DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1117                      HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1118                      HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1119 
1120   SDValue Ops[] = {
1121     DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad),
1122     DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1123                 LoLoad.getValue(1), HiLoad.getValue(1))
1124   };
1125 
1126   return DAG.getMergeValues(Ops, SL);
1127 }
1128 
1129 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1130                                                SelectionDAG &DAG) const {
1131   StoreSDNode *Store = cast<StoreSDNode>(Op);
1132   SDValue Val = Store->getValue();
1133   EVT VT = Val.getValueType();
1134 
1135   // If this is a 2 element vector, we really want to scalarize and not create
1136   // weird 1 element vectors.
1137   if (VT.getVectorNumElements() == 2)
1138     return scalarizeVectorStore(Store, DAG);
1139 
1140   EVT MemVT = Store->getMemoryVT();
1141   SDValue Chain = Store->getChain();
1142   SDValue BasePtr = Store->getBasePtr();
1143   SDLoc SL(Op);
1144 
1145   EVT LoVT, HiVT;
1146   EVT LoMemVT, HiMemVT;
1147   SDValue Lo, Hi;
1148 
1149   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1150   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1151   std::tie(Lo, Hi) = DAG.SplitVector(Val, SL, LoVT, HiVT);
1152 
1153   EVT PtrVT = BasePtr.getValueType();
1154   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1155                               DAG.getConstant(LoMemVT.getStoreSize(), SL,
1156                                               PtrVT));
1157 
1158   const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1159   unsigned BaseAlign = Store->getAlignment();
1160   unsigned Size = LoMemVT.getStoreSize();
1161   unsigned HiAlign = MinAlign(BaseAlign, Size);
1162 
1163   SDValue LoStore =
1164       DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1165                         Store->getMemOperand()->getFlags());
1166   SDValue HiStore =
1167       DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1168                         HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1169 
1170   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1171 }
1172 
1173 // This is a shortcut for integer division because we have fast i32<->f32
1174 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1175 // float is enough to accurately represent up to a 24-bit signed integer.
1176 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG,
1177                                             bool Sign) const {
1178   SDLoc DL(Op);
1179   EVT VT = Op.getValueType();
1180   SDValue LHS = Op.getOperand(0);
1181   SDValue RHS = Op.getOperand(1);
1182   MVT IntVT = MVT::i32;
1183   MVT FltVT = MVT::f32;
1184 
1185   unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1186   if (LHSSignBits < 9)
1187     return SDValue();
1188 
1189   unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1190   if (RHSSignBits < 9)
1191     return SDValue();
1192 
1193   unsigned BitSize = VT.getSizeInBits();
1194   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1195   unsigned DivBits = BitSize - SignBits;
1196   if (Sign)
1197     ++DivBits;
1198 
1199   ISD::NodeType ToFp = Sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1200   ISD::NodeType ToInt = Sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1201 
1202   SDValue jq = DAG.getConstant(1, DL, IntVT);
1203 
1204   if (Sign) {
1205     // char|short jq = ia ^ ib;
1206     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1207 
1208     // jq = jq >> (bitsize - 2)
1209     jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1210                      DAG.getConstant(BitSize - 2, DL, VT));
1211 
1212     // jq = jq | 0x1
1213     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1214   }
1215 
1216   // int ia = (int)LHS;
1217   SDValue ia = LHS;
1218 
1219   // int ib, (int)RHS;
1220   SDValue ib = RHS;
1221 
1222   // float fa = (float)ia;
1223   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1224 
1225   // float fb = (float)ib;
1226   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1227 
1228   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1229                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1230 
1231   // fq = trunc(fq);
1232   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1233 
1234   // float fqneg = -fq;
1235   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1236 
1237   // float fr = mad(fqneg, fb, fa);
1238   SDValue fr = DAG.getNode(ISD::FMAD, DL, FltVT, fqneg, fb, fa);
1239 
1240   // int iq = (int)fq;
1241   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1242 
1243   // fr = fabs(fr);
1244   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1245 
1246   // fb = fabs(fb);
1247   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1248 
1249   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1250 
1251   // int cv = fr >= fb;
1252   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1253 
1254   // jq = (cv ? jq : 0);
1255   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1256 
1257   // dst = iq + jq;
1258   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1259 
1260   // Rem needs compensation, it's easier to recompute it
1261   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1262   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1263 
1264   // Truncate to number of bits this divide really is.
1265   if (Sign) {
1266     SDValue InRegSize
1267       = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1268     Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1269     Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1270   } else {
1271     SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1272     Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1273     Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1274   }
1275 
1276   return DAG.getMergeValues({ Div, Rem }, DL);
1277 }
1278 
1279 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1280                                       SelectionDAG &DAG,
1281                                       SmallVectorImpl<SDValue> &Results) const {
1282   assert(Op.getValueType() == MVT::i64);
1283 
1284   SDLoc DL(Op);
1285   EVT VT = Op.getValueType();
1286   EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1287 
1288   SDValue one = DAG.getConstant(1, DL, HalfVT);
1289   SDValue zero = DAG.getConstant(0, DL, HalfVT);
1290 
1291   //HiLo split
1292   SDValue LHS = Op.getOperand(0);
1293   SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
1294   SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
1295 
1296   SDValue RHS = Op.getOperand(1);
1297   SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
1298   SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
1299 
1300   if (VT == MVT::i64 &&
1301     DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1302     DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1303 
1304     SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1305                               LHS_Lo, RHS_Lo);
1306 
1307     SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), zero});
1308     SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), zero});
1309 
1310     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1311     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1312     return;
1313   }
1314 
1315   // Get Speculative values
1316   SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1317   SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1318 
1319   SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
1320   SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, zero});
1321   REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1322 
1323   SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
1324   SDValue DIV_Lo = zero;
1325 
1326   const unsigned halfBitWidth = HalfVT.getSizeInBits();
1327 
1328   for (unsigned i = 0; i < halfBitWidth; ++i) {
1329     const unsigned bitPos = halfBitWidth - i - 1;
1330     SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1331     // Get value of high bit
1332     SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1333     HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
1334     HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1335 
1336     // Shift
1337     REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1338     // Add LHS high bit
1339     REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1340 
1341     SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1342     SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETUGE);
1343 
1344     DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1345 
1346     // Update REM
1347     SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1348     REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1349   }
1350 
1351   SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1352   DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1353   Results.push_back(DIV);
1354   Results.push_back(REM);
1355 }
1356 
1357 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1358                                            SelectionDAG &DAG) const {
1359   SDLoc DL(Op);
1360   EVT VT = Op.getValueType();
1361 
1362   if (VT == MVT::i64) {
1363     SmallVector<SDValue, 2> Results;
1364     LowerUDIVREM64(Op, DAG, Results);
1365     return DAG.getMergeValues(Results, DL);
1366   }
1367 
1368   if (VT == MVT::i32) {
1369     if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1370       return Res;
1371   }
1372 
1373   SDValue Num = Op.getOperand(0);
1374   SDValue Den = Op.getOperand(1);
1375 
1376   // RCP =  URECIP(Den) = 2^32 / Den + e
1377   // e is rounding error.
1378   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1379 
1380   // RCP_LO = mul(RCP, Den) */
1381   SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1382 
1383   // RCP_HI = mulhu (RCP, Den) */
1384   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1385 
1386   // NEG_RCP_LO = -RCP_LO
1387   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1388                                                      RCP_LO);
1389 
1390   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1391   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1392                                            NEG_RCP_LO, RCP_LO,
1393                                            ISD::SETEQ);
1394   // Calculate the rounding error from the URECIP instruction
1395   // E = mulhu(ABS_RCP_LO, RCP)
1396   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1397 
1398   // RCP_A_E = RCP + E
1399   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1400 
1401   // RCP_S_E = RCP - E
1402   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1403 
1404   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1405   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1406                                      RCP_A_E, RCP_S_E,
1407                                      ISD::SETEQ);
1408   // Quotient = mulhu(Tmp0, Num)
1409   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1410 
1411   // Num_S_Remainder = Quotient * Den
1412   SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1413 
1414   // Remainder = Num - Num_S_Remainder
1415   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1416 
1417   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1418   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1419                                                  DAG.getConstant(-1, DL, VT),
1420                                                  DAG.getConstant(0, DL, VT),
1421                                                  ISD::SETUGE);
1422   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1423   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1424                                                   Num_S_Remainder,
1425                                                   DAG.getConstant(-1, DL, VT),
1426                                                   DAG.getConstant(0, DL, VT),
1427                                                   ISD::SETUGE);
1428   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1429   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1430                                                Remainder_GE_Zero);
1431 
1432   // Calculate Division result:
1433 
1434   // Quotient_A_One = Quotient + 1
1435   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1436                                        DAG.getConstant(1, DL, VT));
1437 
1438   // Quotient_S_One = Quotient - 1
1439   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1440                                        DAG.getConstant(1, DL, VT));
1441 
1442   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1443   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1444                                      Quotient, Quotient_A_One, ISD::SETEQ);
1445 
1446   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1447   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1448                             Quotient_S_One, Div, ISD::SETEQ);
1449 
1450   // Calculate Rem result:
1451 
1452   // Remainder_S_Den = Remainder - Den
1453   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1454 
1455   // Remainder_A_Den = Remainder + Den
1456   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1457 
1458   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1459   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1460                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1461 
1462   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1463   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1464                             Remainder_A_Den, Rem, ISD::SETEQ);
1465   SDValue Ops[2] = {
1466     Div,
1467     Rem
1468   };
1469   return DAG.getMergeValues(Ops, DL);
1470 }
1471 
1472 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1473                                            SelectionDAG &DAG) const {
1474   SDLoc DL(Op);
1475   EVT VT = Op.getValueType();
1476 
1477   SDValue LHS = Op.getOperand(0);
1478   SDValue RHS = Op.getOperand(1);
1479 
1480   SDValue Zero = DAG.getConstant(0, DL, VT);
1481   SDValue NegOne = DAG.getConstant(-1, DL, VT);
1482 
1483   if (VT == MVT::i32) {
1484     if (SDValue Res = LowerDIVREM24(Op, DAG, true))
1485       return Res;
1486   }
1487 
1488   if (VT == MVT::i64 &&
1489       DAG.ComputeNumSignBits(LHS) > 32 &&
1490       DAG.ComputeNumSignBits(RHS) > 32) {
1491     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1492 
1493     //HiLo split
1494     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1495     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1496     SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1497                                  LHS_Lo, RHS_Lo);
1498     SDValue Res[2] = {
1499       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1500       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1501     };
1502     return DAG.getMergeValues(Res, DL);
1503   }
1504 
1505   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1506   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1507   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1508   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1509 
1510   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1511   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1512 
1513   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1514   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1515 
1516   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1517   SDValue Rem = Div.getValue(1);
1518 
1519   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1520   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1521 
1522   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1523   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1524 
1525   SDValue Res[2] = {
1526     Div,
1527     Rem
1528   };
1529   return DAG.getMergeValues(Res, DL);
1530 }
1531 
1532 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
1533 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
1534   SDLoc SL(Op);
1535   EVT VT = Op.getValueType();
1536   SDValue X = Op.getOperand(0);
1537   SDValue Y = Op.getOperand(1);
1538 
1539   // TODO: Should this propagate fast-math-flags?
1540 
1541   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
1542   SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
1543   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
1544 
1545   return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
1546 }
1547 
1548 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1549   SDLoc SL(Op);
1550   SDValue Src = Op.getOperand(0);
1551 
1552   // result = trunc(src)
1553   // if (src > 0.0 && src != result)
1554   //   result += 1.0
1555 
1556   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1557 
1558   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1559   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1560 
1561   EVT SetCCVT =
1562       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1563 
1564   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1565   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1566   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1567 
1568   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1569   // TODO: Should this propagate fast-math-flags?
1570   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1571 }
1572 
1573 static SDValue extractF64Exponent(SDValue Hi, const SDLoc &SL,
1574                                   SelectionDAG &DAG) {
1575   const unsigned FractBits = 52;
1576   const unsigned ExpBits = 11;
1577 
1578   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
1579                                 Hi,
1580                                 DAG.getConstant(FractBits - 32, SL, MVT::i32),
1581                                 DAG.getConstant(ExpBits, SL, MVT::i32));
1582   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1583                             DAG.getConstant(1023, SL, MVT::i32));
1584 
1585   return Exp;
1586 }
1587 
1588 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1589   SDLoc SL(Op);
1590   SDValue Src = Op.getOperand(0);
1591 
1592   assert(Op.getValueType() == MVT::f64);
1593 
1594   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1595   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1596 
1597   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1598 
1599   // Extract the upper half, since this is where we will find the sign and
1600   // exponent.
1601   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1602 
1603   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1604 
1605   const unsigned FractBits = 52;
1606 
1607   // Extract the sign bit.
1608   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
1609   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1610 
1611   // Extend back to to 64-bits.
1612   SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
1613   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1614 
1615   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1616   const SDValue FractMask
1617     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
1618 
1619   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1620   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1621   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1622 
1623   EVT SetCCVT =
1624       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
1625 
1626   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
1627 
1628   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1629   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1630 
1631   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1632   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
1633 
1634   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
1635 }
1636 
1637 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
1638   SDLoc SL(Op);
1639   SDValue Src = Op.getOperand(0);
1640 
1641   assert(Op.getValueType() == MVT::f64);
1642 
1643   APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
1644   SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
1645   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
1646 
1647   // TODO: Should this propagate fast-math-flags?
1648 
1649   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
1650   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
1651 
1652   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
1653 
1654   APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
1655   SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
1656 
1657   EVT SetCCVT =
1658       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1659   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
1660 
1661   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
1662 }
1663 
1664 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
1665   // FNEARBYINT and FRINT are the same, except in their handling of FP
1666   // exceptions. Those aren't really meaningful for us, and OpenCL only has
1667   // rint, so just treat them as equivalent.
1668   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
1669 }
1670 
1671 // XXX - May require not supporting f32 denormals?
1672 SDValue AMDGPUTargetLowering::LowerFROUND32(SDValue Op, SelectionDAG &DAG) const {
1673   SDLoc SL(Op);
1674   SDValue X = Op.getOperand(0);
1675 
1676   SDValue T = DAG.getNode(ISD::FTRUNC, SL, MVT::f32, X);
1677 
1678   // TODO: Should this propagate fast-math-flags?
1679 
1680   SDValue Diff = DAG.getNode(ISD::FSUB, SL, MVT::f32, X, T);
1681 
1682   SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, MVT::f32, Diff);
1683 
1684   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f32);
1685   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1686   const SDValue Half = DAG.getConstantFP(0.5, SL, MVT::f32);
1687 
1688   SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f32, One, X);
1689 
1690   EVT SetCCVT =
1691       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1692 
1693   SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
1694 
1695   SDValue Sel = DAG.getNode(ISD::SELECT, SL, MVT::f32, Cmp, SignOne, Zero);
1696 
1697   return DAG.getNode(ISD::FADD, SL, MVT::f32, T, Sel);
1698 }
1699 
1700 SDValue AMDGPUTargetLowering::LowerFROUND64(SDValue Op, SelectionDAG &DAG) const {
1701   SDLoc SL(Op);
1702   SDValue X = Op.getOperand(0);
1703 
1704   SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
1705 
1706   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1707   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1708   const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
1709   const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
1710   EVT SetCCVT =
1711       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
1712 
1713   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1714 
1715   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
1716 
1717   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1718 
1719   const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
1720                                        MVT::i64);
1721 
1722   SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
1723   SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
1724                           DAG.getConstant(INT64_C(0x0008000000000000), SL,
1725                                           MVT::i64),
1726                           Exp);
1727 
1728   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
1729   SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
1730                               DAG.getConstant(0, SL, MVT::i64), Tmp0,
1731                               ISD::SETNE);
1732 
1733   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
1734                              D, DAG.getConstant(0, SL, MVT::i64));
1735   SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
1736 
1737   K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
1738   K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
1739 
1740   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1741   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1742   SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
1743 
1744   SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
1745                             ExpEqNegOne,
1746                             DAG.getConstantFP(1.0, SL, MVT::f64),
1747                             DAG.getConstantFP(0.0, SL, MVT::f64));
1748 
1749   SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
1750 
1751   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
1752   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
1753 
1754   return K;
1755 }
1756 
1757 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
1758   EVT VT = Op.getValueType();
1759 
1760   if (VT == MVT::f32)
1761     return LowerFROUND32(Op, DAG);
1762 
1763   if (VT == MVT::f64)
1764     return LowerFROUND64(Op, DAG);
1765 
1766   llvm_unreachable("unhandled type");
1767 }
1768 
1769 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
1770   SDLoc SL(Op);
1771   SDValue Src = Op.getOperand(0);
1772 
1773   // result = trunc(src);
1774   // if (src < 0.0 && src != result)
1775   //   result += -1.0.
1776 
1777   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1778 
1779   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1780   const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
1781 
1782   EVT SetCCVT =
1783       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1784 
1785   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
1786   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1787   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1788 
1789   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
1790   // TODO: Should this propagate fast-math-flags?
1791   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1792 }
1793 
1794 SDValue AMDGPUTargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
1795   SDLoc SL(Op);
1796   SDValue Src = Op.getOperand(0);
1797   bool ZeroUndef = Op.getOpcode() == ISD::CTLZ_ZERO_UNDEF;
1798 
1799   if (ZeroUndef && Src.getValueType() == MVT::i32)
1800     return DAG.getNode(AMDGPUISD::FFBH_U32, SL, MVT::i32, Src);
1801 
1802   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1803 
1804   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1805   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1806 
1807   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1808   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1809 
1810   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
1811                                    *DAG.getContext(), MVT::i32);
1812 
1813   SDValue Hi0 = DAG.getSetCC(SL, SetCCVT, Hi, Zero, ISD::SETEQ);
1814 
1815   SDValue CtlzLo = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i32, Lo);
1816   SDValue CtlzHi = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i32, Hi);
1817 
1818   const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
1819   SDValue Add = DAG.getNode(ISD::ADD, SL, MVT::i32, CtlzLo, Bits32);
1820 
1821   // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
1822   SDValue NewCtlz = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0, Add, CtlzHi);
1823 
1824   if (!ZeroUndef) {
1825     // Test if the full 64-bit input is zero.
1826 
1827     // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
1828     // which we probably don't want.
1829     SDValue Lo0 = DAG.getSetCC(SL, SetCCVT, Lo, Zero, ISD::SETEQ);
1830     SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0, Hi0);
1831 
1832     // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
1833     // with the same cycles, otherwise it is slower.
1834     // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
1835     // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
1836 
1837     const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
1838 
1839     // The instruction returns -1 for 0 input, but the defined intrinsic
1840     // behavior is to return the number of bits.
1841     NewCtlz = DAG.getNode(ISD::SELECT, SL, MVT::i32,
1842                           SrcIsZero, Bits32, NewCtlz);
1843   }
1844 
1845   return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewCtlz);
1846 }
1847 
1848 SDValue AMDGPUTargetLowering::LowerINT_TO_FP32(SDValue Op, SelectionDAG &DAG,
1849                                                bool Signed) const {
1850   // Unsigned
1851   // cul2f(ulong u)
1852   //{
1853   //  uint lz = clz(u);
1854   //  uint e = (u != 0) ? 127U + 63U - lz : 0;
1855   //  u = (u << lz) & 0x7fffffffffffffffUL;
1856   //  ulong t = u & 0xffffffffffUL;
1857   //  uint v = (e << 23) | (uint)(u >> 40);
1858   //  uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
1859   //  return as_float(v + r);
1860   //}
1861   // Signed
1862   // cl2f(long l)
1863   //{
1864   //  long s = l >> 63;
1865   //  float r = cul2f((l + s) ^ s);
1866   //  return s ? -r : r;
1867   //}
1868 
1869   SDLoc SL(Op);
1870   SDValue Src = Op.getOperand(0);
1871   SDValue L = Src;
1872 
1873   SDValue S;
1874   if (Signed) {
1875     const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
1876     S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
1877 
1878     SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
1879     L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
1880   }
1881 
1882   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
1883                                    *DAG.getContext(), MVT::f32);
1884 
1885 
1886   SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
1887   SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
1888   SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
1889   LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
1890 
1891   SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
1892   SDValue E = DAG.getSelect(SL, MVT::i32,
1893     DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
1894     DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
1895     ZeroI32);
1896 
1897   SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
1898     DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
1899     DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
1900 
1901   SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
1902                           DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
1903 
1904   SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
1905                              U, DAG.getConstant(40, SL, MVT::i64));
1906 
1907   SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
1908     DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
1909     DAG.getNode(ISD::TRUNCATE, SL, MVT::i32,  UShl));
1910 
1911   SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
1912   SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
1913   SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
1914 
1915   SDValue One = DAG.getConstant(1, SL, MVT::i32);
1916 
1917   SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
1918 
1919   SDValue R = DAG.getSelect(SL, MVT::i32,
1920     RCmp,
1921     One,
1922     DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
1923   R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
1924   R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
1925 
1926   if (!Signed)
1927     return R;
1928 
1929   SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
1930   return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
1931 }
1932 
1933 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
1934                                                bool Signed) const {
1935   SDLoc SL(Op);
1936   SDValue Src = Op.getOperand(0);
1937 
1938   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1939 
1940   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
1941                            DAG.getConstant(0, SL, MVT::i32));
1942   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
1943                            DAG.getConstant(1, SL, MVT::i32));
1944 
1945   SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
1946                               SL, MVT::f64, Hi);
1947 
1948   SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
1949 
1950   SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
1951                               DAG.getConstant(32, SL, MVT::i32));
1952   // TODO: Should this propagate fast-math-flags?
1953   return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
1954 }
1955 
1956 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
1957                                                SelectionDAG &DAG) const {
1958   assert(Op.getOperand(0).getValueType() == MVT::i64 &&
1959          "operation should be legal");
1960 
1961   // TODO: Factor out code common with LowerSINT_TO_FP.
1962 
1963   EVT DestVT = Op.getValueType();
1964   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
1965     SDLoc DL(Op);
1966     SDValue Src = Op.getOperand(0);
1967 
1968     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
1969     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
1970     SDValue FPRound =
1971         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
1972 
1973     return FPRound;
1974   }
1975 
1976   if (DestVT == MVT::f32)
1977     return LowerINT_TO_FP32(Op, DAG, false);
1978 
1979   assert(DestVT == MVT::f64);
1980   return LowerINT_TO_FP64(Op, DAG, false);
1981 }
1982 
1983 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
1984                                               SelectionDAG &DAG) const {
1985   assert(Op.getOperand(0).getValueType() == MVT::i64 &&
1986          "operation should be legal");
1987 
1988   // TODO: Factor out code common with LowerUINT_TO_FP.
1989 
1990   EVT DestVT = Op.getValueType();
1991   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
1992     SDLoc DL(Op);
1993     SDValue Src = Op.getOperand(0);
1994 
1995     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
1996     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
1997     SDValue FPRound =
1998         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
1999 
2000     return FPRound;
2001   }
2002 
2003   if (DestVT == MVT::f32)
2004     return LowerINT_TO_FP32(Op, DAG, true);
2005 
2006   assert(DestVT == MVT::f64);
2007   return LowerINT_TO_FP64(Op, DAG, true);
2008 }
2009 
2010 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2011                                                bool Signed) const {
2012   SDLoc SL(Op);
2013 
2014   SDValue Src = Op.getOperand(0);
2015 
2016   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2017 
2018   SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2019                                  MVT::f64);
2020   SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2021                                  MVT::f64);
2022   // TODO: Should this propagate fast-math-flags?
2023   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2024 
2025   SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2026 
2027 
2028   SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2029 
2030   SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2031                            MVT::i32, FloorMul);
2032   SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2033 
2034   SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2035 
2036   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2037 }
2038 
2039 SDValue AMDGPUTargetLowering::LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) const {
2040 
2041   if (getTargetMachine().Options.UnsafeFPMath) {
2042     // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2043     return SDValue();
2044   }
2045 
2046   SDLoc DL(Op);
2047   SDValue N0 = Op.getOperand(0);
2048   assert (N0.getSimpleValueType() == MVT::f64);
2049 
2050   // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2051   const unsigned ExpMask = 0x7ff;
2052   const unsigned ExpBiasf64 = 1023;
2053   const unsigned ExpBiasf16 = 15;
2054   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2055   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2056   SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2057   SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2058                            DAG.getConstant(32, DL, MVT::i64));
2059   UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2060   U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2061   SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2062                           DAG.getConstant(20, DL, MVT::i64));
2063   E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2064                   DAG.getConstant(ExpMask, DL, MVT::i32));
2065   // Subtract the fp64 exponent bias (1023) to get the real exponent and
2066   // add the f16 bias (15) to get the biased exponent for the f16 format.
2067   E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2068                   DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2069 
2070   SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2071                           DAG.getConstant(8, DL, MVT::i32));
2072   M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2073                   DAG.getConstant(0xffe, DL, MVT::i32));
2074 
2075   SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2076                                   DAG.getConstant(0x1ff, DL, MVT::i32));
2077   MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2078 
2079   SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2080   M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2081 
2082   // (M != 0 ? 0x0200 : 0) | 0x7c00;
2083   SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2084       DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2085                       Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2086 
2087   // N = M | (E << 12);
2088   SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2089       DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2090                   DAG.getConstant(12, DL, MVT::i32)));
2091 
2092   // B = clamp(1-E, 0, 13);
2093   SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2094                                   One, E);
2095   SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2096   B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2097                   DAG.getConstant(13, DL, MVT::i32));
2098 
2099   SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2100                                    DAG.getConstant(0x1000, DL, MVT::i32));
2101 
2102   SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2103   SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2104   SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2105   D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2106 
2107   SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2108   SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2109                               DAG.getConstant(0x7, DL, MVT::i32));
2110   V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2111                   DAG.getConstant(2, DL, MVT::i32));
2112   SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2113                                One, Zero, ISD::SETEQ);
2114   SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2115                                One, Zero, ISD::SETGT);
2116   V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2117   V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2118 
2119   V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2120                       DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2121   V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2122                       I, V, ISD::SETEQ);
2123 
2124   // Extract the sign bit.
2125   SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2126                             DAG.getConstant(16, DL, MVT::i32));
2127   Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2128                      DAG.getConstant(0x8000, DL, MVT::i32));
2129 
2130   V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2131   return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2132 }
2133 
2134 SDValue AMDGPUTargetLowering::LowerFP_TO_SINT(SDValue Op,
2135                                               SelectionDAG &DAG) const {
2136   SDValue Src = Op.getOperand(0);
2137 
2138   // TODO: Factor out code common with LowerFP_TO_UINT.
2139 
2140   EVT SrcVT = Src.getValueType();
2141   if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2142     SDLoc DL(Op);
2143 
2144     SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2145     SDValue FpToInt32 =
2146         DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2147 
2148     return FpToInt32;
2149   }
2150 
2151   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2152     return LowerFP64_TO_INT(Op, DAG, true);
2153 
2154   return SDValue();
2155 }
2156 
2157 SDValue AMDGPUTargetLowering::LowerFP_TO_UINT(SDValue Op,
2158                                               SelectionDAG &DAG) const {
2159   SDValue Src = Op.getOperand(0);
2160 
2161   // TODO: Factor out code common with LowerFP_TO_SINT.
2162 
2163   EVT SrcVT = Src.getValueType();
2164   if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2165     SDLoc DL(Op);
2166 
2167     SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2168     SDValue FpToInt32 =
2169         DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2170 
2171     return FpToInt32;
2172   }
2173 
2174   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2175     return LowerFP64_TO_INT(Op, DAG, false);
2176 
2177   return SDValue();
2178 }
2179 
2180 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2181                                                      SelectionDAG &DAG) const {
2182   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2183   MVT VT = Op.getSimpleValueType();
2184   MVT ScalarVT = VT.getScalarType();
2185 
2186   assert(VT.isVector());
2187 
2188   SDValue Src = Op.getOperand(0);
2189   SDLoc DL(Op);
2190 
2191   // TODO: Don't scalarize on Evergreen?
2192   unsigned NElts = VT.getVectorNumElements();
2193   SmallVector<SDValue, 8> Args;
2194   DAG.ExtractVectorElements(Src, Args, 0, NElts);
2195 
2196   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2197   for (unsigned I = 0; I < NElts; ++I)
2198     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2199 
2200   return DAG.getBuildVector(VT, DL, Args);
2201 }
2202 
2203 //===----------------------------------------------------------------------===//
2204 // Custom DAG optimizations
2205 //===----------------------------------------------------------------------===//
2206 
2207 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2208   APInt KnownZero, KnownOne;
2209   EVT VT = Op.getValueType();
2210   DAG.computeKnownBits(Op, KnownZero, KnownOne);
2211 
2212   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
2213 }
2214 
2215 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2216   EVT VT = Op.getValueType();
2217 
2218   // In order for this to be a signed 24-bit value, bit 23, must
2219   // be a sign bit.
2220   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2221                                      // as unsigned 24-bit values.
2222          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
2223 }
2224 
2225 static bool simplifyI24(SDNode *Node24, unsigned OpIdx,
2226                         TargetLowering::DAGCombinerInfo &DCI) {
2227 
2228   SelectionDAG &DAG = DCI.DAG;
2229   SDValue Op = Node24->getOperand(OpIdx);
2230   EVT VT = Op.getValueType();
2231 
2232   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
2233   APInt KnownZero, KnownOne;
2234   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
2235   if (TLO.SimplifyDemandedBits(Node24, OpIdx, Demanded, DCI))
2236     return true;
2237 
2238   return false;
2239 }
2240 
2241 template <typename IntTy>
2242 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0, uint32_t Offset,
2243                                uint32_t Width, const SDLoc &DL) {
2244   if (Width + Offset < 32) {
2245     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2246     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2247     return DAG.getConstant(Result, DL, MVT::i32);
2248   }
2249 
2250   return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2251 }
2252 
2253 static bool hasVolatileUser(SDNode *Val) {
2254   for (SDNode *U : Val->uses()) {
2255     if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2256       if (M->isVolatile())
2257         return true;
2258     }
2259   }
2260 
2261   return false;
2262 }
2263 
2264 bool AMDGPUTargetLowering::shouldCombineMemoryType(EVT VT) const {
2265   // i32 vectors are the canonical memory type.
2266   if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2267     return false;
2268 
2269   if (!VT.isByteSized())
2270     return false;
2271 
2272   unsigned Size = VT.getStoreSize();
2273 
2274   if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2275     return false;
2276 
2277   if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2278     return false;
2279 
2280   return true;
2281 }
2282 
2283 // Replace load of an illegal type with a store of a bitcast to a friendlier
2284 // type.
2285 SDValue AMDGPUTargetLowering::performLoadCombine(SDNode *N,
2286                                                  DAGCombinerInfo &DCI) const {
2287   if (!DCI.isBeforeLegalize())
2288     return SDValue();
2289 
2290   LoadSDNode *LN = cast<LoadSDNode>(N);
2291   if (LN->isVolatile() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2292     return SDValue();
2293 
2294   SDLoc SL(N);
2295   SelectionDAG &DAG = DCI.DAG;
2296   EVT VT = LN->getMemoryVT();
2297 
2298   unsigned Size = VT.getStoreSize();
2299   unsigned Align = LN->getAlignment();
2300   if (Align < Size && isTypeLegal(VT)) {
2301     bool IsFast;
2302     unsigned AS = LN->getAddressSpace();
2303 
2304     // Expand unaligned loads earlier than legalization. Due to visitation order
2305     // problems during legalization, the emitted instructions to pack and unpack
2306     // the bytes again are not eliminated in the case of an unaligned copy.
2307     if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2308       if (VT.isVector())
2309         return scalarizeVectorLoad(LN, DAG);
2310 
2311       SDValue Ops[2];
2312       std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2313       return DAG.getMergeValues(Ops, SDLoc(N));
2314     }
2315 
2316     if (!IsFast)
2317       return SDValue();
2318   }
2319 
2320   if (!shouldCombineMemoryType(VT))
2321     return SDValue();
2322 
2323   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2324 
2325   SDValue NewLoad
2326     = DAG.getLoad(NewVT, SL, LN->getChain(),
2327                   LN->getBasePtr(), LN->getMemOperand());
2328 
2329   SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2330   DCI.CombineTo(N, BC, NewLoad.getValue(1));
2331   return SDValue(N, 0);
2332 }
2333 
2334 // Replace store of an illegal type with a store of a bitcast to a friendlier
2335 // type.
2336 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2337                                                   DAGCombinerInfo &DCI) const {
2338   if (!DCI.isBeforeLegalize())
2339     return SDValue();
2340 
2341   StoreSDNode *SN = cast<StoreSDNode>(N);
2342   if (SN->isVolatile() || !ISD::isNormalStore(SN))
2343     return SDValue();
2344 
2345   EVT VT = SN->getMemoryVT();
2346   unsigned Size = VT.getStoreSize();
2347 
2348   SDLoc SL(N);
2349   SelectionDAG &DAG = DCI.DAG;
2350   unsigned Align = SN->getAlignment();
2351   if (Align < Size && isTypeLegal(VT)) {
2352     bool IsFast;
2353     unsigned AS = SN->getAddressSpace();
2354 
2355     // Expand unaligned stores earlier than legalization. Due to visitation
2356     // order problems during legalization, the emitted instructions to pack and
2357     // unpack the bytes again are not eliminated in the case of an unaligned
2358     // copy.
2359     if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2360       if (VT.isVector())
2361         return scalarizeVectorStore(SN, DAG);
2362 
2363       return expandUnalignedStore(SN, DAG);
2364     }
2365 
2366     if (!IsFast)
2367       return SDValue();
2368   }
2369 
2370   if (!shouldCombineMemoryType(VT))
2371     return SDValue();
2372 
2373   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2374   SDValue Val = SN->getValue();
2375 
2376   //DCI.AddToWorklist(Val.getNode());
2377 
2378   bool OtherUses = !Val.hasOneUse();
2379   SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2380   if (OtherUses) {
2381     SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
2382     DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
2383   }
2384 
2385   return DAG.getStore(SN->getChain(), SL, CastVal,
2386                       SN->getBasePtr(), SN->getMemOperand());
2387 }
2388 
2389 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
2390 /// binary operation \p Opc to it with the corresponding constant operands.
2391 SDValue AMDGPUTargetLowering::splitBinaryBitConstantOpImpl(
2392   DAGCombinerInfo &DCI, const SDLoc &SL,
2393   unsigned Opc, SDValue LHS,
2394   uint32_t ValLo, uint32_t ValHi) const {
2395   SelectionDAG &DAG = DCI.DAG;
2396   SDValue Lo, Hi;
2397   std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
2398 
2399   SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
2400   SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
2401 
2402   SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
2403   SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
2404 
2405   // Re-visit the ands. It's possible we eliminated one of them and it could
2406   // simplify the vector.
2407   DCI.AddToWorklist(Lo.getNode());
2408   DCI.AddToWorklist(Hi.getNode());
2409 
2410   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
2411   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2412 }
2413 
2414 SDValue AMDGPUTargetLowering::performShlCombine(SDNode *N,
2415                                                 DAGCombinerInfo &DCI) const {
2416   if (N->getValueType(0) != MVT::i64)
2417     return SDValue();
2418 
2419   // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
2420 
2421   // On some subtargets, 64-bit shift is a quarter rate instruction. In the
2422   // common case, splitting this into a move and a 32-bit shift is faster and
2423   // the same code size.
2424   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2425   if (!RHS)
2426     return SDValue();
2427 
2428   unsigned RHSVal = RHS->getZExtValue();
2429   if (RHSVal < 32)
2430     return SDValue();
2431 
2432   SDValue LHS = N->getOperand(0);
2433 
2434   SDLoc SL(N);
2435   SelectionDAG &DAG = DCI.DAG;
2436 
2437   SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
2438 
2439   SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
2440   SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
2441 
2442   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2443 
2444   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
2445   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2446 }
2447 
2448 SDValue AMDGPUTargetLowering::performSraCombine(SDNode *N,
2449                                                 DAGCombinerInfo &DCI) const {
2450   if (N->getValueType(0) != MVT::i64)
2451     return SDValue();
2452 
2453   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2454   if (!RHS)
2455     return SDValue();
2456 
2457   SelectionDAG &DAG = DCI.DAG;
2458   SDLoc SL(N);
2459   unsigned RHSVal = RHS->getZExtValue();
2460 
2461   // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
2462   if (RHSVal == 32) {
2463     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2464     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2465                                    DAG.getConstant(31, SL, MVT::i32));
2466 
2467     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
2468     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2469   }
2470 
2471   // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
2472   if (RHSVal == 63) {
2473     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2474     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2475                                    DAG.getConstant(31, SL, MVT::i32));
2476     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
2477     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2478   }
2479 
2480   return SDValue();
2481 }
2482 
2483 SDValue AMDGPUTargetLowering::performSrlCombine(SDNode *N,
2484                                                 DAGCombinerInfo &DCI) const {
2485   if (N->getValueType(0) != MVT::i64)
2486     return SDValue();
2487 
2488   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2489   if (!RHS)
2490     return SDValue();
2491 
2492   unsigned ShiftAmt = RHS->getZExtValue();
2493   if (ShiftAmt < 32)
2494     return SDValue();
2495 
2496   // srl i64:x, C for C >= 32
2497   // =>
2498   //   build_pair (srl hi_32(x), C - 32), 0
2499 
2500   SelectionDAG &DAG = DCI.DAG;
2501   SDLoc SL(N);
2502 
2503   SDValue One = DAG.getConstant(1, SL, MVT::i32);
2504   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2505 
2506   SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, N->getOperand(0));
2507   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32,
2508                            VecOp, One);
2509 
2510   SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
2511   SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
2512 
2513   SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
2514 
2515   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
2516 }
2517 
2518 // We need to specifically handle i64 mul here to avoid unnecessary conversion
2519 // instructions. If we only match on the legalized i64 mul expansion,
2520 // SimplifyDemandedBits will be unable to remove them because there will be
2521 // multiple uses due to the separate mul + mulh[su].
2522 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
2523                         SDValue N0, SDValue N1, unsigned Size, bool Signed) {
2524   if (Size <= 32) {
2525     unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2526     return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
2527   }
2528 
2529   // Because we want to eliminate extension instructions before the
2530   // operation, we need to create a single user here (i.e. not the separate
2531   // mul_lo + mul_hi) so that SimplifyDemandedBits will deal with it.
2532 
2533   unsigned MulOpc = Signed ? AMDGPUISD::MUL_LOHI_I24 : AMDGPUISD::MUL_LOHI_U24;
2534 
2535   SDValue Mul = DAG.getNode(MulOpc, SL,
2536                             DAG.getVTList(MVT::i32, MVT::i32), N0, N1);
2537 
2538   return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64,
2539                      Mul.getValue(0), Mul.getValue(1));
2540 }
2541 
2542 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
2543                                                 DAGCombinerInfo &DCI) const {
2544   EVT VT = N->getValueType(0);
2545 
2546   unsigned Size = VT.getSizeInBits();
2547   if (VT.isVector() || Size > 64)
2548     return SDValue();
2549 
2550   // There are i16 integer mul/mad.
2551   if (Subtarget->has16BitInsts() && VT.getScalarType().bitsLE(MVT::i16))
2552     return SDValue();
2553 
2554   SelectionDAG &DAG = DCI.DAG;
2555   SDLoc DL(N);
2556 
2557   SDValue N0 = N->getOperand(0);
2558   SDValue N1 = N->getOperand(1);
2559   SDValue Mul;
2560 
2561   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
2562     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
2563     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
2564     Mul = getMul24(DAG, DL, N0, N1, Size, false);
2565   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
2566     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
2567     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
2568     Mul = getMul24(DAG, DL, N0, N1, Size, true);
2569   } else {
2570     return SDValue();
2571   }
2572 
2573   // We need to use sext even for MUL_U24, because MUL_U24 is used
2574   // for signed multiply of 8 and 16-bit types.
2575   return DAG.getSExtOrTrunc(Mul, DL, VT);
2576 }
2577 
2578 SDValue AMDGPUTargetLowering::performMulhsCombine(SDNode *N,
2579                                                   DAGCombinerInfo &DCI) const {
2580   EVT VT = N->getValueType(0);
2581 
2582   if (!Subtarget->hasMulI24() || VT.isVector())
2583     return SDValue();
2584 
2585   SelectionDAG &DAG = DCI.DAG;
2586   SDLoc DL(N);
2587 
2588   SDValue N0 = N->getOperand(0);
2589   SDValue N1 = N->getOperand(1);
2590 
2591   if (!isI24(N0, DAG) || !isI24(N1, DAG))
2592     return SDValue();
2593 
2594   N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
2595   N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
2596 
2597   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
2598   DCI.AddToWorklist(Mulhi.getNode());
2599   return DAG.getSExtOrTrunc(Mulhi, DL, VT);
2600 }
2601 
2602 SDValue AMDGPUTargetLowering::performMulhuCombine(SDNode *N,
2603                                                   DAGCombinerInfo &DCI) const {
2604   EVT VT = N->getValueType(0);
2605 
2606   if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
2607     return SDValue();
2608 
2609   SelectionDAG &DAG = DCI.DAG;
2610   SDLoc DL(N);
2611 
2612   SDValue N0 = N->getOperand(0);
2613   SDValue N1 = N->getOperand(1);
2614 
2615   if (!isU24(N0, DAG) || !isU24(N1, DAG))
2616     return SDValue();
2617 
2618   N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
2619   N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
2620 
2621   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
2622   DCI.AddToWorklist(Mulhi.getNode());
2623   return DAG.getZExtOrTrunc(Mulhi, DL, VT);
2624 }
2625 
2626 SDValue AMDGPUTargetLowering::performMulLoHi24Combine(
2627   SDNode *N, DAGCombinerInfo &DCI) const {
2628   SelectionDAG &DAG = DCI.DAG;
2629 
2630   // Simplify demanded bits before splitting into multiple users.
2631   if (simplifyI24(N, 0, DCI) || simplifyI24(N, 1, DCI))
2632     return SDValue();
2633 
2634   SDValue N0 = N->getOperand(0);
2635   SDValue N1 = N->getOperand(1);
2636 
2637   bool Signed = (N->getOpcode() == AMDGPUISD::MUL_LOHI_I24);
2638 
2639   unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2640   unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
2641 
2642   SDLoc SL(N);
2643 
2644   SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
2645   SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
2646   return DAG.getMergeValues({ MulLo, MulHi }, SL);
2647 }
2648 
2649 static bool isNegativeOne(SDValue Val) {
2650   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
2651     return C->isAllOnesValue();
2652   return false;
2653 }
2654 
2655 static bool isCtlzOpc(unsigned Opc) {
2656   return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2657 }
2658 
2659 SDValue AMDGPUTargetLowering::getFFBH_U32(SelectionDAG &DAG,
2660                                           SDValue Op,
2661                                           const SDLoc &DL) const {
2662   EVT VT = Op.getValueType();
2663   EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
2664   if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
2665                               LegalVT != MVT::i16))
2666     return SDValue();
2667 
2668   if (VT != MVT::i32)
2669     Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
2670 
2671   SDValue FFBH = DAG.getNode(AMDGPUISD::FFBH_U32, DL, MVT::i32, Op);
2672   if (VT != MVT::i32)
2673     FFBH = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBH);
2674 
2675   return FFBH;
2676 }
2677 
2678 // The native instructions return -1 on 0 input. Optimize out a select that
2679 // produces -1 on 0.
2680 //
2681 // TODO: If zero is not undef, we could also do this if the output is compared
2682 // against the bitwidth.
2683 //
2684 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
2685 SDValue AMDGPUTargetLowering::performCtlzCombine(const SDLoc &SL, SDValue Cond,
2686                                                  SDValue LHS, SDValue RHS,
2687                                                  DAGCombinerInfo &DCI) const {
2688   ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2689   if (!CmpRhs || !CmpRhs->isNullValue())
2690     return SDValue();
2691 
2692   SelectionDAG &DAG = DCI.DAG;
2693   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
2694   SDValue CmpLHS = Cond.getOperand(0);
2695 
2696   // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
2697   if (CCOpcode == ISD::SETEQ &&
2698       isCtlzOpc(RHS.getOpcode()) &&
2699       RHS.getOperand(0) == CmpLHS &&
2700       isNegativeOne(LHS)) {
2701     return getFFBH_U32(DAG, CmpLHS, SL);
2702   }
2703 
2704   // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
2705   if (CCOpcode == ISD::SETNE &&
2706       isCtlzOpc(LHS.getOpcode()) &&
2707       LHS.getOperand(0) == CmpLHS &&
2708       isNegativeOne(RHS)) {
2709     return getFFBH_U32(DAG, CmpLHS, SL);
2710   }
2711 
2712   return SDValue();
2713 }
2714 
2715 static SDValue distributeOpThroughSelect(TargetLowering::DAGCombinerInfo &DCI,
2716                                          unsigned Op,
2717                                          const SDLoc &SL,
2718                                          SDValue Cond,
2719                                          SDValue N1,
2720                                          SDValue N2) {
2721   SelectionDAG &DAG = DCI.DAG;
2722   EVT VT = N1.getValueType();
2723 
2724   SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
2725                                   N1.getOperand(0), N2.getOperand(0));
2726   DCI.AddToWorklist(NewSelect.getNode());
2727   return DAG.getNode(Op, SL, VT, NewSelect);
2728 }
2729 
2730 // Pull a free FP operation out of a select so it may fold into uses.
2731 //
2732 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
2733 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
2734 //
2735 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
2736 // select c, (fabs x), +k -> fabs (select c, x, k)
2737 static SDValue foldFreeOpFromSelect(TargetLowering::DAGCombinerInfo &DCI,
2738                                     SDValue N) {
2739   SelectionDAG &DAG = DCI.DAG;
2740   SDValue Cond = N.getOperand(0);
2741   SDValue LHS = N.getOperand(1);
2742   SDValue RHS = N.getOperand(2);
2743 
2744   EVT VT = N.getValueType();
2745   if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
2746       (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
2747     return distributeOpThroughSelect(DCI, LHS.getOpcode(),
2748                                      SDLoc(N), Cond, LHS, RHS);
2749   }
2750 
2751   bool Inv = false;
2752   if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
2753     std::swap(LHS, RHS);
2754     Inv = true;
2755   }
2756 
2757   // TODO: Support vector constants.
2758   ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
2759   if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
2760     SDLoc SL(N);
2761     // If one side is an fneg/fabs and the other is a constant, we can push the
2762     // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
2763     SDValue NewLHS = LHS.getOperand(0);
2764     SDValue NewRHS = RHS;
2765 
2766     // Careful: if the neg can be folded up, don't try to pull it back down.
2767     bool ShouldFoldNeg = true;
2768 
2769     if (NewLHS.hasOneUse()) {
2770       unsigned Opc = NewLHS.getOpcode();
2771       if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
2772         ShouldFoldNeg = false;
2773       if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
2774         ShouldFoldNeg = false;
2775     }
2776 
2777     if (ShouldFoldNeg) {
2778       if (LHS.getOpcode() == ISD::FNEG)
2779         NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2780       else if (CRHS->isNegative())
2781         return SDValue();
2782 
2783       if (Inv)
2784         std::swap(NewLHS, NewRHS);
2785 
2786       SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
2787                                       Cond, NewLHS, NewRHS);
2788       DCI.AddToWorklist(NewSelect.getNode());
2789       return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
2790     }
2791   }
2792 
2793   return SDValue();
2794 }
2795 
2796 
2797 SDValue AMDGPUTargetLowering::performSelectCombine(SDNode *N,
2798                                                    DAGCombinerInfo &DCI) const {
2799   if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
2800     return Folded;
2801 
2802   SDValue Cond = N->getOperand(0);
2803   if (Cond.getOpcode() != ISD::SETCC)
2804     return SDValue();
2805 
2806   EVT VT = N->getValueType(0);
2807   SDValue LHS = Cond.getOperand(0);
2808   SDValue RHS = Cond.getOperand(1);
2809   SDValue CC = Cond.getOperand(2);
2810 
2811   SDValue True = N->getOperand(1);
2812   SDValue False = N->getOperand(2);
2813 
2814   if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
2815     SelectionDAG &DAG = DCI.DAG;
2816     if ((DAG.isConstantValueOfAnyType(True) ||
2817          DAG.isConstantValueOfAnyType(True)) &&
2818         (!DAG.isConstantValueOfAnyType(False) &&
2819          !DAG.isConstantValueOfAnyType(False))) {
2820       // Swap cmp + select pair to move constant to false input.
2821       // This will allow using VOPC cndmasks more often.
2822       // select (setcc x, y), k, x -> select (setcc y, x) x, x
2823 
2824       SDLoc SL(N);
2825       ISD::CondCode NewCC = getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2826                                             LHS.getValueType().isInteger());
2827 
2828       SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
2829       return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
2830     }
2831 
2832     if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
2833       SDValue MinMax
2834         = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
2835       // Revisit this node so we can catch min3/max3/med3 patterns.
2836       //DCI.AddToWorklist(MinMax.getNode());
2837       return MinMax;
2838     }
2839   }
2840 
2841   // There's no reason to not do this if the condition has other uses.
2842   return performCtlzCombine(SDLoc(N), Cond, True, False, DCI);
2843 }
2844 
2845 SDValue AMDGPUTargetLowering::performFNegCombine(SDNode *N,
2846                                                  DAGCombinerInfo &DCI) const {
2847   SelectionDAG &DAG = DCI.DAG;
2848   SDValue N0 = N->getOperand(0);
2849   EVT VT = N->getValueType(0);
2850 
2851   unsigned Opc = N0.getOpcode();
2852 
2853   // If the input has multiple uses and we can either fold the negate down, or
2854   // the other uses cannot, give up. This both prevents unprofitable
2855   // transformations and infinite loops: we won't repeatedly try to fold around
2856   // a negate that has no 'good' form.
2857   //
2858   // TODO: Check users can fold
2859   if (fnegFoldsIntoOp(Opc) && !N0.hasOneUse())
2860     return SDValue();
2861 
2862   SDLoc SL(N);
2863   switch (Opc) {
2864   case ISD::FADD: {
2865     if (!mayIgnoreSignedZero(N0))
2866       return SDValue();
2867 
2868     // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
2869     SDValue LHS = N0.getOperand(0);
2870     SDValue RHS = N0.getOperand(1);
2871 
2872     if (LHS.getOpcode() != ISD::FNEG)
2873       LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
2874     else
2875       LHS = LHS.getOperand(0);
2876 
2877     if (RHS.getOpcode() != ISD::FNEG)
2878       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2879     else
2880       RHS = RHS.getOperand(0);
2881 
2882     SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
2883     if (!N0.hasOneUse())
2884       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
2885     return Res;
2886   }
2887   case ISD::FMUL:
2888   case AMDGPUISD::FMUL_LEGACY: {
2889     // (fneg (fmul x, y)) -> (fmul x, (fneg y))
2890     // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
2891     SDValue LHS = N0.getOperand(0);
2892     SDValue RHS = N0.getOperand(1);
2893 
2894     if (LHS.getOpcode() == ISD::FNEG)
2895       LHS = LHS.getOperand(0);
2896     else if (RHS.getOpcode() == ISD::FNEG)
2897       RHS = RHS.getOperand(0);
2898     else
2899       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2900 
2901     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
2902     if (!N0.hasOneUse())
2903       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
2904     return Res;
2905   }
2906   case ISD::FMA:
2907   case ISD::FMAD: {
2908     if (!mayIgnoreSignedZero(N0))
2909       return SDValue();
2910 
2911     // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
2912     SDValue LHS = N0.getOperand(0);
2913     SDValue MHS = N0.getOperand(1);
2914     SDValue RHS = N0.getOperand(2);
2915 
2916     if (LHS.getOpcode() == ISD::FNEG)
2917       LHS = LHS.getOperand(0);
2918     else if (MHS.getOpcode() == ISD::FNEG)
2919       MHS = MHS.getOperand(0);
2920     else
2921       MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
2922 
2923     if (RHS.getOpcode() != ISD::FNEG)
2924       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2925     else
2926       RHS = RHS.getOperand(0);
2927 
2928     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
2929     if (!N0.hasOneUse())
2930       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
2931     return Res;
2932   }
2933   case ISD::FP_EXTEND:
2934   case ISD::FTRUNC:
2935   case ISD::FRINT:
2936   case ISD::FNEARBYINT: // XXX - Should fround be handled?
2937   case ISD::FSIN:
2938   case AMDGPUISD::RCP:
2939   case AMDGPUISD::RCP_LEGACY:
2940   case AMDGPUISD::SIN_HW: {
2941     SDValue CvtSrc = N0.getOperand(0);
2942     if (CvtSrc.getOpcode() == ISD::FNEG) {
2943       // (fneg (fp_extend (fneg x))) -> (fp_extend x)
2944       // (fneg (rcp (fneg x))) -> (rcp x)
2945       return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
2946     }
2947 
2948     if (!N0.hasOneUse())
2949       return SDValue();
2950 
2951     // (fneg (fp_extend x)) -> (fp_extend (fneg x))
2952     // (fneg (rcp x)) -> (rcp (fneg x))
2953     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
2954     return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
2955   }
2956   case ISD::FP_ROUND: {
2957     SDValue CvtSrc = N0.getOperand(0);
2958 
2959     if (CvtSrc.getOpcode() == ISD::FNEG) {
2960       // (fneg (fp_round (fneg x))) -> (fp_round x)
2961       return DAG.getNode(ISD::FP_ROUND, SL, VT,
2962                          CvtSrc.getOperand(0), N0.getOperand(1));
2963     }
2964 
2965     if (!N0.hasOneUse())
2966       return SDValue();
2967 
2968     // (fneg (fp_round x)) -> (fp_round (fneg x))
2969     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
2970     return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
2971   }
2972   case ISD::FP16_TO_FP: {
2973     // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
2974     // f16, but legalization of f16 fneg ends up pulling it out of the source.
2975     // Put the fneg back as a legal source operation that can be matched later.
2976     SDLoc SL(N);
2977 
2978     SDValue Src = N0.getOperand(0);
2979     EVT SrcVT = Src.getValueType();
2980 
2981     // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
2982     SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
2983                                   DAG.getConstant(0x8000, SL, SrcVT));
2984     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
2985   }
2986   default:
2987     return SDValue();
2988   }
2989 }
2990 
2991 SDValue AMDGPUTargetLowering::performFAbsCombine(SDNode *N,
2992                                                  DAGCombinerInfo &DCI) const {
2993   SelectionDAG &DAG = DCI.DAG;
2994   SDValue N0 = N->getOperand(0);
2995 
2996   if (!N0.hasOneUse())
2997     return SDValue();
2998 
2999   switch (N0.getOpcode()) {
3000   case ISD::FP16_TO_FP: {
3001     assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3002     SDLoc SL(N);
3003     SDValue Src = N0.getOperand(0);
3004     EVT SrcVT = Src.getValueType();
3005 
3006     // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3007     SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3008                                   DAG.getConstant(0x7fff, SL, SrcVT));
3009     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3010   }
3011   default:
3012     return SDValue();
3013   }
3014 }
3015 
3016 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
3017                                                 DAGCombinerInfo &DCI) const {
3018   SelectionDAG &DAG = DCI.DAG;
3019   SDLoc DL(N);
3020 
3021   switch(N->getOpcode()) {
3022   default:
3023     break;
3024   case ISD::BITCAST: {
3025     EVT DestVT = N->getValueType(0);
3026 
3027     // Push casts through vector builds. This helps avoid emitting a large
3028     // number of copies when materializing floating point vector constants.
3029     //
3030     // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3031     //   vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3032     if (DestVT.isVector()) {
3033       SDValue Src = N->getOperand(0);
3034       if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3035         EVT SrcVT = Src.getValueType();
3036         unsigned NElts = DestVT.getVectorNumElements();
3037 
3038         if (SrcVT.getVectorNumElements() == NElts) {
3039           EVT DestEltVT = DestVT.getVectorElementType();
3040 
3041           SmallVector<SDValue, 8> CastedElts;
3042           SDLoc SL(N);
3043           for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3044             SDValue Elt = Src.getOperand(I);
3045             CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3046           }
3047 
3048           return DAG.getBuildVector(DestVT, SL, CastedElts);
3049         }
3050       }
3051     }
3052 
3053     if (DestVT.getSizeInBits() != 64 && !DestVT.isVector())
3054       break;
3055 
3056     // Fold bitcasts of constants.
3057     //
3058     // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3059     // TODO: Generalize and move to DAGCombiner
3060     SDValue Src = N->getOperand(0);
3061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3062       assert(Src.getValueType() == MVT::i64);
3063       SDLoc SL(N);
3064       uint64_t CVal = C->getZExtValue();
3065       return DAG.getNode(ISD::BUILD_VECTOR, SL, DestVT,
3066                          DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3067                          DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3068     }
3069 
3070     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3071       const APInt &Val = C->getValueAPF().bitcastToAPInt();
3072       SDLoc SL(N);
3073       uint64_t CVal = Val.getZExtValue();
3074       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3075                                 DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3076                                 DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3077 
3078       return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3079     }
3080 
3081     break;
3082   }
3083   case ISD::SHL: {
3084     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3085       break;
3086 
3087     return performShlCombine(N, DCI);
3088   }
3089   case ISD::SRL: {
3090     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3091       break;
3092 
3093     return performSrlCombine(N, DCI);
3094   }
3095   case ISD::SRA: {
3096     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3097       break;
3098 
3099     return performSraCombine(N, DCI);
3100   }
3101   case ISD::MUL:
3102     return performMulCombine(N, DCI);
3103   case ISD::MULHS:
3104     return performMulhsCombine(N, DCI);
3105   case ISD::MULHU:
3106     return performMulhuCombine(N, DCI);
3107   case AMDGPUISD::MUL_I24:
3108   case AMDGPUISD::MUL_U24:
3109   case AMDGPUISD::MULHI_I24:
3110   case AMDGPUISD::MULHI_U24: {
3111     // If the first call to simplify is successfull, then N may end up being
3112     // deleted, so we shouldn't call simplifyI24 again.
3113     simplifyI24(N, 0, DCI) || simplifyI24(N, 1, DCI);
3114     return SDValue();
3115   }
3116   case AMDGPUISD::MUL_LOHI_I24:
3117   case AMDGPUISD::MUL_LOHI_U24:
3118     return performMulLoHi24Combine(N, DCI);
3119   case ISD::SELECT:
3120     return performSelectCombine(N, DCI);
3121   case ISD::FNEG:
3122     return performFNegCombine(N, DCI);
3123   case ISD::FABS:
3124     return performFAbsCombine(N, DCI);
3125   case AMDGPUISD::BFE_I32:
3126   case AMDGPUISD::BFE_U32: {
3127     assert(!N->getValueType(0).isVector() &&
3128            "Vector handling of BFE not implemented");
3129     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
3130     if (!Width)
3131       break;
3132 
3133     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
3134     if (WidthVal == 0)
3135       return DAG.getConstant(0, DL, MVT::i32);
3136 
3137     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
3138     if (!Offset)
3139       break;
3140 
3141     SDValue BitsFrom = N->getOperand(0);
3142     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
3143 
3144     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
3145 
3146     if (OffsetVal == 0) {
3147       // This is already sign / zero extended, so try to fold away extra BFEs.
3148       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
3149 
3150       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
3151       if (OpSignBits >= SignBits)
3152         return BitsFrom;
3153 
3154       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
3155       if (Signed) {
3156         // This is a sign_extend_inreg. Replace it to take advantage of existing
3157         // DAG Combines. If not eliminated, we will match back to BFE during
3158         // selection.
3159 
3160         // TODO: The sext_inreg of extended types ends, although we can could
3161         // handle them in a single BFE.
3162         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
3163                            DAG.getValueType(SmallVT));
3164       }
3165 
3166       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
3167     }
3168 
3169     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
3170       if (Signed) {
3171         return constantFoldBFE<int32_t>(DAG,
3172                                         CVal->getSExtValue(),
3173                                         OffsetVal,
3174                                         WidthVal,
3175                                         DL);
3176       }
3177 
3178       return constantFoldBFE<uint32_t>(DAG,
3179                                        CVal->getZExtValue(),
3180                                        OffsetVal,
3181                                        WidthVal,
3182                                        DL);
3183     }
3184 
3185     if ((OffsetVal + WidthVal) >= 32) {
3186       SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
3187       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
3188                          BitsFrom, ShiftVal);
3189     }
3190 
3191     if (BitsFrom.hasOneUse()) {
3192       APInt Demanded = APInt::getBitsSet(32,
3193                                          OffsetVal,
3194                                          OffsetVal + WidthVal);
3195 
3196       APInt KnownZero, KnownOne;
3197       TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3198                                             !DCI.isBeforeLegalizeOps());
3199       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3200       if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
3201           TLI.SimplifyDemandedBits(BitsFrom, Demanded,
3202                                    KnownZero, KnownOne, TLO)) {
3203         DCI.CommitTargetLoweringOpt(TLO);
3204       }
3205     }
3206 
3207     break;
3208   }
3209   case ISD::LOAD:
3210     return performLoadCombine(N, DCI);
3211   case ISD::STORE:
3212     return performStoreCombine(N, DCI);
3213   }
3214   return SDValue();
3215 }
3216 
3217 //===----------------------------------------------------------------------===//
3218 // Helper functions
3219 //===----------------------------------------------------------------------===//
3220 
3221 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
3222                                                   const TargetRegisterClass *RC,
3223                                                    unsigned Reg, EVT VT) const {
3224   MachineFunction &MF = DAG.getMachineFunction();
3225   MachineRegisterInfo &MRI = MF.getRegInfo();
3226   unsigned VirtualRegister;
3227   if (!MRI.isLiveIn(Reg)) {
3228     VirtualRegister = MRI.createVirtualRegister(RC);
3229     MRI.addLiveIn(Reg, VirtualRegister);
3230   } else {
3231     VirtualRegister = MRI.getLiveInVirtReg(Reg);
3232   }
3233   return DAG.getRegister(VirtualRegister, VT);
3234 }
3235 
3236 uint32_t AMDGPUTargetLowering::getImplicitParameterOffset(
3237     const AMDGPUMachineFunction *MFI, const ImplicitParameter Param) const {
3238   unsigned Alignment = Subtarget->getAlignmentForImplicitArgPtr();
3239   uint64_t ArgOffset = alignTo(MFI->getABIArgOffset(), Alignment);
3240   switch (Param) {
3241   case GRID_DIM:
3242     return ArgOffset;
3243   case GRID_OFFSET:
3244     return ArgOffset + 4;
3245   }
3246   llvm_unreachable("unexpected implicit parameter type");
3247 }
3248 
3249 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
3250 
3251 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
3252   switch ((AMDGPUISD::NodeType)Opcode) {
3253   case AMDGPUISD::FIRST_NUMBER: break;
3254   // AMDIL DAG nodes
3255   NODE_NAME_CASE(CALL);
3256   NODE_NAME_CASE(UMUL);
3257   NODE_NAME_CASE(BRANCH_COND);
3258 
3259   // AMDGPU DAG nodes
3260   NODE_NAME_CASE(ENDPGM)
3261   NODE_NAME_CASE(RETURN)
3262   NODE_NAME_CASE(DWORDADDR)
3263   NODE_NAME_CASE(FRACT)
3264   NODE_NAME_CASE(SETCC)
3265   NODE_NAME_CASE(SETREG)
3266   NODE_NAME_CASE(FMA_W_CHAIN)
3267   NODE_NAME_CASE(FMUL_W_CHAIN)
3268   NODE_NAME_CASE(CLAMP)
3269   NODE_NAME_CASE(COS_HW)
3270   NODE_NAME_CASE(SIN_HW)
3271   NODE_NAME_CASE(FMAX_LEGACY)
3272   NODE_NAME_CASE(FMIN_LEGACY)
3273   NODE_NAME_CASE(FMAX3)
3274   NODE_NAME_CASE(SMAX3)
3275   NODE_NAME_CASE(UMAX3)
3276   NODE_NAME_CASE(FMIN3)
3277   NODE_NAME_CASE(SMIN3)
3278   NODE_NAME_CASE(UMIN3)
3279   NODE_NAME_CASE(FMED3)
3280   NODE_NAME_CASE(SMED3)
3281   NODE_NAME_CASE(UMED3)
3282   NODE_NAME_CASE(URECIP)
3283   NODE_NAME_CASE(DIV_SCALE)
3284   NODE_NAME_CASE(DIV_FMAS)
3285   NODE_NAME_CASE(DIV_FIXUP)
3286   NODE_NAME_CASE(TRIG_PREOP)
3287   NODE_NAME_CASE(RCP)
3288   NODE_NAME_CASE(RSQ)
3289   NODE_NAME_CASE(RCP_LEGACY)
3290   NODE_NAME_CASE(RSQ_LEGACY)
3291   NODE_NAME_CASE(FMUL_LEGACY)
3292   NODE_NAME_CASE(RSQ_CLAMP)
3293   NODE_NAME_CASE(LDEXP)
3294   NODE_NAME_CASE(FP_CLASS)
3295   NODE_NAME_CASE(DOT4)
3296   NODE_NAME_CASE(CARRY)
3297   NODE_NAME_CASE(BORROW)
3298   NODE_NAME_CASE(BFE_U32)
3299   NODE_NAME_CASE(BFE_I32)
3300   NODE_NAME_CASE(BFI)
3301   NODE_NAME_CASE(BFM)
3302   NODE_NAME_CASE(FFBH_U32)
3303   NODE_NAME_CASE(FFBH_I32)
3304   NODE_NAME_CASE(MUL_U24)
3305   NODE_NAME_CASE(MUL_I24)
3306   NODE_NAME_CASE(MULHI_U24)
3307   NODE_NAME_CASE(MULHI_I24)
3308   NODE_NAME_CASE(MUL_LOHI_U24)
3309   NODE_NAME_CASE(MUL_LOHI_I24)
3310   NODE_NAME_CASE(MAD_U24)
3311   NODE_NAME_CASE(MAD_I24)
3312   NODE_NAME_CASE(TEXTURE_FETCH)
3313   NODE_NAME_CASE(EXPORT)
3314   NODE_NAME_CASE(EXPORT_DONE)
3315   NODE_NAME_CASE(R600_EXPORT)
3316   NODE_NAME_CASE(CONST_ADDRESS)
3317   NODE_NAME_CASE(REGISTER_LOAD)
3318   NODE_NAME_CASE(REGISTER_STORE)
3319   NODE_NAME_CASE(LOAD_INPUT)
3320   NODE_NAME_CASE(SAMPLE)
3321   NODE_NAME_CASE(SAMPLEB)
3322   NODE_NAME_CASE(SAMPLED)
3323   NODE_NAME_CASE(SAMPLEL)
3324   NODE_NAME_CASE(CVT_F32_UBYTE0)
3325   NODE_NAME_CASE(CVT_F32_UBYTE1)
3326   NODE_NAME_CASE(CVT_F32_UBYTE2)
3327   NODE_NAME_CASE(CVT_F32_UBYTE3)
3328   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
3329   NODE_NAME_CASE(CONST_DATA_PTR)
3330   NODE_NAME_CASE(PC_ADD_REL_OFFSET)
3331   NODE_NAME_CASE(KILL)
3332   NODE_NAME_CASE(DUMMY_CHAIN)
3333   case AMDGPUISD::FIRST_MEM_OPCODE_NUMBER: break;
3334   NODE_NAME_CASE(SENDMSG)
3335   NODE_NAME_CASE(SENDMSGHALT)
3336   NODE_NAME_CASE(INTERP_MOV)
3337   NODE_NAME_CASE(INTERP_P1)
3338   NODE_NAME_CASE(INTERP_P2)
3339   NODE_NAME_CASE(STORE_MSKOR)
3340   NODE_NAME_CASE(LOAD_CONSTANT)
3341   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
3342   NODE_NAME_CASE(ATOMIC_CMP_SWAP)
3343   NODE_NAME_CASE(ATOMIC_INC)
3344   NODE_NAME_CASE(ATOMIC_DEC)
3345   NODE_NAME_CASE(BUFFER_LOAD)
3346   NODE_NAME_CASE(BUFFER_LOAD_FORMAT)
3347   case AMDGPUISD::LAST_AMDGPU_ISD_NUMBER: break;
3348   }
3349   return nullptr;
3350 }
3351 
3352 SDValue AMDGPUTargetLowering::getSqrtEstimate(SDValue Operand,
3353                                               SelectionDAG &DAG, int Enabled,
3354                                               int &RefinementSteps,
3355                                               bool &UseOneConstNR,
3356                                               bool Reciprocal) const {
3357   EVT VT = Operand.getValueType();
3358 
3359   if (VT == MVT::f32) {
3360     RefinementSteps = 0;
3361     return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
3362   }
3363 
3364   // TODO: There is also f64 rsq instruction, but the documentation is less
3365   // clear on its precision.
3366 
3367   return SDValue();
3368 }
3369 
3370 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
3371                                                SelectionDAG &DAG, int Enabled,
3372                                                int &RefinementSteps) const {
3373   EVT VT = Operand.getValueType();
3374 
3375   if (VT == MVT::f32) {
3376     // Reciprocal, < 1 ulp error.
3377     //
3378     // This reciprocal approximation converges to < 0.5 ulp error with one
3379     // newton rhapson performed with two fused multiple adds (FMAs).
3380 
3381     RefinementSteps = 0;
3382     return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
3383   }
3384 
3385   // TODO: There is also f64 rcp instruction, but the documentation is less
3386   // clear on its precision.
3387 
3388   return SDValue();
3389 }
3390 
3391 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
3392   const SDValue Op,
3393   APInt &KnownZero,
3394   APInt &KnownOne,
3395   const SelectionDAG &DAG,
3396   unsigned Depth) const {
3397 
3398   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
3399 
3400   APInt KnownZero2;
3401   APInt KnownOne2;
3402   unsigned Opc = Op.getOpcode();
3403 
3404   switch (Opc) {
3405   default:
3406     break;
3407   case AMDGPUISD::CARRY:
3408   case AMDGPUISD::BORROW: {
3409     KnownZero = APInt::getHighBitsSet(32, 31);
3410     break;
3411   }
3412 
3413   case AMDGPUISD::BFE_I32:
3414   case AMDGPUISD::BFE_U32: {
3415     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3416     if (!CWidth)
3417       return;
3418 
3419     unsigned BitWidth = 32;
3420     uint32_t Width = CWidth->getZExtValue() & 0x1f;
3421 
3422     if (Opc == AMDGPUISD::BFE_U32)
3423       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
3424 
3425     break;
3426   }
3427   }
3428 }
3429 
3430 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
3431   SDValue Op,
3432   const SelectionDAG &DAG,
3433   unsigned Depth) const {
3434   switch (Op.getOpcode()) {
3435   case AMDGPUISD::BFE_I32: {
3436     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3437     if (!Width)
3438       return 1;
3439 
3440     unsigned SignBits = 32 - Width->getZExtValue() + 1;
3441     if (!isNullConstant(Op.getOperand(1)))
3442       return SignBits;
3443 
3444     // TODO: Could probably figure something out with non-0 offsets.
3445     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3446     return std::max(SignBits, Op0SignBits);
3447   }
3448 
3449   case AMDGPUISD::BFE_U32: {
3450     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3451     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
3452   }
3453 
3454   case AMDGPUISD::CARRY:
3455   case AMDGPUISD::BORROW:
3456     return 31;
3457 
3458   default:
3459     return 1;
3460   }
3461 }
3462