R600/SI: Add a note about the order of the operands to div_scale
[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   TargetLowering(TM, new TargetLoweringObjectFileELF()) {
107
108   Subtarget = &TM.getSubtarget<AMDGPUSubtarget>();
109
110   setOperationAction(ISD::Constant, MVT::i32, Legal);
111   setOperationAction(ISD::Constant, MVT::i64, Legal);
112   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
113   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
114
115   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
116   setOperationAction(ISD::BRIND, MVT::Other, Expand);
117
118   // We need to custom lower some of the intrinsics
119   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
120
121   // Library functions.  These default to Expand, but we have instructions
122   // for them.
123   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
124   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
125   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
126   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
127   setOperationAction(ISD::FABS,   MVT::f32, Legal);
128   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
129   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
130   setOperationAction(ISD::FROUND, MVT::f32, Legal);
131   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
132
133   setOperationAction(ISD::FREM, MVT::f32, Custom);
134   setOperationAction(ISD::FREM, MVT::f64, Custom);
135
136   // Lower floating point store/load to integer store/load to reduce the number
137   // of patterns in tablegen.
138   setOperationAction(ISD::STORE, MVT::f32, Promote);
139   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
140
141   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
142   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
143
144   setOperationAction(ISD::STORE, MVT::i64, Promote);
145   AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
146
147   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
148   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
149
150   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
151   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
152
153   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
154   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
155
156   setOperationAction(ISD::STORE, MVT::f64, Promote);
157   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
158
159   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
160   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v2i64);
161
162   // Custom lowering of vector stores is required for local address space
163   // stores.
164   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
165   // XXX: Native v2i32 local address space stores are possible, but not
166   // currently implemented.
167   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
168
169   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
170   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
171   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
172
173   // XXX: This can be change to Custom, once ExpandVectorStores can
174   // handle 64-bit stores.
175   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
176
177   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
178   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
179   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
180   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
181   setTruncStoreAction(MVT::v4i64, MVT::v4i1, Expand);
182
183
184   setOperationAction(ISD::LOAD, MVT::f32, Promote);
185   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
186
187   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
188   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
189
190   setOperationAction(ISD::LOAD, MVT::i64, Promote);
191   AddPromotedToType(ISD::LOAD, MVT::i64, 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   setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Expand);
220   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Expand);
221   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i8, Expand);
222   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
223   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Expand);
224   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Expand);
225   setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Expand);
226   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Expand);
227   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, Expand);
228   setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Expand);
229   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Expand);
230   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, Expand);
231
232   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
233
234   if (Subtarget->getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
235     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
236     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
237     setOperationAction(ISD::FRINT, MVT::f64, Custom);
238     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
239   }
240
241   if (!Subtarget->hasBFI()) {
242     // fcopysign can be done in a single instruction with BFI.
243     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
244     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
245   }
246
247   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
248
249   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
250   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
251   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
252
253   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
254   for (MVT VT : ScalarIntVTs) {
255     setOperationAction(ISD::SREM, VT, Expand);
256     setOperationAction(ISD::SDIV, VT, Expand);
257
258     // GPU does not have divrem function for signed or unsigned.
259     setOperationAction(ISD::SDIVREM, VT, Custom);
260     setOperationAction(ISD::UDIVREM, VT, Custom);
261
262     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
263     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
264     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
265
266     setOperationAction(ISD::BSWAP, VT, Expand);
267     setOperationAction(ISD::CTTZ, VT, Expand);
268     setOperationAction(ISD::CTLZ, VT, Expand);
269   }
270
271   if (!Subtarget->hasBCNT(32))
272     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
273
274   if (!Subtarget->hasBCNT(64))
275     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
276
277   // The hardware supports 32-bit ROTR, but not ROTL.
278   setOperationAction(ISD::ROTL, MVT::i32, Expand);
279   setOperationAction(ISD::ROTL, MVT::i64, Expand);
280   setOperationAction(ISD::ROTR, MVT::i64, Expand);
281
282   setOperationAction(ISD::MUL, MVT::i64, Expand);
283   setOperationAction(ISD::MULHU, MVT::i64, Expand);
284   setOperationAction(ISD::MULHS, MVT::i64, Expand);
285   setOperationAction(ISD::UDIV, MVT::i32, Expand);
286   setOperationAction(ISD::UREM, MVT::i32, Expand);
287   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
288   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
289
290   if (!Subtarget->hasFFBH())
291     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
292
293   if (!Subtarget->hasFFBL())
294     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
295
296   static const MVT::SimpleValueType VectorIntTypes[] = {
297     MVT::v2i32, MVT::v4i32
298   };
299
300   for (MVT VT : VectorIntTypes) {
301     // Expand the following operations for the current type by default.
302     setOperationAction(ISD::ADD,  VT, Expand);
303     setOperationAction(ISD::AND,  VT, Expand);
304     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
305     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
306     setOperationAction(ISD::MUL,  VT, Expand);
307     setOperationAction(ISD::OR,   VT, Expand);
308     setOperationAction(ISD::SHL,  VT, Expand);
309     setOperationAction(ISD::SRA,  VT, Expand);
310     setOperationAction(ISD::SRL,  VT, Expand);
311     setOperationAction(ISD::ROTL, VT, Expand);
312     setOperationAction(ISD::ROTR, VT, Expand);
313     setOperationAction(ISD::SUB,  VT, Expand);
314     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
315     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
316     setOperationAction(ISD::SDIV, VT, Expand);
317     setOperationAction(ISD::UDIV, VT, Expand);
318     setOperationAction(ISD::SREM, VT, Expand);
319     setOperationAction(ISD::UREM, VT, Expand);
320     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
321     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
322     setOperationAction(ISD::SDIVREM, VT, Custom);
323     setOperationAction(ISD::UDIVREM, VT, Custom);
324     setOperationAction(ISD::ADDC, VT, Expand);
325     setOperationAction(ISD::SUBC, VT, Expand);
326     setOperationAction(ISD::ADDE, VT, Expand);
327     setOperationAction(ISD::SUBE, VT, Expand);
328     setOperationAction(ISD::SELECT, VT, Expand);
329     setOperationAction(ISD::VSELECT, VT, Expand);
330     setOperationAction(ISD::SELECT_CC, VT, Expand);
331     setOperationAction(ISD::XOR,  VT, Expand);
332     setOperationAction(ISD::BSWAP, VT, Expand);
333     setOperationAction(ISD::CTPOP, VT, Expand);
334     setOperationAction(ISD::CTTZ, VT, Expand);
335     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
336     setOperationAction(ISD::CTLZ, VT, Expand);
337     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
338     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
339   }
340
341   static const MVT::SimpleValueType FloatVectorTypes[] = {
342     MVT::v2f32, MVT::v4f32
343   };
344
345   for (MVT VT : FloatVectorTypes) {
346     setOperationAction(ISD::FABS, VT, Expand);
347     setOperationAction(ISD::FADD, VT, Expand);
348     setOperationAction(ISD::FCEIL, VT, Expand);
349     setOperationAction(ISD::FCOS, VT, Expand);
350     setOperationAction(ISD::FDIV, VT, Expand);
351     setOperationAction(ISD::FEXP2, VT, Expand);
352     setOperationAction(ISD::FLOG2, VT, Expand);
353     setOperationAction(ISD::FREM, VT, Expand);
354     setOperationAction(ISD::FPOW, VT, Expand);
355     setOperationAction(ISD::FFLOOR, VT, Expand);
356     setOperationAction(ISD::FTRUNC, VT, Expand);
357     setOperationAction(ISD::FMUL, VT, Expand);
358     setOperationAction(ISD::FMA, VT, Expand);
359     setOperationAction(ISD::FRINT, VT, Expand);
360     setOperationAction(ISD::FNEARBYINT, VT, Expand);
361     setOperationAction(ISD::FSQRT, VT, Expand);
362     setOperationAction(ISD::FSIN, VT, Expand);
363     setOperationAction(ISD::FSUB, VT, Expand);
364     setOperationAction(ISD::FNEG, VT, Expand);
365     setOperationAction(ISD::SELECT, VT, Expand);
366     setOperationAction(ISD::VSELECT, VT, Expand);
367     setOperationAction(ISD::SELECT_CC, VT, Expand);
368     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
369     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
370   }
371
372   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
373   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
374
375   setTargetDAGCombine(ISD::MUL);
376   setTargetDAGCombine(ISD::SELECT_CC);
377   setTargetDAGCombine(ISD::STORE);
378
379   setSchedulingPreference(Sched::RegPressure);
380   setJumpIsExpensive(true);
381
382   // SI at least has hardware support for floating point exceptions, but no way
383   // of using or handling them is implemented. They are also optional in OpenCL
384   // (Section 7.3)
385   setHasFloatingPointExceptions(false);
386
387   setSelectIsExpensive(false);
388   PredictableSelectIsExpensive = false;
389
390   // There are no integer divide instructions, and these expand to a pretty
391   // large sequence of instructions.
392   setIntDivIsCheap(false);
393   setPow2SDivIsCheap(false);
394
395   // FIXME: Need to really handle these.
396   MaxStoresPerMemcpy  = 4096;
397   MaxStoresPerMemmove = 4096;
398   MaxStoresPerMemset  = 4096;
399 }
400
401 //===----------------------------------------------------------------------===//
402 // Target Information
403 //===----------------------------------------------------------------------===//
404
405 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
406   return MVT::i32;
407 }
408
409 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
410   return true;
411 }
412
413 // The backend supports 32 and 64 bit floating point immediates.
414 // FIXME: Why are we reporting vectors of FP immediates as legal?
415 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
416   EVT ScalarVT = VT.getScalarType();
417   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64);
418 }
419
420 // We don't want to shrink f64 / f32 constants.
421 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
422   EVT ScalarVT = VT.getScalarType();
423   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
424 }
425
426 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
427                                                    EVT CastTy) const {
428   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
429     return true;
430
431   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
432   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
433
434   return ((LScalarSize <= CastScalarSize) ||
435           (CastScalarSize >= 32) ||
436           (LScalarSize < 32));
437 }
438
439 //===---------------------------------------------------------------------===//
440 // Target Properties
441 //===---------------------------------------------------------------------===//
442
443 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
444   assert(VT.isFloatingPoint());
445   return VT == MVT::f32 || VT == MVT::f64;
446 }
447
448 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
449   assert(VT.isFloatingPoint());
450   return VT == MVT::f32 || VT == MVT::f64;
451 }
452
453 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
454   // Truncate is just accessing a subregister.
455   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
456 }
457
458 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
459   // Truncate is just accessing a subregister.
460   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
461          (Dest->getPrimitiveSizeInBits() % 32 == 0);
462 }
463
464 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
465   const DataLayout *DL = getDataLayout();
466   unsigned SrcSize = DL->getTypeSizeInBits(Src->getScalarType());
467   unsigned DestSize = DL->getTypeSizeInBits(Dest->getScalarType());
468
469   return SrcSize == 32 && DestSize == 64;
470 }
471
472 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
473   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
474   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
475   // this will enable reducing 64-bit operations the 32-bit, which is always
476   // good.
477   return Src == MVT::i32 && Dest == MVT::i64;
478 }
479
480 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
481   return isZExtFree(Val.getValueType(), VT2);
482 }
483
484 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
485   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
486   // limited number of native 64-bit operations. Shrinking an operation to fit
487   // in a single 32-bit register should always be helpful. As currently used,
488   // this is much less general than the name suggests, and is only used in
489   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
490   // not profitable, and may actually be harmful.
491   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
492 }
493
494 //===---------------------------------------------------------------------===//
495 // TargetLowering Callbacks
496 //===---------------------------------------------------------------------===//
497
498 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
499                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
500
501   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
502 }
503
504 SDValue AMDGPUTargetLowering::LowerReturn(
505                                      SDValue Chain,
506                                      CallingConv::ID CallConv,
507                                      bool isVarArg,
508                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
509                                      const SmallVectorImpl<SDValue> &OutVals,
510                                      SDLoc DL, SelectionDAG &DAG) const {
511   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
512 }
513
514 //===---------------------------------------------------------------------===//
515 // Target specific lowering
516 //===---------------------------------------------------------------------===//
517
518 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
519                                         SmallVectorImpl<SDValue> &InVals) const {
520   SDValue Callee = CLI.Callee;
521   SelectionDAG &DAG = CLI.DAG;
522
523   const Function &Fn = *DAG.getMachineFunction().getFunction();
524
525   StringRef FuncName("<unknown>");
526
527   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
528     FuncName = G->getSymbol();
529   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
530     FuncName = G->getGlobal()->getName();
531
532   DiagnosticInfoUnsupported NoCalls(Fn, "call to function " + FuncName);
533   DAG.getContext()->diagnose(NoCalls);
534   return SDValue();
535 }
536
537 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
538                                              SelectionDAG &DAG) const {
539   switch (Op.getOpcode()) {
540   default:
541     Op.getNode()->dump();
542     llvm_unreachable("Custom lowering code for this"
543                      "instruction is not implemented yet!");
544     break;
545   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
546   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
547   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
548   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
549   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
550   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
551   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
552   case ISD::FREM: return LowerFREM(Op, DAG);
553   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
554   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
555   case ISD::FRINT: return LowerFRINT(Op, DAG);
556   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
557   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
558   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
559   }
560   return Op;
561 }
562
563 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
564                                               SmallVectorImpl<SDValue> &Results,
565                                               SelectionDAG &DAG) const {
566   switch (N->getOpcode()) {
567   case ISD::SIGN_EXTEND_INREG:
568     // Different parts of legalization seem to interpret which type of
569     // sign_extend_inreg is the one to check for custom lowering. The extended
570     // from type is what really matters, but some places check for custom
571     // lowering of the result type. This results in trying to use
572     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
573     // nothing here and let the illegal result integer be handled normally.
574     return;
575   case ISD::LOAD: {
576     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
577     if (!Node)
578       return;
579
580     Results.push_back(SDValue(Node, 0));
581     Results.push_back(SDValue(Node, 1));
582     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
583     // function
584     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
585     return;
586   }
587   case ISD::STORE: {
588     SDValue Lowered = LowerSTORE(SDValue(N, 0), DAG);
589     if (Lowered.getNode())
590       Results.push_back(Lowered);
591     return;
592   }
593   default:
594     return;
595   }
596 }
597
598 // FIXME: This implements accesses to initialized globals in the constant
599 // address space by copying them to private and accessing that. It does not
600 // properly handle illegal types or vectors. The private vector loads are not
601 // scalarized, and the illegal scalars hit an assertion. This technique will not
602 // work well with large initializers, and this should eventually be
603 // removed. Initialized globals should be placed into a data section that the
604 // runtime will load into a buffer before the kernel is executed. Uses of the
605 // global need to be replaced with a pointer loaded from an implicit kernel
606 // argument into this buffer holding the copy of the data, which will remove the
607 // need for any of this.
608 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
609                                                        const GlobalValue *GV,
610                                                        const SDValue &InitPtr,
611                                                        SDValue Chain,
612                                                        SelectionDAG &DAG) const {
613   const DataLayout *TD = getTargetMachine().getSubtargetImpl()->getDataLayout();
614   SDLoc DL(InitPtr);
615   Type *InitTy = Init->getType();
616
617   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
618     EVT VT = EVT::getEVT(InitTy);
619     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
620     return DAG.getStore(Chain, DL, DAG.getConstant(*CI, VT), InitPtr,
621                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
622                         TD->getPrefTypeAlignment(InitTy));
623   }
624
625   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
626     EVT VT = EVT::getEVT(CFP->getType());
627     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
628     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
629                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
630                  TD->getPrefTypeAlignment(CFP->getType()));
631   }
632
633   if (StructType *ST = dyn_cast<StructType>(InitTy)) {
634     const StructLayout *SL = TD->getStructLayout(ST);
635
636     EVT PtrVT = InitPtr.getValueType();
637     SmallVector<SDValue, 8> Chains;
638
639     for (unsigned I = 0, N = ST->getNumElements(); I != N; ++I) {
640       SDValue Offset = DAG.getConstant(SL->getElementOffset(I), PtrVT);
641       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
642
643       Constant *Elt = Init->getAggregateElement(I);
644       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
645     }
646
647     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
648   }
649
650   if (SequentialType *SeqTy = dyn_cast<SequentialType>(InitTy)) {
651     EVT PtrVT = InitPtr.getValueType();
652
653     unsigned NumElements;
654     if (ArrayType *AT = dyn_cast<ArrayType>(SeqTy))
655       NumElements = AT->getNumElements();
656     else if (VectorType *VT = dyn_cast<VectorType>(SeqTy))
657       NumElements = VT->getNumElements();
658     else
659       llvm_unreachable("Unexpected type");
660
661     unsigned EltSize = TD->getTypeAllocSize(SeqTy->getElementType());
662     SmallVector<SDValue, 8> Chains;
663     for (unsigned i = 0; i < NumElements; ++i) {
664       SDValue Offset = DAG.getConstant(i * EltSize, PtrVT);
665       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
666
667       Constant *Elt = Init->getAggregateElement(i);
668       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
669     }
670
671     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
672   }
673
674   if (isa<UndefValue>(Init)) {
675     EVT VT = EVT::getEVT(InitTy);
676     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
677     return DAG.getStore(Chain, DL, DAG.getUNDEF(VT), InitPtr,
678                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
679                         TD->getPrefTypeAlignment(InitTy));
680   }
681
682   Init->dump();
683   llvm_unreachable("Unhandled constant initializer");
684 }
685
686 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
687                                                  SDValue Op,
688                                                  SelectionDAG &DAG) const {
689
690   const DataLayout *TD = getTargetMachine().getSubtargetImpl()->getDataLayout();
691   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
692   const GlobalValue *GV = G->getGlobal();
693
694   switch (G->getAddressSpace()) {
695   default: llvm_unreachable("Global Address lowering not implemented for this "
696                             "address space");
697   case AMDGPUAS::LOCAL_ADDRESS: {
698     // XXX: What does the value of G->getOffset() mean?
699     assert(G->getOffset() == 0 &&
700          "Do not know what to do with an non-zero offset");
701
702     unsigned Offset;
703     if (MFI->LocalMemoryObjects.count(GV) == 0) {
704       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
705       Offset = MFI->LDSSize;
706       MFI->LocalMemoryObjects[GV] = Offset;
707       // XXX: Account for alignment?
708       MFI->LDSSize += Size;
709     } else {
710       Offset = MFI->LocalMemoryObjects[GV];
711     }
712
713     return DAG.getConstant(Offset, getPointerTy(AMDGPUAS::LOCAL_ADDRESS));
714   }
715   case AMDGPUAS::CONSTANT_ADDRESS: {
716     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
717     Type *EltType = GV->getType()->getElementType();
718     unsigned Size = TD->getTypeAllocSize(EltType);
719     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
720
721     MVT PrivPtrVT = getPointerTy(AMDGPUAS::PRIVATE_ADDRESS);
722     MVT ConstPtrVT = getPointerTy(AMDGPUAS::CONSTANT_ADDRESS);
723
724     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
725     SDValue InitPtr = DAG.getFrameIndex(FI, PrivPtrVT);
726
727     const GlobalVariable *Var = cast<GlobalVariable>(GV);
728     if (!Var->hasInitializer()) {
729       // This has no use, but bugpoint will hit it.
730       return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
731     }
732
733     const Constant *Init = Var->getInitializer();
734     SmallVector<SDNode*, 8> WorkList;
735
736     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
737                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
738       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
739         continue;
740       WorkList.push_back(*I);
741     }
742     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
743     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
744                                            E = WorkList.end(); I != E; ++I) {
745       SmallVector<SDValue, 8> Ops;
746       Ops.push_back(Chain);
747       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
748         Ops.push_back((*I)->getOperand(i));
749       }
750       DAG.UpdateNodeOperands(*I, Ops);
751     }
752     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
753   }
754   }
755 }
756
757 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
758                                                   SelectionDAG &DAG) const {
759   SmallVector<SDValue, 8> Args;
760   SDValue A = Op.getOperand(0);
761   SDValue B = Op.getOperand(1);
762
763   DAG.ExtractVectorElements(A, Args);
764   DAG.ExtractVectorElements(B, Args);
765
766   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
767 }
768
769 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
770                                                      SelectionDAG &DAG) const {
771
772   SmallVector<SDValue, 8> Args;
773   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
774   EVT VT = Op.getValueType();
775   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
776                             VT.getVectorNumElements());
777
778   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
779 }
780
781 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
782                                               SelectionDAG &DAG) const {
783
784   MachineFunction &MF = DAG.getMachineFunction();
785   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering *>(
786       getTargetMachine().getSubtargetImpl()->getFrameLowering());
787
788   FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op);
789
790   unsigned FrameIndex = FIN->getIndex();
791   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
792   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
793                          Op.getValueType());
794 }
795
796 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
797     SelectionDAG &DAG) const {
798   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
799   SDLoc DL(Op);
800   EVT VT = Op.getValueType();
801
802   switch (IntrinsicID) {
803     default: return Op;
804     case AMDGPUIntrinsic::AMDGPU_abs:
805     case AMDGPUIntrinsic::AMDIL_abs: // Legacy name.
806       return LowerIntrinsicIABS(Op, DAG);
807     case AMDGPUIntrinsic::AMDGPU_lrp:
808       return LowerIntrinsicLRP(Op, DAG);
809     case AMDGPUIntrinsic::AMDGPU_fract:
810     case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
811       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
812
813     case AMDGPUIntrinsic::AMDGPU_clamp:
814     case AMDGPUIntrinsic::AMDIL_clamp: // Legacy name.
815       return DAG.getNode(AMDGPUISD::CLAMP, DL, VT,
816                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
817
818     case Intrinsic::AMDGPU_div_scale: {
819       // 3rd parameter required to be a constant.
820       const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
821       if (!Param)
822         return DAG.getUNDEF(VT);
823
824       // Translate to the operands expected by the machine instruction. The
825       // first parameter must be the same as the first instruction.
826       SDValue Numerator = Op.getOperand(1);
827       SDValue Denominator = Op.getOperand(2);
828
829       // Note this order is opposite of the machine instruction's operations,
830       // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
831       // intrinsic has the numerator as the first operand to match a normal
832       // division operation.
833
834       SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
835
836       return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
837                          Denominator, Numerator);
838     }
839
840     case Intrinsic::AMDGPU_div_fmas:
841       return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
842                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
843
844     case Intrinsic::AMDGPU_div_fixup:
845       return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
846                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
847
848     case Intrinsic::AMDGPU_trig_preop:
849       return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
850                          Op.getOperand(1), Op.getOperand(2));
851
852     case Intrinsic::AMDGPU_rcp:
853       return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
854
855     case Intrinsic::AMDGPU_rsq:
856       return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
857
858     case AMDGPUIntrinsic::AMDGPU_legacy_rsq:
859       return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
860
861     case Intrinsic::AMDGPU_rsq_clamped:
862       return DAG.getNode(AMDGPUISD::RSQ_CLAMPED, DL, VT, Op.getOperand(1));
863
864     case Intrinsic::AMDGPU_ldexp:
865       return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, Op.getOperand(1),
866                                                    Op.getOperand(2));
867
868     case AMDGPUIntrinsic::AMDGPU_imax:
869       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
870                                                   Op.getOperand(2));
871     case AMDGPUIntrinsic::AMDGPU_umax:
872       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
873                                                   Op.getOperand(2));
874     case AMDGPUIntrinsic::AMDGPU_imin:
875       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
876                                                   Op.getOperand(2));
877     case AMDGPUIntrinsic::AMDGPU_umin:
878       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
879                                                   Op.getOperand(2));
880
881     case AMDGPUIntrinsic::AMDGPU_umul24:
882       return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT,
883                          Op.getOperand(1), Op.getOperand(2));
884
885     case AMDGPUIntrinsic::AMDGPU_imul24:
886       return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT,
887                          Op.getOperand(1), Op.getOperand(2));
888
889     case AMDGPUIntrinsic::AMDGPU_umad24:
890       return DAG.getNode(AMDGPUISD::MAD_U24, DL, VT,
891                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
892
893     case AMDGPUIntrinsic::AMDGPU_imad24:
894       return DAG.getNode(AMDGPUISD::MAD_I24, DL, VT,
895                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
896
897     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0:
898       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1));
899
900     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1:
901       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1));
902
903     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2:
904       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1));
905
906     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3:
907       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1));
908
909     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
910       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
911                          Op.getOperand(1),
912                          Op.getOperand(2),
913                          Op.getOperand(3));
914
915     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
916       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
917                          Op.getOperand(1),
918                          Op.getOperand(2),
919                          Op.getOperand(3));
920
921     case AMDGPUIntrinsic::AMDGPU_bfi:
922       return DAG.getNode(AMDGPUISD::BFI, DL, VT,
923                          Op.getOperand(1),
924                          Op.getOperand(2),
925                          Op.getOperand(3));
926
927     case AMDGPUIntrinsic::AMDGPU_bfm:
928       return DAG.getNode(AMDGPUISD::BFM, DL, VT,
929                          Op.getOperand(1),
930                          Op.getOperand(2));
931
932     case AMDGPUIntrinsic::AMDGPU_brev:
933       return DAG.getNode(AMDGPUISD::BREV, DL, VT, Op.getOperand(1));
934
935     case AMDGPUIntrinsic::AMDIL_exp: // Legacy name.
936       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
937
938     case AMDGPUIntrinsic::AMDIL_round_nearest: // Legacy name.
939       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
940     case AMDGPUIntrinsic::AMDGPU_trunc: // Legacy name.
941       return DAG.getNode(ISD::FTRUNC, DL, VT, Op.getOperand(1));
942   }
943 }
944
945 ///IABS(a) = SMAX(sub(0, a), a)
946 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
947                                                  SelectionDAG &DAG) const {
948   SDLoc DL(Op);
949   EVT VT = Op.getValueType();
950   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
951                                               Op.getOperand(1));
952
953   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
954 }
955
956 /// Linear Interpolation
957 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
958 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
959                                                 SelectionDAG &DAG) const {
960   SDLoc DL(Op);
961   EVT VT = Op.getValueType();
962   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
963                                 DAG.getConstantFP(1.0f, MVT::f32),
964                                 Op.getOperand(1));
965   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
966                                                     Op.getOperand(3));
967   return DAG.getNode(ISD::FADD, DL, VT,
968       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
969       OneSubAC);
970 }
971
972 /// \brief Generate Min/Max node
973 SDValue AMDGPUTargetLowering::CombineMinMax(SDNode *N,
974                                             SelectionDAG &DAG) const {
975   SDLoc DL(N);
976   EVT VT = N->getValueType(0);
977
978   SDValue LHS = N->getOperand(0);
979   SDValue RHS = N->getOperand(1);
980   SDValue True = N->getOperand(2);
981   SDValue False = N->getOperand(3);
982   SDValue CC = N->getOperand(4);
983
984   if (VT != MVT::f32 ||
985       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
986     return SDValue();
987   }
988
989   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
990   switch (CCOpcode) {
991   case ISD::SETOEQ:
992   case ISD::SETONE:
993   case ISD::SETUNE:
994   case ISD::SETNE:
995   case ISD::SETUEQ:
996   case ISD::SETEQ:
997   case ISD::SETFALSE:
998   case ISD::SETFALSE2:
999   case ISD::SETTRUE:
1000   case ISD::SETTRUE2:
1001   case ISD::SETUO:
1002   case ISD::SETO:
1003     llvm_unreachable("Operation should already be optimised!");
1004   case ISD::SETULE:
1005   case ISD::SETULT:
1006   case ISD::SETOLE:
1007   case ISD::SETOLT:
1008   case ISD::SETLE:
1009   case ISD::SETLT: {
1010     unsigned Opc = (LHS == True) ? AMDGPUISD::FMIN : AMDGPUISD::FMAX;
1011     return DAG.getNode(Opc, DL, VT, LHS, RHS);
1012   }
1013   case ISD::SETGT:
1014   case ISD::SETGE:
1015   case ISD::SETUGE:
1016   case ISD::SETOGE:
1017   case ISD::SETUGT:
1018   case ISD::SETOGT: {
1019     unsigned Opc = (LHS == True) ? AMDGPUISD::FMAX : AMDGPUISD::FMIN;
1020     return DAG.getNode(Opc, DL, VT, LHS, RHS);
1021   }
1022   case ISD::SETCC_INVALID:
1023     llvm_unreachable("Invalid setcc condcode!");
1024   }
1025   return SDValue();
1026 }
1027
1028 SDValue AMDGPUTargetLowering::ScalarizeVectorLoad(const SDValue Op,
1029                                                   SelectionDAG &DAG) const {
1030   LoadSDNode *Load = cast<LoadSDNode>(Op);
1031   EVT MemVT = Load->getMemoryVT();
1032   EVT MemEltVT = MemVT.getVectorElementType();
1033
1034   EVT LoadVT = Op.getValueType();
1035   EVT EltVT = LoadVT.getVectorElementType();
1036   EVT PtrVT = Load->getBasePtr().getValueType();
1037
1038   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
1039   SmallVector<SDValue, 8> Loads;
1040   SmallVector<SDValue, 8> Chains;
1041
1042   SDLoc SL(Op);
1043   unsigned MemEltSize = MemEltVT.getStoreSize();
1044   MachinePointerInfo SrcValue(Load->getMemOperand()->getValue());
1045
1046   for (unsigned i = 0; i < NumElts; ++i) {
1047     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
1048                               DAG.getConstant(i * MemEltSize, PtrVT));
1049
1050     SDValue NewLoad
1051       = DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
1052                        Load->getChain(), Ptr,
1053                        SrcValue.getWithOffset(i * MemEltSize),
1054                        MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
1055                        Load->isInvariant(), Load->getAlignment());
1056     Loads.push_back(NewLoad.getValue(0));
1057     Chains.push_back(NewLoad.getValue(1));
1058   }
1059
1060   SDValue Ops[] = {
1061     DAG.getNode(ISD::BUILD_VECTOR, SL, LoadVT, Loads),
1062     DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains)
1063   };
1064
1065   return DAG.getMergeValues(Ops, SL);
1066 }
1067
1068 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1069                                               SelectionDAG &DAG) const {
1070   EVT VT = Op.getValueType();
1071
1072   // If this is a 2 element vector, we really want to scalarize and not create
1073   // weird 1 element vectors.
1074   if (VT.getVectorNumElements() == 2)
1075     return ScalarizeVectorLoad(Op, DAG);
1076
1077   LoadSDNode *Load = cast<LoadSDNode>(Op);
1078   SDValue BasePtr = Load->getBasePtr();
1079   EVT PtrVT = BasePtr.getValueType();
1080   EVT MemVT = Load->getMemoryVT();
1081   SDLoc SL(Op);
1082   MachinePointerInfo SrcValue(Load->getMemOperand()->getValue());
1083
1084   EVT LoVT, HiVT;
1085   EVT LoMemVT, HiMemVT;
1086   SDValue Lo, Hi;
1087
1088   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1089   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1090   std::tie(Lo, Hi) = DAG.SplitVector(Op, SL, LoVT, HiVT);
1091   SDValue LoLoad
1092     = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1093                      Load->getChain(), BasePtr,
1094                      SrcValue,
1095                      LoMemVT, Load->isVolatile(), Load->isNonTemporal(),
1096                      Load->isInvariant(), Load->getAlignment());
1097
1098   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1099                               DAG.getConstant(LoMemVT.getStoreSize(), PtrVT));
1100
1101   SDValue HiLoad
1102     = DAG.getExtLoad(Load->getExtensionType(), SL, HiVT,
1103                      Load->getChain(), HiPtr,
1104                      SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1105                      HiMemVT, Load->isVolatile(), Load->isNonTemporal(),
1106                      Load->isInvariant(), Load->getAlignment());
1107
1108   SDValue Ops[] = {
1109     DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad),
1110     DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1111                 LoLoad.getValue(1), HiLoad.getValue(1))
1112   };
1113
1114   return DAG.getMergeValues(Ops, SL);
1115 }
1116
1117 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
1118                                                SelectionDAG &DAG) const {
1119   StoreSDNode *Store = cast<StoreSDNode>(Op);
1120   EVT MemVT = Store->getMemoryVT();
1121   unsigned MemBits = MemVT.getSizeInBits();
1122
1123   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
1124   // truncating store into an i32 store.
1125   // XXX: We could also handle optimize other vector bitwidths.
1126   if (!MemVT.isVector() || MemBits > 32) {
1127     return SDValue();
1128   }
1129
1130   SDLoc DL(Op);
1131   SDValue Value = Store->getValue();
1132   EVT VT = Value.getValueType();
1133   EVT ElemVT = VT.getVectorElementType();
1134   SDValue Ptr = Store->getBasePtr();
1135   EVT MemEltVT = MemVT.getVectorElementType();
1136   unsigned MemEltBits = MemEltVT.getSizeInBits();
1137   unsigned MemNumElements = MemVT.getVectorNumElements();
1138   unsigned PackedSize = MemVT.getStoreSizeInBits();
1139   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, MVT::i32);
1140
1141   assert(Value.getValueType().getScalarSizeInBits() >= 32);
1142
1143   SDValue PackedValue;
1144   for (unsigned i = 0; i < MemNumElements; ++i) {
1145     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
1146                               DAG.getConstant(i, MVT::i32));
1147     Elt = DAG.getZExtOrTrunc(Elt, DL, MVT::i32);
1148     Elt = DAG.getNode(ISD::AND, DL, MVT::i32, Elt, Mask); // getZeroExtendInReg
1149
1150     SDValue Shift = DAG.getConstant(MemEltBits * i, MVT::i32);
1151     Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt, Shift);
1152
1153     if (i == 0) {
1154       PackedValue = Elt;
1155     } else {
1156       PackedValue = DAG.getNode(ISD::OR, DL, MVT::i32, PackedValue, Elt);
1157     }
1158   }
1159
1160   if (PackedSize < 32) {
1161     EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), PackedSize);
1162     return DAG.getTruncStore(Store->getChain(), DL, PackedValue, Ptr,
1163                              Store->getMemOperand()->getPointerInfo(),
1164                              PackedVT,
1165                              Store->isNonTemporal(), Store->isVolatile(),
1166                              Store->getAlignment());
1167   }
1168
1169   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
1170                       Store->getMemOperand()->getPointerInfo(),
1171                       Store->isVolatile(),  Store->isNonTemporal(),
1172                       Store->getAlignment());
1173 }
1174
1175 SDValue AMDGPUTargetLowering::ScalarizeVectorStore(SDValue Op,
1176                                                    SelectionDAG &DAG) const {
1177   StoreSDNode *Store = cast<StoreSDNode>(Op);
1178   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
1179   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
1180   EVT PtrVT = Store->getBasePtr().getValueType();
1181   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
1182   SDLoc SL(Op);
1183
1184   SmallVector<SDValue, 8> Chains;
1185
1186   unsigned EltSize = MemEltVT.getStoreSize();
1187   MachinePointerInfo SrcValue(Store->getMemOperand()->getValue());
1188
1189   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1190     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
1191                               Store->getValue(),
1192                               DAG.getConstant(i, MVT::i32));
1193
1194     SDValue Offset = DAG.getConstant(i * MemEltVT.getStoreSize(), PtrVT);
1195     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Store->getBasePtr(), Offset);
1196     SDValue NewStore =
1197       DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
1198                         SrcValue.getWithOffset(i * EltSize),
1199                         MemEltVT, Store->isNonTemporal(), Store->isVolatile(),
1200                         Store->getAlignment());
1201     Chains.push_back(NewStore);
1202   }
1203
1204   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains);
1205 }
1206
1207 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1208                                                SelectionDAG &DAG) const {
1209   StoreSDNode *Store = cast<StoreSDNode>(Op);
1210   SDValue Val = Store->getValue();
1211   EVT VT = Val.getValueType();
1212
1213   // If this is a 2 element vector, we really want to scalarize and not create
1214   // weird 1 element vectors.
1215   if (VT.getVectorNumElements() == 2)
1216     return ScalarizeVectorStore(Op, DAG);
1217
1218   EVT MemVT = Store->getMemoryVT();
1219   SDValue Chain = Store->getChain();
1220   SDValue BasePtr = Store->getBasePtr();
1221   SDLoc SL(Op);
1222
1223   EVT LoVT, HiVT;
1224   EVT LoMemVT, HiMemVT;
1225   SDValue Lo, Hi;
1226
1227   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1228   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1229   std::tie(Lo, Hi) = DAG.SplitVector(Val, SL, LoVT, HiVT);
1230
1231   EVT PtrVT = BasePtr.getValueType();
1232   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1233                               DAG.getConstant(LoMemVT.getStoreSize(), PtrVT));
1234
1235   MachinePointerInfo SrcValue(Store->getMemOperand()->getValue());
1236   SDValue LoStore
1237     = DAG.getTruncStore(Chain, SL, Lo,
1238                         BasePtr,
1239                         SrcValue,
1240                         LoMemVT,
1241                         Store->isNonTemporal(),
1242                         Store->isVolatile(),
1243                         Store->getAlignment());
1244   SDValue HiStore
1245     = DAG.getTruncStore(Chain, SL, Hi,
1246                         HiPtr,
1247                         SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1248                         HiMemVT,
1249                         Store->isNonTemporal(),
1250                         Store->isVolatile(),
1251                         Store->getAlignment());
1252
1253   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1254 }
1255
1256
1257 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1258   SDLoc DL(Op);
1259   LoadSDNode *Load = cast<LoadSDNode>(Op);
1260   ISD::LoadExtType ExtType = Load->getExtensionType();
1261   EVT VT = Op.getValueType();
1262   EVT MemVT = Load->getMemoryVT();
1263
1264   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
1265     // We can do the extload to 32-bits, and then need to separately extend to
1266     // 64-bits.
1267
1268     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
1269                                        Load->getChain(),
1270                                        Load->getBasePtr(),
1271                                        MemVT,
1272                                        Load->getMemOperand());
1273
1274     SDValue Ops[] = {
1275       DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32),
1276       ExtLoad32.getValue(1)
1277     };
1278
1279     return DAG.getMergeValues(Ops, DL);
1280   }
1281
1282   if (ExtType == ISD::NON_EXTLOAD && VT.getSizeInBits() < 32) {
1283     assert(VT == MVT::i1 && "Only i1 non-extloads expected");
1284     // FIXME: Copied from PPC
1285     // First, load into 32 bits, then truncate to 1 bit.
1286
1287     SDValue Chain = Load->getChain();
1288     SDValue BasePtr = Load->getBasePtr();
1289     MachineMemOperand *MMO = Load->getMemOperand();
1290
1291     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1292                                    BasePtr, MVT::i8, MMO);
1293
1294     SDValue Ops[] = {
1295       DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD),
1296       NewLD.getValue(1)
1297     };
1298
1299     return DAG.getMergeValues(Ops, DL);
1300   }
1301
1302   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS ||
1303       Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
1304       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
1305     return SDValue();
1306
1307
1308   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
1309                             DAG.getConstant(2, MVT::i32));
1310   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1311                             Load->getChain(), Ptr,
1312                             DAG.getTargetConstant(0, MVT::i32),
1313                             Op.getOperand(2));
1314   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
1315                                 Load->getBasePtr(),
1316                                 DAG.getConstant(0x3, MVT::i32));
1317   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1318                                  DAG.getConstant(3, MVT::i32));
1319
1320   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
1321
1322   EVT MemEltVT = MemVT.getScalarType();
1323   if (ExtType == ISD::SEXTLOAD) {
1324     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
1325
1326     SDValue Ops[] = {
1327       DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode),
1328       Load->getChain()
1329     };
1330
1331     return DAG.getMergeValues(Ops, DL);
1332   }
1333
1334   SDValue Ops[] = {
1335     DAG.getZeroExtendInReg(Ret, DL, MemEltVT),
1336     Load->getChain()
1337   };
1338
1339   return DAG.getMergeValues(Ops, DL);
1340 }
1341
1342 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1343   SDLoc DL(Op);
1344   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
1345   if (Result.getNode()) {
1346     return Result;
1347   }
1348
1349   StoreSDNode *Store = cast<StoreSDNode>(Op);
1350   SDValue Chain = Store->getChain();
1351   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1352        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
1353       Store->getValue().getValueType().isVector()) {
1354     return ScalarizeVectorStore(Op, DAG);
1355   }
1356
1357   EVT MemVT = Store->getMemoryVT();
1358   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
1359       MemVT.bitsLT(MVT::i32)) {
1360     unsigned Mask = 0;
1361     if (Store->getMemoryVT() == MVT::i8) {
1362       Mask = 0xff;
1363     } else if (Store->getMemoryVT() == MVT::i16) {
1364       Mask = 0xffff;
1365     }
1366     SDValue BasePtr = Store->getBasePtr();
1367     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
1368                               DAG.getConstant(2, MVT::i32));
1369     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
1370                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
1371
1372     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
1373                                   DAG.getConstant(0x3, MVT::i32));
1374
1375     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1376                                    DAG.getConstant(3, MVT::i32));
1377
1378     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
1379                                     Store->getValue());
1380
1381     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
1382
1383     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1384                                        MaskedValue, ShiftAmt);
1385
1386     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
1387                                   ShiftAmt);
1388     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
1389                           DAG.getConstant(0xffffffff, MVT::i32));
1390     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1391
1392     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1393     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1394                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
1395   }
1396   return SDValue();
1397 }
1398
1399 // This is a shortcut for integer division because we have fast i32<->f32
1400 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1401 // float is enough to accurately represent up to a 24-bit integer.
1402 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG, bool sign) const {
1403   SDLoc DL(Op);
1404   EVT VT = Op.getValueType();
1405   SDValue LHS = Op.getOperand(0);
1406   SDValue RHS = Op.getOperand(1);
1407   MVT IntVT = MVT::i32;
1408   MVT FltVT = MVT::f32;
1409
1410   ISD::NodeType ToFp  = sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1411   ISD::NodeType ToInt = sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1412
1413   if (VT.isVector()) {
1414     unsigned NElts = VT.getVectorNumElements();
1415     IntVT = MVT::getVectorVT(MVT::i32, NElts);
1416     FltVT = MVT::getVectorVT(MVT::f32, NElts);
1417   }
1418
1419   unsigned BitSize = VT.getScalarType().getSizeInBits();
1420
1421   SDValue jq = DAG.getConstant(1, IntVT);
1422
1423   if (sign) {
1424     // char|short jq = ia ^ ib;
1425     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1426
1427     // jq = jq >> (bitsize - 2)
1428     jq = DAG.getNode(ISD::SRA, DL, VT, jq, DAG.getConstant(BitSize - 2, VT));
1429
1430     // jq = jq | 0x1
1431     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, VT));
1432
1433     // jq = (int)jq
1434     jq = DAG.getSExtOrTrunc(jq, DL, IntVT);
1435   }
1436
1437   // int ia = (int)LHS;
1438   SDValue ia = sign ?
1439     DAG.getSExtOrTrunc(LHS, DL, IntVT) : DAG.getZExtOrTrunc(LHS, DL, IntVT);
1440
1441   // int ib, (int)RHS;
1442   SDValue ib = sign ?
1443     DAG.getSExtOrTrunc(RHS, DL, IntVT) : DAG.getZExtOrTrunc(RHS, DL, IntVT);
1444
1445   // float fa = (float)ia;
1446   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1447
1448   // float fb = (float)ib;
1449   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1450
1451   // float fq = native_divide(fa, fb);
1452   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1453                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1454
1455   // fq = trunc(fq);
1456   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1457
1458   // float fqneg = -fq;
1459   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1460
1461   // float fr = mad(fqneg, fb, fa);
1462   SDValue fr = DAG.getNode(ISD::FADD, DL, FltVT,
1463                            DAG.getNode(ISD::FMUL, DL, FltVT, fqneg, fb), fa);
1464
1465   // int iq = (int)fq;
1466   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1467
1468   // fr = fabs(fr);
1469   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1470
1471   // fb = fabs(fb);
1472   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1473
1474   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), VT);
1475
1476   // int cv = fr >= fb;
1477   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1478
1479   // jq = (cv ? jq : 0);
1480   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, VT));
1481
1482   // dst = trunc/extend to legal type
1483   iq = sign ? DAG.getSExtOrTrunc(iq, DL, VT) : DAG.getZExtOrTrunc(iq, DL, VT);
1484
1485   // dst = iq + jq;
1486   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1487
1488   // Rem needs compensation, it's easier to recompute it
1489   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1490   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1491
1492   SDValue Res[2] = {
1493     Div,
1494     Rem
1495   };
1496   return DAG.getMergeValues(Res, DL);
1497 }
1498
1499 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1500                                            SelectionDAG &DAG) const {
1501   SDLoc DL(Op);
1502   EVT VT = Op.getValueType();
1503
1504   SDValue Num = Op.getOperand(0);
1505   SDValue Den = Op.getOperand(1);
1506
1507   if (VT == MVT::i32) {
1508     if (DAG.MaskedValueIsZero(Op.getOperand(0), APInt(32, 0xff << 24)) &&
1509         DAG.MaskedValueIsZero(Op.getOperand(1), APInt(32, 0xff << 24))) {
1510       // TODO: We technically could do this for i64, but shouldn't that just be
1511       // handled by something generally reducing 64-bit division on 32-bit
1512       // values to 32-bit?
1513       return LowerDIVREM24(Op, DAG, false);
1514     }
1515   }
1516
1517   // RCP =  URECIP(Den) = 2^32 / Den + e
1518   // e is rounding error.
1519   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1520
1521   // RCP_LO = mul(RCP, Den) */
1522   SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1523
1524   // RCP_HI = mulhu (RCP, Den) */
1525   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1526
1527   // NEG_RCP_LO = -RCP_LO
1528   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
1529                                                      RCP_LO);
1530
1531   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1532   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1533                                            NEG_RCP_LO, RCP_LO,
1534                                            ISD::SETEQ);
1535   // Calculate the rounding error from the URECIP instruction
1536   // E = mulhu(ABS_RCP_LO, RCP)
1537   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1538
1539   // RCP_A_E = RCP + E
1540   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1541
1542   // RCP_S_E = RCP - E
1543   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1544
1545   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1546   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1547                                      RCP_A_E, RCP_S_E,
1548                                      ISD::SETEQ);
1549   // Quotient = mulhu(Tmp0, Num)
1550   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1551
1552   // Num_S_Remainder = Quotient * Den
1553   SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1554
1555   // Remainder = Num - Num_S_Remainder
1556   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1557
1558   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1559   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1560                                                  DAG.getConstant(-1, VT),
1561                                                  DAG.getConstant(0, VT),
1562                                                  ISD::SETUGE);
1563   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1564   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1565                                                   Num_S_Remainder,
1566                                                   DAG.getConstant(-1, VT),
1567                                                   DAG.getConstant(0, VT),
1568                                                   ISD::SETUGE);
1569   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1570   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1571                                                Remainder_GE_Zero);
1572
1573   // Calculate Division result:
1574
1575   // Quotient_A_One = Quotient + 1
1576   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1577                                                          DAG.getConstant(1, VT));
1578
1579   // Quotient_S_One = Quotient - 1
1580   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1581                                                          DAG.getConstant(1, VT));
1582
1583   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1584   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1585                                      Quotient, Quotient_A_One, ISD::SETEQ);
1586
1587   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1588   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1589                             Quotient_S_One, Div, ISD::SETEQ);
1590
1591   // Calculate Rem result:
1592
1593   // Remainder_S_Den = Remainder - Den
1594   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1595
1596   // Remainder_A_Den = Remainder + Den
1597   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1598
1599   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1600   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1601                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1602
1603   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1604   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1605                             Remainder_A_Den, Rem, ISD::SETEQ);
1606   SDValue Ops[2] = {
1607     Div,
1608     Rem
1609   };
1610   return DAG.getMergeValues(Ops, DL);
1611 }
1612
1613 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1614                                            SelectionDAG &DAG) const {
1615   SDLoc DL(Op);
1616   EVT VT = Op.getValueType();
1617
1618   SDValue LHS = Op.getOperand(0);
1619   SDValue RHS = Op.getOperand(1);
1620
1621   if (VT == MVT::i32) {
1622     if (DAG.ComputeNumSignBits(Op.getOperand(0)) > 8 &&
1623         DAG.ComputeNumSignBits(Op.getOperand(1)) > 8) {
1624       // TODO: We technically could do this for i64, but shouldn't that just be
1625       // handled by something generally reducing 64-bit division on 32-bit
1626       // values to 32-bit?
1627       return LowerDIVREM24(Op, DAG, true);
1628     }
1629   }
1630
1631   SDValue Zero = DAG.getConstant(0, VT);
1632   SDValue NegOne = DAG.getConstant(-1, VT);
1633
1634   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1635   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1636   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1637   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1638
1639   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1640   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1641
1642   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1643   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1644
1645   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1646   SDValue Rem = Div.getValue(1);
1647
1648   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1649   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1650
1651   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1652   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1653
1654   SDValue Res[2] = {
1655     Div,
1656     Rem
1657   };
1658   return DAG.getMergeValues(Res, DL);
1659 }
1660
1661 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
1662 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
1663   SDLoc SL(Op);
1664   EVT VT = Op.getValueType();
1665   SDValue X = Op.getOperand(0);
1666   SDValue Y = Op.getOperand(1);
1667
1668   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
1669   SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
1670   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
1671
1672   return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
1673 }
1674
1675 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1676   SDLoc SL(Op);
1677   SDValue Src = Op.getOperand(0);
1678
1679   // result = trunc(src)
1680   // if (src > 0.0 && src != result)
1681   //   result += 1.0
1682
1683   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1684
1685   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1686   const SDValue One = DAG.getConstantFP(1.0, MVT::f64);
1687
1688   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1689
1690   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1691   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1692   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1693
1694   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1695   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1696 }
1697
1698 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1699   SDLoc SL(Op);
1700   SDValue Src = Op.getOperand(0);
1701
1702   assert(Op.getValueType() == MVT::f64);
1703
1704   const SDValue Zero = DAG.getConstant(0, MVT::i32);
1705   const SDValue One = DAG.getConstant(1, MVT::i32);
1706
1707   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1708
1709   // Extract the upper half, since this is where we will find the sign and
1710   // exponent.
1711   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1712
1713   const unsigned FractBits = 52;
1714   const unsigned ExpBits = 11;
1715
1716   // Extract the exponent.
1717   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_I32, SL, MVT::i32,
1718                                 Hi,
1719                                 DAG.getConstant(FractBits - 32, MVT::i32),
1720                                 DAG.getConstant(ExpBits, MVT::i32));
1721   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1722                             DAG.getConstant(1023, MVT::i32));
1723
1724   // Extract the sign bit.
1725   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, MVT::i32);
1726   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1727
1728   // Extend back to to 64-bits.
1729   SDValue SignBit64 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
1730                                   Zero, SignBit);
1731   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1732
1733   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1734   const SDValue FractMask
1735     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, MVT::i64);
1736
1737   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1738   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1739   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1740
1741   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::i32);
1742
1743   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, MVT::i32);
1744
1745   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1746   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1747
1748   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1749   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
1750
1751   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
1752 }
1753
1754 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
1755   SDLoc SL(Op);
1756   SDValue Src = Op.getOperand(0);
1757
1758   assert(Op.getValueType() == MVT::f64);
1759
1760   APFloat C1Val(APFloat::IEEEdouble, "0x1.0p+52");
1761   SDValue C1 = DAG.getConstantFP(C1Val, MVT::f64);
1762   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
1763
1764   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
1765   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
1766
1767   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
1768
1769   APFloat C2Val(APFloat::IEEEdouble, "0x1.fffffffffffffp+51");
1770   SDValue C2 = DAG.getConstantFP(C2Val, MVT::f64);
1771
1772   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1773   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
1774
1775   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
1776 }
1777
1778 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
1779   // FNEARBYINT and FRINT are the same, except in their handling of FP
1780   // exceptions. Those aren't really meaningful for us, and OpenCL only has
1781   // rint, so just treat them as equivalent.
1782   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
1783 }
1784
1785 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
1786   SDLoc SL(Op);
1787   SDValue Src = Op.getOperand(0);
1788
1789   // result = trunc(src);
1790   // if (src < 0.0 && src != result)
1791   //   result += -1.0.
1792
1793   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1794
1795   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1796   const SDValue NegOne = DAG.getConstantFP(-1.0, MVT::f64);
1797
1798   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1799
1800   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
1801   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1802   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1803
1804   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
1805   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1806 }
1807
1808 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
1809                                                SelectionDAG &DAG) const {
1810   SDValue S0 = Op.getOperand(0);
1811   SDLoc DL(Op);
1812   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
1813     return SDValue();
1814
1815   // f32 uint_to_fp i64
1816   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1817                            DAG.getConstant(0, MVT::i32));
1818   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
1819   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1820                            DAG.getConstant(1, MVT::i32));
1821   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
1822   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
1823                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
1824   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
1825 }
1826
1827 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
1828                                                       unsigned BitsDiff,
1829                                                       SelectionDAG &DAG) const {
1830   MVT VT = Op.getSimpleValueType();
1831   SDLoc DL(Op);
1832   SDValue Shift = DAG.getConstant(BitsDiff, VT);
1833   // Shift left by 'Shift' bits.
1834   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
1835   // Signed shift Right by 'Shift' bits.
1836   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
1837 }
1838
1839 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1840                                                      SelectionDAG &DAG) const {
1841   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1842   MVT VT = Op.getSimpleValueType();
1843   MVT ScalarVT = VT.getScalarType();
1844
1845   if (!VT.isVector())
1846     return SDValue();
1847
1848   SDValue Src = Op.getOperand(0);
1849   SDLoc DL(Op);
1850
1851   // TODO: Don't scalarize on Evergreen?
1852   unsigned NElts = VT.getVectorNumElements();
1853   SmallVector<SDValue, 8> Args;
1854   DAG.ExtractVectorElements(Src, Args, 0, NElts);
1855
1856   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
1857   for (unsigned I = 0; I < NElts; ++I)
1858     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
1859
1860   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);
1861 }
1862
1863 //===----------------------------------------------------------------------===//
1864 // Custom DAG optimizations
1865 //===----------------------------------------------------------------------===//
1866
1867 static bool isU24(SDValue Op, SelectionDAG &DAG) {
1868   APInt KnownZero, KnownOne;
1869   EVT VT = Op.getValueType();
1870   DAG.computeKnownBits(Op, KnownZero, KnownOne);
1871
1872   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
1873 }
1874
1875 static bool isI24(SDValue Op, SelectionDAG &DAG) {
1876   EVT VT = Op.getValueType();
1877
1878   // In order for this to be a signed 24-bit value, bit 23, must
1879   // be a sign bit.
1880   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
1881                                      // as unsigned 24-bit values.
1882          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
1883 }
1884
1885 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
1886
1887   SelectionDAG &DAG = DCI.DAG;
1888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1889   EVT VT = Op.getValueType();
1890
1891   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
1892   APInt KnownZero, KnownOne;
1893   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
1894   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
1895     DCI.CommitTargetLoweringOpt(TLO);
1896 }
1897
1898 template <typename IntTy>
1899 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0,
1900                                uint32_t Offset, uint32_t Width) {
1901   if (Width + Offset < 32) {
1902     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
1903     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
1904     return DAG.getConstant(Result, MVT::i32);
1905   }
1906
1907   return DAG.getConstant(Src0 >> Offset, MVT::i32);
1908 }
1909
1910 static bool usesAllNormalStores(SDNode *LoadVal) {
1911   for (SDNode::use_iterator I = LoadVal->use_begin(); !I.atEnd(); ++I) {
1912     if (!ISD::isNormalStore(*I))
1913       return false;
1914   }
1915
1916   return true;
1917 }
1918
1919 // If we have a copy of an illegal type, replace it with a load / store of an
1920 // equivalently sized legal type. This avoids intermediate bit pack / unpack
1921 // instructions emitted when handling extloads and truncstores. Ideally we could
1922 // recognize the pack / unpack pattern to eliminate it.
1923 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
1924                                                   DAGCombinerInfo &DCI) const {
1925   if (!DCI.isBeforeLegalize())
1926     return SDValue();
1927
1928   StoreSDNode *SN = cast<StoreSDNode>(N);
1929   SDValue Value = SN->getValue();
1930   EVT VT = Value.getValueType();
1931
1932   if (isTypeLegal(VT) || SN->isVolatile() || !ISD::isNormalLoad(Value.getNode()))
1933     return SDValue();
1934
1935   LoadSDNode *LoadVal = cast<LoadSDNode>(Value);
1936   if (LoadVal->isVolatile() || !usesAllNormalStores(LoadVal))
1937     return SDValue();
1938
1939   EVT MemVT = LoadVal->getMemoryVT();
1940
1941   SDLoc SL(N);
1942   SelectionDAG &DAG = DCI.DAG;
1943   EVT LoadVT = getEquivalentMemType(*DAG.getContext(), MemVT);
1944
1945   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
1946                                 LoadVT, SL,
1947                                 LoadVal->getChain(),
1948                                 LoadVal->getBasePtr(),
1949                                 LoadVal->getOffset(),
1950                                 LoadVT,
1951                                 LoadVal->getMemOperand());
1952
1953   SDValue CastLoad = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad.getValue(0));
1954   DCI.CombineTo(LoadVal, CastLoad, NewLoad.getValue(1), false);
1955
1956   return DAG.getStore(SN->getChain(), SL, NewLoad,
1957                       SN->getBasePtr(), SN->getMemOperand());
1958 }
1959
1960 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
1961                                                 DAGCombinerInfo &DCI) const {
1962   EVT VT = N->getValueType(0);
1963
1964   if (VT.isVector() || VT.getSizeInBits() > 32)
1965     return SDValue();
1966
1967   SelectionDAG &DAG = DCI.DAG;
1968   SDLoc DL(N);
1969
1970   SDValue N0 = N->getOperand(0);
1971   SDValue N1 = N->getOperand(1);
1972   SDValue Mul;
1973
1974   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
1975     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
1976     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
1977     Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
1978   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
1979     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
1980     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
1981     Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
1982   } else {
1983     return SDValue();
1984   }
1985
1986   // We need to use sext even for MUL_U24, because MUL_U24 is used
1987   // for signed multiply of 8 and 16-bit types.
1988   return DAG.getSExtOrTrunc(Mul, DL, VT);
1989 }
1990
1991 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
1992                                                 DAGCombinerInfo &DCI) const {
1993   SelectionDAG &DAG = DCI.DAG;
1994   SDLoc DL(N);
1995
1996   switch(N->getOpcode()) {
1997     default: break;
1998     case ISD::MUL:
1999       return performMulCombine(N, DCI);
2000     case AMDGPUISD::MUL_I24:
2001     case AMDGPUISD::MUL_U24: {
2002       SDValue N0 = N->getOperand(0);
2003       SDValue N1 = N->getOperand(1);
2004       simplifyI24(N0, DCI);
2005       simplifyI24(N1, DCI);
2006       return SDValue();
2007     }
2008     case ISD::SELECT_CC: {
2009       return CombineMinMax(N, DAG);
2010     }
2011   case AMDGPUISD::BFE_I32:
2012   case AMDGPUISD::BFE_U32: {
2013     assert(!N->getValueType(0).isVector() &&
2014            "Vector handling of BFE not implemented");
2015     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
2016     if (!Width)
2017       break;
2018
2019     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
2020     if (WidthVal == 0)
2021       return DAG.getConstant(0, MVT::i32);
2022
2023     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2024     if (!Offset)
2025       break;
2026
2027     SDValue BitsFrom = N->getOperand(0);
2028     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
2029
2030     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
2031
2032     if (OffsetVal == 0) {
2033       // This is already sign / zero extended, so try to fold away extra BFEs.
2034       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
2035
2036       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
2037       if (OpSignBits >= SignBits)
2038         return BitsFrom;
2039
2040       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
2041       if (Signed) {
2042         // This is a sign_extend_inreg. Replace it to take advantage of existing
2043         // DAG Combines. If not eliminated, we will match back to BFE during
2044         // selection.
2045
2046         // TODO: The sext_inreg of extended types ends, although we can could
2047         // handle them in a single BFE.
2048         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
2049                            DAG.getValueType(SmallVT));
2050       }
2051
2052       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
2053     }
2054
2055     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
2056       if (Signed) {
2057         // Avoid undefined left shift of a negative in the constant fold.
2058         // TODO: I'm not sure what the behavior of the hardware is, this should
2059         // probably follow that instead.
2060         return constantFoldBFE<int32_t>(DAG,
2061                                         CVal->getSExtValue(),
2062                                         OffsetVal,
2063                                         WidthVal);
2064       }
2065
2066       return constantFoldBFE<uint32_t>(DAG,
2067                                        CVal->getZExtValue(),
2068                                        OffsetVal,
2069                                        WidthVal);
2070     }
2071
2072     APInt Demanded = APInt::getBitsSet(32,
2073                                        OffsetVal,
2074                                        OffsetVal + WidthVal);
2075
2076     if ((OffsetVal + WidthVal) >= 32) {
2077       SDValue ShiftVal = DAG.getConstant(OffsetVal, MVT::i32);
2078       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2079                          BitsFrom, ShiftVal);
2080     }
2081
2082     APInt KnownZero, KnownOne;
2083     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2084                                           !DCI.isBeforeLegalizeOps());
2085     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2086     if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
2087         TLI.SimplifyDemandedBits(BitsFrom, Demanded, KnownZero, KnownOne, TLO)) {
2088       DCI.CommitTargetLoweringOpt(TLO);
2089     }
2090
2091     break;
2092   }
2093
2094   case ISD::STORE:
2095     return performStoreCombine(N, DCI);
2096   }
2097   return SDValue();
2098 }
2099
2100 //===----------------------------------------------------------------------===//
2101 // Helper functions
2102 //===----------------------------------------------------------------------===//
2103
2104 void AMDGPUTargetLowering::getOriginalFunctionArgs(
2105                                SelectionDAG &DAG,
2106                                const Function *F,
2107                                const SmallVectorImpl<ISD::InputArg> &Ins,
2108                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
2109
2110   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
2111     if (Ins[i].ArgVT == Ins[i].VT) {
2112       OrigIns.push_back(Ins[i]);
2113       continue;
2114     }
2115
2116     EVT VT;
2117     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
2118       // Vector has been split into scalars.
2119       VT = Ins[i].ArgVT.getVectorElementType();
2120     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
2121                Ins[i].ArgVT.getVectorElementType() !=
2122                Ins[i].VT.getVectorElementType()) {
2123       // Vector elements have been promoted
2124       VT = Ins[i].ArgVT;
2125     } else {
2126       // Vector has been spilt into smaller vectors.
2127       VT = Ins[i].VT;
2128     }
2129
2130     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
2131                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
2132     OrigIns.push_back(Arg);
2133   }
2134 }
2135
2136 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
2137   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2138     return CFP->isExactlyValue(1.0);
2139   }
2140   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2141     return C->isAllOnesValue();
2142   }
2143   return false;
2144 }
2145
2146 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
2147   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2148     return CFP->getValueAPF().isZero();
2149   }
2150   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2151     return C->isNullValue();
2152   }
2153   return false;
2154 }
2155
2156 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2157                                                   const TargetRegisterClass *RC,
2158                                                    unsigned Reg, EVT VT) const {
2159   MachineFunction &MF = DAG.getMachineFunction();
2160   MachineRegisterInfo &MRI = MF.getRegInfo();
2161   unsigned VirtualRegister;
2162   if (!MRI.isLiveIn(Reg)) {
2163     VirtualRegister = MRI.createVirtualRegister(RC);
2164     MRI.addLiveIn(Reg, VirtualRegister);
2165   } else {
2166     VirtualRegister = MRI.getLiveInVirtReg(Reg);
2167   }
2168   return DAG.getRegister(VirtualRegister, VT);
2169 }
2170
2171 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
2172
2173 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
2174   switch (Opcode) {
2175   default: return nullptr;
2176   // AMDIL DAG nodes
2177   NODE_NAME_CASE(CALL);
2178   NODE_NAME_CASE(UMUL);
2179   NODE_NAME_CASE(RET_FLAG);
2180   NODE_NAME_CASE(BRANCH_COND);
2181
2182   // AMDGPU DAG nodes
2183   NODE_NAME_CASE(DWORDADDR)
2184   NODE_NAME_CASE(FRACT)
2185   NODE_NAME_CASE(CLAMP)
2186   NODE_NAME_CASE(MAD)
2187   NODE_NAME_CASE(FMAX)
2188   NODE_NAME_CASE(SMAX)
2189   NODE_NAME_CASE(UMAX)
2190   NODE_NAME_CASE(FMIN)
2191   NODE_NAME_CASE(SMIN)
2192   NODE_NAME_CASE(UMIN)
2193   NODE_NAME_CASE(URECIP)
2194   NODE_NAME_CASE(DIV_SCALE)
2195   NODE_NAME_CASE(DIV_FMAS)
2196   NODE_NAME_CASE(DIV_FIXUP)
2197   NODE_NAME_CASE(TRIG_PREOP)
2198   NODE_NAME_CASE(RCP)
2199   NODE_NAME_CASE(RSQ)
2200   NODE_NAME_CASE(RSQ_LEGACY)
2201   NODE_NAME_CASE(RSQ_CLAMPED)
2202   NODE_NAME_CASE(LDEXP)
2203   NODE_NAME_CASE(DOT4)
2204   NODE_NAME_CASE(BFE_U32)
2205   NODE_NAME_CASE(BFE_I32)
2206   NODE_NAME_CASE(BFI)
2207   NODE_NAME_CASE(BFM)
2208   NODE_NAME_CASE(BREV)
2209   NODE_NAME_CASE(MUL_U24)
2210   NODE_NAME_CASE(MUL_I24)
2211   NODE_NAME_CASE(MAD_U24)
2212   NODE_NAME_CASE(MAD_I24)
2213   NODE_NAME_CASE(EXPORT)
2214   NODE_NAME_CASE(CONST_ADDRESS)
2215   NODE_NAME_CASE(REGISTER_LOAD)
2216   NODE_NAME_CASE(REGISTER_STORE)
2217   NODE_NAME_CASE(LOAD_CONSTANT)
2218   NODE_NAME_CASE(LOAD_INPUT)
2219   NODE_NAME_CASE(SAMPLE)
2220   NODE_NAME_CASE(SAMPLEB)
2221   NODE_NAME_CASE(SAMPLED)
2222   NODE_NAME_CASE(SAMPLEL)
2223   NODE_NAME_CASE(CVT_F32_UBYTE0)
2224   NODE_NAME_CASE(CVT_F32_UBYTE1)
2225   NODE_NAME_CASE(CVT_F32_UBYTE2)
2226   NODE_NAME_CASE(CVT_F32_UBYTE3)
2227   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
2228   NODE_NAME_CASE(CONST_DATA_PTR)
2229   NODE_NAME_CASE(STORE_MSKOR)
2230   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
2231   }
2232 }
2233
2234 static void computeKnownBitsForMinMax(const SDValue Op0,
2235                                       const SDValue Op1,
2236                                       APInt &KnownZero,
2237                                       APInt &KnownOne,
2238                                       const SelectionDAG &DAG,
2239                                       unsigned Depth) {
2240   APInt Op0Zero, Op0One;
2241   APInt Op1Zero, Op1One;
2242   DAG.computeKnownBits(Op0, Op0Zero, Op0One, Depth);
2243   DAG.computeKnownBits(Op1, Op1Zero, Op1One, Depth);
2244
2245   KnownZero = Op0Zero & Op1Zero;
2246   KnownOne = Op0One & Op1One;
2247 }
2248
2249 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
2250   const SDValue Op,
2251   APInt &KnownZero,
2252   APInt &KnownOne,
2253   const SelectionDAG &DAG,
2254   unsigned Depth) const {
2255
2256   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
2257
2258   APInt KnownZero2;
2259   APInt KnownOne2;
2260   unsigned Opc = Op.getOpcode();
2261
2262   switch (Opc) {
2263   default:
2264     break;
2265   case ISD::INTRINSIC_WO_CHAIN: {
2266     // FIXME: The intrinsic should just use the node.
2267     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
2268     case AMDGPUIntrinsic::AMDGPU_imax:
2269     case AMDGPUIntrinsic::AMDGPU_umax:
2270     case AMDGPUIntrinsic::AMDGPU_imin:
2271     case AMDGPUIntrinsic::AMDGPU_umin:
2272       computeKnownBitsForMinMax(Op.getOperand(1), Op.getOperand(2),
2273                                 KnownZero, KnownOne, DAG, Depth);
2274       break;
2275     default:
2276       break;
2277     }
2278
2279     break;
2280   }
2281   case AMDGPUISD::SMAX:
2282   case AMDGPUISD::UMAX:
2283   case AMDGPUISD::SMIN:
2284   case AMDGPUISD::UMIN:
2285     computeKnownBitsForMinMax(Op.getOperand(0), Op.getOperand(1),
2286                               KnownZero, KnownOne, DAG, Depth);
2287     break;
2288
2289   case AMDGPUISD::BFE_I32:
2290   case AMDGPUISD::BFE_U32: {
2291     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2292     if (!CWidth)
2293       return;
2294
2295     unsigned BitWidth = 32;
2296     uint32_t Width = CWidth->getZExtValue() & 0x1f;
2297     if (Width == 0) {
2298       KnownZero = APInt::getAllOnesValue(BitWidth);
2299       KnownOne = APInt::getNullValue(BitWidth);
2300       return;
2301     }
2302
2303     // FIXME: This could do a lot more. If offset is 0, should be the same as
2304     // sign_extend_inreg implementation, but that involves duplicating it.
2305     if (Opc == AMDGPUISD::BFE_I32)
2306       KnownOne = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2307     else
2308       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2309
2310     break;
2311   }
2312   }
2313 }
2314
2315 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
2316   SDValue Op,
2317   const SelectionDAG &DAG,
2318   unsigned Depth) const {
2319   switch (Op.getOpcode()) {
2320   case AMDGPUISD::BFE_I32: {
2321     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2322     if (!Width)
2323       return 1;
2324
2325     unsigned SignBits = 32 - Width->getZExtValue() + 1;
2326     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2327     if (!Offset || !Offset->isNullValue())
2328       return SignBits;
2329
2330     // TODO: Could probably figure something out with non-0 offsets.
2331     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2332     return std::max(SignBits, Op0SignBits);
2333   }
2334
2335   case AMDGPUISD::BFE_U32: {
2336     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2337     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
2338   }
2339
2340   default:
2341     return 1;
2342   }
2343 }