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