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