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