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