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