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