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