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