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