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