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