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