64636de959b44b4d2ba33818e0cef6808109ec97
[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   case ISD::LOAD: {
558     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
559     if (!Node)
560       return;
561
562     Results.push_back(SDValue(Node, 0));
563     Results.push_back(SDValue(Node, 1));
564     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
565     // function
566     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
567     return;
568   }
569   case ISD::STORE: {
570     SDValue Lowered = LowerSTORE(SDValue(N, 0), DAG);
571     if (Lowered.getNode())
572       Results.push_back(Lowered);
573     return;
574   }
575   default:
576     return;
577   }
578 }
579
580 // FIXME: This implements accesses to initialized globals in the constant
581 // address space by copying them to private and accessing that. It does not
582 // properly handle illegal types or vectors. The private vector loads are not
583 // scalarized, and the illegal scalars hit an assertion. This technique will not
584 // work well with large initializers, and this should eventually be
585 // removed. Initialized globals should be placed into a data section that the
586 // runtime will load into a buffer before the kernel is executed. Uses of the
587 // global need to be replaced with a pointer loaded from an implicit kernel
588 // argument into this buffer holding the copy of the data, which will remove the
589 // need for any of this.
590 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
591                                                        const GlobalValue *GV,
592                                                        const SDValue &InitPtr,
593                                                        SDValue Chain,
594                                                        SelectionDAG &DAG) const {
595   const DataLayout *TD = getTargetMachine().getDataLayout();
596   SDLoc DL(InitPtr);
597   Type *InitTy = Init->getType();
598
599   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
600     EVT VT = EVT::getEVT(InitTy);
601     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
602     return DAG.getStore(Chain, DL, DAG.getConstant(*CI, VT), InitPtr,
603                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
604                         TD->getPrefTypeAlignment(InitTy));
605   }
606
607   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
608     EVT VT = EVT::getEVT(CFP->getType());
609     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
610     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
611                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
612                  TD->getPrefTypeAlignment(CFP->getType()));
613   }
614
615   if (StructType *ST = dyn_cast<StructType>(InitTy)) {
616     const StructLayout *SL = TD->getStructLayout(ST);
617
618     EVT PtrVT = InitPtr.getValueType();
619     SmallVector<SDValue, 8> Chains;
620
621     for (unsigned I = 0, N = ST->getNumElements(); I != N; ++I) {
622       SDValue Offset = DAG.getConstant(SL->getElementOffset(I), PtrVT);
623       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
624
625       Constant *Elt = Init->getAggregateElement(I);
626       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
627     }
628
629     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
630   }
631
632   if (SequentialType *SeqTy = dyn_cast<SequentialType>(InitTy)) {
633     EVT PtrVT = InitPtr.getValueType();
634
635     unsigned NumElements;
636     if (ArrayType *AT = dyn_cast<ArrayType>(SeqTy))
637       NumElements = AT->getNumElements();
638     else if (VectorType *VT = dyn_cast<VectorType>(SeqTy))
639       NumElements = VT->getNumElements();
640     else
641       llvm_unreachable("Unexpected type");
642
643     unsigned EltSize = TD->getTypeAllocSize(SeqTy->getElementType());
644     SmallVector<SDValue, 8> Chains;
645     for (unsigned i = 0; i < NumElements; ++i) {
646       SDValue Offset = DAG.getConstant(i * EltSize, PtrVT);
647       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
648
649       Constant *Elt = Init->getAggregateElement(i);
650       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
651     }
652
653     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
654   }
655
656   if (isa<UndefValue>(Init)) {
657     EVT VT = EVT::getEVT(InitTy);
658     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
659     return DAG.getStore(Chain, DL, DAG.getUNDEF(VT), InitPtr,
660                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
661                         TD->getPrefTypeAlignment(InitTy));
662   }
663
664   Init->dump();
665   llvm_unreachable("Unhandled constant initializer");
666 }
667
668 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
669                                                  SDValue Op,
670                                                  SelectionDAG &DAG) const {
671
672   const DataLayout *TD = getTargetMachine().getDataLayout();
673   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
674   const GlobalValue *GV = G->getGlobal();
675
676   switch (G->getAddressSpace()) {
677   default: llvm_unreachable("Global Address lowering not implemented for this "
678                             "address space");
679   case AMDGPUAS::LOCAL_ADDRESS: {
680     // XXX: What does the value of G->getOffset() mean?
681     assert(G->getOffset() == 0 &&
682          "Do not know what to do with an non-zero offset");
683
684     unsigned Offset;
685     if (MFI->LocalMemoryObjects.count(GV) == 0) {
686       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
687       Offset = MFI->LDSSize;
688       MFI->LocalMemoryObjects[GV] = Offset;
689       // XXX: Account for alignment?
690       MFI->LDSSize += Size;
691     } else {
692       Offset = MFI->LocalMemoryObjects[GV];
693     }
694
695     return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
696   }
697   case AMDGPUAS::CONSTANT_ADDRESS: {
698     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
699     Type *EltType = GV->getType()->getElementType();
700     unsigned Size = TD->getTypeAllocSize(EltType);
701     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
702
703     MVT PrivPtrVT = getPointerTy(AMDGPUAS::PRIVATE_ADDRESS);
704     MVT ConstPtrVT = getPointerTy(AMDGPUAS::CONSTANT_ADDRESS);
705
706     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
707     SDValue InitPtr = DAG.getFrameIndex(FI, PrivPtrVT);
708
709     const GlobalVariable *Var = cast<GlobalVariable>(GV);
710     if (!Var->hasInitializer()) {
711       // This has no use, but bugpoint will hit it.
712       return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
713     }
714
715     const Constant *Init = Var->getInitializer();
716     SmallVector<SDNode*, 8> WorkList;
717
718     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
719                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
720       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
721         continue;
722       WorkList.push_back(*I);
723     }
724     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
725     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
726                                            E = WorkList.end(); I != E; ++I) {
727       SmallVector<SDValue, 8> Ops;
728       Ops.push_back(Chain);
729       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
730         Ops.push_back((*I)->getOperand(i));
731       }
732       DAG.UpdateNodeOperands(*I, Ops);
733     }
734     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
735   }
736   }
737 }
738
739 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
740                                                   SelectionDAG &DAG) const {
741   SmallVector<SDValue, 8> Args;
742   SDValue A = Op.getOperand(0);
743   SDValue B = Op.getOperand(1);
744
745   DAG.ExtractVectorElements(A, Args);
746   DAG.ExtractVectorElements(B, Args);
747
748   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
749 }
750
751 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
752                                                      SelectionDAG &DAG) const {
753
754   SmallVector<SDValue, 8> Args;
755   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
756   EVT VT = Op.getValueType();
757   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
758                             VT.getVectorNumElements());
759
760   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
761 }
762
763 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
764                                               SelectionDAG &DAG) const {
765
766   MachineFunction &MF = DAG.getMachineFunction();
767   const AMDGPUFrameLowering *TFL =
768    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
769
770   FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op);
771
772   unsigned FrameIndex = FIN->getIndex();
773   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
774   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
775                          Op.getValueType());
776 }
777
778 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
779     SelectionDAG &DAG) const {
780   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
781   SDLoc DL(Op);
782   EVT VT = Op.getValueType();
783
784   switch (IntrinsicID) {
785     default: return Op;
786     case AMDGPUIntrinsic::AMDGPU_abs:
787     case AMDGPUIntrinsic::AMDIL_abs: // Legacy name.
788       return LowerIntrinsicIABS(Op, DAG);
789     case AMDGPUIntrinsic::AMDGPU_lrp:
790       return LowerIntrinsicLRP(Op, DAG);
791     case AMDGPUIntrinsic::AMDGPU_fract:
792     case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
793       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
794
795     case AMDGPUIntrinsic::AMDGPU_clamp:
796     case AMDGPUIntrinsic::AMDIL_clamp: // Legacy name.
797       return DAG.getNode(AMDGPUISD::CLAMP, DL, VT,
798                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
799
800     case Intrinsic::AMDGPU_div_scale: {
801       // 3rd parameter required to be a constant.
802       const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
803       if (!Param)
804         return DAG.getUNDEF(VT);
805
806       // Translate to the operands expected by the machine instruction. The
807       // first parameter must be the same as the first instruction.
808       SDValue Numerator = Op.getOperand(1);
809       SDValue Denominator = Op.getOperand(2);
810       SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
811
812       return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, VT,
813                          Src0, Denominator, Numerator);
814     }
815
816     case Intrinsic::AMDGPU_div_fmas:
817       return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
818                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
819
820     case Intrinsic::AMDGPU_div_fixup:
821       return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
822                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
823
824     case Intrinsic::AMDGPU_trig_preop:
825       return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
826                          Op.getOperand(1), Op.getOperand(2));
827
828     case Intrinsic::AMDGPU_rcp:
829       return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
830
831     case Intrinsic::AMDGPU_rsq:
832       return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
833
834     case AMDGPUIntrinsic::AMDGPU_legacy_rsq:
835       return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
836
837     case Intrinsic::AMDGPU_rsq_clamped:
838       return DAG.getNode(AMDGPUISD::RSQ_CLAMPED, DL, VT, Op.getOperand(1));
839
840     case AMDGPUIntrinsic::AMDGPU_imax:
841       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
842                                                   Op.getOperand(2));
843     case AMDGPUIntrinsic::AMDGPU_umax:
844       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
845                                                   Op.getOperand(2));
846     case AMDGPUIntrinsic::AMDGPU_imin:
847       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
848                                                   Op.getOperand(2));
849     case AMDGPUIntrinsic::AMDGPU_umin:
850       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
851                                                   Op.getOperand(2));
852
853     case AMDGPUIntrinsic::AMDGPU_umul24:
854       return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT,
855                          Op.getOperand(1), Op.getOperand(2));
856
857     case AMDGPUIntrinsic::AMDGPU_imul24:
858       return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT,
859                          Op.getOperand(1), Op.getOperand(2));
860
861     case AMDGPUIntrinsic::AMDGPU_umad24:
862       return DAG.getNode(AMDGPUISD::MAD_U24, DL, VT,
863                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
864
865     case AMDGPUIntrinsic::AMDGPU_imad24:
866       return DAG.getNode(AMDGPUISD::MAD_I24, DL, VT,
867                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
868
869     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0:
870       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1));
871
872     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1:
873       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1));
874
875     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2:
876       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1));
877
878     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3:
879       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1));
880
881     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
882       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
883                          Op.getOperand(1),
884                          Op.getOperand(2),
885                          Op.getOperand(3));
886
887     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
888       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
889                          Op.getOperand(1),
890                          Op.getOperand(2),
891                          Op.getOperand(3));
892
893     case AMDGPUIntrinsic::AMDGPU_bfi:
894       return DAG.getNode(AMDGPUISD::BFI, DL, VT,
895                          Op.getOperand(1),
896                          Op.getOperand(2),
897                          Op.getOperand(3));
898
899     case AMDGPUIntrinsic::AMDGPU_bfm:
900       return DAG.getNode(AMDGPUISD::BFM, DL, VT,
901                          Op.getOperand(1),
902                          Op.getOperand(2));
903
904     case AMDGPUIntrinsic::AMDGPU_brev:
905       return DAG.getNode(AMDGPUISD::BREV, DL, VT, Op.getOperand(1));
906
907     case AMDGPUIntrinsic::AMDIL_exp: // Legacy name.
908       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
909
910     case AMDGPUIntrinsic::AMDIL_round_nearest: // Legacy name.
911       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
912     case AMDGPUIntrinsic::AMDGPU_trunc:
913       return DAG.getNode(ISD::FTRUNC, DL, VT, Op.getOperand(1));
914   }
915 }
916
917 ///IABS(a) = SMAX(sub(0, a), a)
918 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
919                                                  SelectionDAG &DAG) const {
920   SDLoc DL(Op);
921   EVT VT = Op.getValueType();
922   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
923                                               Op.getOperand(1));
924
925   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
926 }
927
928 /// Linear Interpolation
929 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
930 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
931                                                 SelectionDAG &DAG) const {
932   SDLoc DL(Op);
933   EVT VT = Op.getValueType();
934   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
935                                 DAG.getConstantFP(1.0f, MVT::f32),
936                                 Op.getOperand(1));
937   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
938                                                     Op.getOperand(3));
939   return DAG.getNode(ISD::FADD, DL, VT,
940       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
941       OneSubAC);
942 }
943
944 /// \brief Generate Min/Max node
945 SDValue AMDGPUTargetLowering::CombineMinMax(SDNode *N,
946                                             SelectionDAG &DAG) const {
947   SDLoc DL(N);
948   EVT VT = N->getValueType(0);
949
950   SDValue LHS = N->getOperand(0);
951   SDValue RHS = N->getOperand(1);
952   SDValue True = N->getOperand(2);
953   SDValue False = N->getOperand(3);
954   SDValue CC = N->getOperand(4);
955
956   if (VT != MVT::f32 ||
957       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
958     return SDValue();
959   }
960
961   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
962   switch (CCOpcode) {
963   case ISD::SETOEQ:
964   case ISD::SETONE:
965   case ISD::SETUNE:
966   case ISD::SETNE:
967   case ISD::SETUEQ:
968   case ISD::SETEQ:
969   case ISD::SETFALSE:
970   case ISD::SETFALSE2:
971   case ISD::SETTRUE:
972   case ISD::SETTRUE2:
973   case ISD::SETUO:
974   case ISD::SETO:
975     llvm_unreachable("Operation should already be optimised!");
976   case ISD::SETULE:
977   case ISD::SETULT:
978   case ISD::SETOLE:
979   case ISD::SETOLT:
980   case ISD::SETLE:
981   case ISD::SETLT: {
982     unsigned Opc = (LHS == True) ? AMDGPUISD::FMIN : AMDGPUISD::FMAX;
983     return DAG.getNode(Opc, DL, VT, LHS, RHS);
984   }
985   case ISD::SETGT:
986   case ISD::SETGE:
987   case ISD::SETUGE:
988   case ISD::SETOGE:
989   case ISD::SETUGT:
990   case ISD::SETOGT: {
991     unsigned Opc = (LHS == True) ? AMDGPUISD::FMAX : AMDGPUISD::FMIN;
992     return DAG.getNode(Opc, DL, VT, LHS, RHS);
993   }
994   case ISD::SETCC_INVALID:
995     llvm_unreachable("Invalid setcc condcode!");
996   }
997   return SDValue();
998 }
999
1000 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
1001                                               SelectionDAG &DAG) const {
1002   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
1003   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
1004   EVT EltVT = Op.getValueType().getVectorElementType();
1005   EVT PtrVT = Load->getBasePtr().getValueType();
1006   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
1007   SmallVector<SDValue, 8> Loads;
1008   SDLoc SL(Op);
1009
1010   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1011     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
1012                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
1013     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
1014                         Load->getChain(), Ptr,
1015                         MachinePointerInfo(Load->getMemOperand()->getValue()),
1016                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
1017                         Load->getAlignment()));
1018   }
1019   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(), Loads);
1020 }
1021
1022 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
1023                                                SelectionDAG &DAG) const {
1024   StoreSDNode *Store = cast<StoreSDNode>(Op);
1025   EVT MemVT = Store->getMemoryVT();
1026   unsigned MemBits = MemVT.getSizeInBits();
1027
1028   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
1029   // truncating store into an i32 store.
1030   // XXX: We could also handle optimize other vector bitwidths.
1031   if (!MemVT.isVector() || MemBits > 32) {
1032     return SDValue();
1033   }
1034
1035   SDLoc DL(Op);
1036   SDValue Value = Store->getValue();
1037   EVT VT = Value.getValueType();
1038   EVT ElemVT = VT.getVectorElementType();
1039   SDValue Ptr = Store->getBasePtr();
1040   EVT MemEltVT = MemVT.getVectorElementType();
1041   unsigned MemEltBits = MemEltVT.getSizeInBits();
1042   unsigned MemNumElements = MemVT.getVectorNumElements();
1043   unsigned PackedSize = MemVT.getStoreSizeInBits();
1044   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, MVT::i32);
1045
1046   assert(Value.getValueType().getScalarSizeInBits() >= 32);
1047
1048   SDValue PackedValue;
1049   for (unsigned i = 0; i < MemNumElements; ++i) {
1050     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
1051                               DAG.getConstant(i, MVT::i32));
1052     Elt = DAG.getZExtOrTrunc(Elt, DL, MVT::i32);
1053     Elt = DAG.getNode(ISD::AND, DL, MVT::i32, Elt, Mask); // getZeroExtendInReg
1054
1055     SDValue Shift = DAG.getConstant(MemEltBits * i, MVT::i32);
1056     Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt, Shift);
1057
1058     if (i == 0) {
1059       PackedValue = Elt;
1060     } else {
1061       PackedValue = DAG.getNode(ISD::OR, DL, MVT::i32, PackedValue, Elt);
1062     }
1063   }
1064
1065   if (PackedSize < 32) {
1066     EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), PackedSize);
1067     return DAG.getTruncStore(Store->getChain(), DL, PackedValue, Ptr,
1068                              Store->getMemOperand()->getPointerInfo(),
1069                              PackedVT,
1070                              Store->isNonTemporal(), Store->isVolatile(),
1071                              Store->getAlignment());
1072   }
1073
1074   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
1075                       Store->getMemOperand()->getPointerInfo(),
1076                       Store->isVolatile(),  Store->isNonTemporal(),
1077                       Store->getAlignment());
1078 }
1079
1080 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1081                                             SelectionDAG &DAG) const {
1082   StoreSDNode *Store = cast<StoreSDNode>(Op);
1083   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
1084   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
1085   EVT PtrVT = Store->getBasePtr().getValueType();
1086   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
1087   SDLoc SL(Op);
1088
1089   SmallVector<SDValue, 8> Chains;
1090
1091   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1092     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
1093                               Store->getValue(), DAG.getConstant(i, MVT::i32));
1094     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
1095                               Store->getBasePtr(),
1096                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
1097                                             PtrVT));
1098     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
1099                          MachinePointerInfo(Store->getMemOperand()->getValue()),
1100                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
1101                          Store->getAlignment()));
1102   }
1103   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains);
1104 }
1105
1106 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1107   SDLoc DL(Op);
1108   LoadSDNode *Load = cast<LoadSDNode>(Op);
1109   ISD::LoadExtType ExtType = Load->getExtensionType();
1110   EVT VT = Op.getValueType();
1111   EVT MemVT = Load->getMemoryVT();
1112
1113   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
1114     // We can do the extload to 32-bits, and then need to separately extend to
1115     // 64-bits.
1116
1117     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
1118                                        Load->getChain(),
1119                                        Load->getBasePtr(),
1120                                        MemVT,
1121                                        Load->getMemOperand());
1122     return DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32);
1123   }
1124
1125   if (ExtType == ISD::NON_EXTLOAD && VT.getSizeInBits() < 32) {
1126     assert(VT == MVT::i1 && "Only i1 non-extloads expected");
1127     // FIXME: Copied from PPC
1128     // First, load into 32 bits, then truncate to 1 bit.
1129
1130     SDValue Chain = Load->getChain();
1131     SDValue BasePtr = Load->getBasePtr();
1132     MachineMemOperand *MMO = Load->getMemOperand();
1133
1134     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1135                                    BasePtr, MVT::i8, MMO);
1136     return DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1137   }
1138
1139   // Lower loads constant address space global variable loads
1140   if (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
1141       isa<GlobalVariable>(
1142           GetUnderlyingObject(Load->getMemOperand()->getValue()))) {
1143
1144     SDValue Ptr = DAG.getZExtOrTrunc(Load->getBasePtr(), DL,
1145         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
1146     Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr,
1147         DAG.getConstant(2, MVT::i32));
1148     return DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1149                        Load->getChain(), Ptr,
1150                        DAG.getTargetConstant(0, MVT::i32), Op.getOperand(2));
1151   }
1152
1153   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
1154       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
1155     return SDValue();
1156
1157
1158   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
1159                             DAG.getConstant(2, MVT::i32));
1160   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1161                             Load->getChain(), Ptr,
1162                             DAG.getTargetConstant(0, MVT::i32),
1163                             Op.getOperand(2));
1164   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
1165                                 Load->getBasePtr(),
1166                                 DAG.getConstant(0x3, MVT::i32));
1167   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1168                                  DAG.getConstant(3, MVT::i32));
1169
1170   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
1171
1172   EVT MemEltVT = MemVT.getScalarType();
1173   if (ExtType == ISD::SEXTLOAD) {
1174     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
1175     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode);
1176   }
1177
1178   return DAG.getZeroExtendInReg(Ret, DL, MemEltVT);
1179 }
1180
1181 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1182   SDLoc DL(Op);
1183   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
1184   if (Result.getNode()) {
1185     return Result;
1186   }
1187
1188   StoreSDNode *Store = cast<StoreSDNode>(Op);
1189   SDValue Chain = Store->getChain();
1190   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1191        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
1192       Store->getValue().getValueType().isVector()) {
1193     return SplitVectorStore(Op, DAG);
1194   }
1195
1196   EVT MemVT = Store->getMemoryVT();
1197   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
1198       MemVT.bitsLT(MVT::i32)) {
1199     unsigned Mask = 0;
1200     if (Store->getMemoryVT() == MVT::i8) {
1201       Mask = 0xff;
1202     } else if (Store->getMemoryVT() == MVT::i16) {
1203       Mask = 0xffff;
1204     }
1205     SDValue BasePtr = Store->getBasePtr();
1206     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
1207                               DAG.getConstant(2, MVT::i32));
1208     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
1209                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
1210
1211     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
1212                                   DAG.getConstant(0x3, MVT::i32));
1213
1214     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1215                                    DAG.getConstant(3, MVT::i32));
1216
1217     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
1218                                     Store->getValue());
1219
1220     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
1221
1222     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1223                                        MaskedValue, ShiftAmt);
1224
1225     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
1226                                   ShiftAmt);
1227     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
1228                           DAG.getConstant(0xffffffff, MVT::i32));
1229     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1230
1231     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1232     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1233                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
1234   }
1235   return SDValue();
1236 }
1237
1238 SDValue AMDGPUTargetLowering::LowerSDIV24(SDValue Op, SelectionDAG &DAG) const {
1239   SDLoc DL(Op);
1240   EVT OVT = Op.getValueType();
1241   SDValue LHS = Op.getOperand(0);
1242   SDValue RHS = Op.getOperand(1);
1243   MVT INTTY;
1244   MVT FLTTY;
1245   if (!OVT.isVector()) {
1246     INTTY = MVT::i32;
1247     FLTTY = MVT::f32;
1248   } else if (OVT.getVectorNumElements() == 2) {
1249     INTTY = MVT::v2i32;
1250     FLTTY = MVT::v2f32;
1251   } else if (OVT.getVectorNumElements() == 4) {
1252     INTTY = MVT::v4i32;
1253     FLTTY = MVT::v4f32;
1254   }
1255   unsigned bitsize = OVT.getScalarType().getSizeInBits();
1256   // char|short jq = ia ^ ib;
1257   SDValue jq = DAG.getNode(ISD::XOR, DL, OVT, LHS, RHS);
1258
1259   // jq = jq >> (bitsize - 2)
1260   jq = DAG.getNode(ISD::SRA, DL, OVT, jq, DAG.getConstant(bitsize - 2, OVT));
1261
1262   // jq = jq | 0x1
1263   jq = DAG.getNode(ISD::OR, DL, OVT, jq, DAG.getConstant(1, OVT));
1264
1265   // jq = (int)jq
1266   jq = DAG.getSExtOrTrunc(jq, DL, INTTY);
1267
1268   // int ia = (int)LHS;
1269   SDValue ia = DAG.getSExtOrTrunc(LHS, DL, INTTY);
1270
1271   // int ib, (int)RHS;
1272   SDValue ib = DAG.getSExtOrTrunc(RHS, DL, INTTY);
1273
1274   // float fa = (float)ia;
1275   SDValue fa = DAG.getNode(ISD::SINT_TO_FP, DL, FLTTY, ia);
1276
1277   // float fb = (float)ib;
1278   SDValue fb = DAG.getNode(ISD::SINT_TO_FP, DL, FLTTY, ib);
1279
1280   // float fq = native_divide(fa, fb);
1281   SDValue fq = DAG.getNode(ISD::FMUL, DL, FLTTY,
1282                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FLTTY, fb));
1283
1284   // fq = trunc(fq);
1285   fq = DAG.getNode(ISD::FTRUNC, DL, FLTTY, fq);
1286
1287   // float fqneg = -fq;
1288   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FLTTY, fq);
1289
1290   // float fr = mad(fqneg, fb, fa);
1291   SDValue fr = DAG.getNode(ISD::FADD, DL, FLTTY,
1292       DAG.getNode(ISD::MUL, DL, FLTTY, fqneg, fb), fa);
1293
1294   // int iq = (int)fq;
1295   SDValue iq = DAG.getNode(ISD::FP_TO_SINT, DL, INTTY, fq);
1296
1297   // fr = fabs(fr);
1298   fr = DAG.getNode(ISD::FABS, DL, FLTTY, fr);
1299
1300   // fb = fabs(fb);
1301   fb = DAG.getNode(ISD::FABS, DL, FLTTY, fb);
1302
1303   // int cv = fr >= fb;
1304   SDValue cv;
1305   if (INTTY == MVT::i32) {
1306     cv = DAG.getSetCC(DL, INTTY, fr, fb, ISD::SETOGE);
1307   } else {
1308     cv = DAG.getSetCC(DL, INTTY, fr, fb, ISD::SETOGE);
1309   }
1310   // jq = (cv ? jq : 0);
1311   jq = DAG.getNode(ISD::SELECT, DL, OVT, cv, jq,
1312       DAG.getConstant(0, OVT));
1313   // dst = iq + jq;
1314   iq = DAG.getSExtOrTrunc(iq, DL, OVT);
1315   iq = DAG.getNode(ISD::ADD, DL, OVT, iq, jq);
1316   return iq;
1317 }
1318
1319 SDValue AMDGPUTargetLowering::LowerSDIV32(SDValue Op, SelectionDAG &DAG) const {
1320   SDLoc DL(Op);
1321   EVT OVT = Op.getValueType();
1322   SDValue LHS = Op.getOperand(0);
1323   SDValue RHS = Op.getOperand(1);
1324   // The LowerSDIV32 function generates equivalent to the following IL.
1325   // mov r0, LHS
1326   // mov r1, RHS
1327   // ilt r10, r0, 0
1328   // ilt r11, r1, 0
1329   // iadd r0, r0, r10
1330   // iadd r1, r1, r11
1331   // ixor r0, r0, r10
1332   // ixor r1, r1, r11
1333   // udiv r0, r0, r1
1334   // ixor r10, r10, r11
1335   // iadd r0, r0, r10
1336   // ixor DST, r0, r10
1337
1338   // mov r0, LHS
1339   SDValue r0 = LHS;
1340
1341   // mov r1, RHS
1342   SDValue r1 = RHS;
1343
1344   // ilt r10, r0, 0
1345   SDValue r10 = DAG.getSelectCC(DL,
1346       r0, DAG.getConstant(0, OVT),
1347       DAG.getConstant(-1, OVT),
1348       DAG.getConstant(0, OVT),
1349       ISD::SETLT);
1350
1351   // ilt r11, r1, 0
1352   SDValue r11 = DAG.getSelectCC(DL,
1353       r1, DAG.getConstant(0, OVT),
1354       DAG.getConstant(-1, OVT),
1355       DAG.getConstant(0, OVT),
1356       ISD::SETLT);
1357
1358   // iadd r0, r0, r10
1359   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1360
1361   // iadd r1, r1, r11
1362   r1 = DAG.getNode(ISD::ADD, DL, OVT, r1, r11);
1363
1364   // ixor r0, r0, r10
1365   r0 = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1366
1367   // ixor r1, r1, r11
1368   r1 = DAG.getNode(ISD::XOR, DL, OVT, r1, r11);
1369
1370   // udiv r0, r0, r1
1371   r0 = DAG.getNode(ISD::UDIV, DL, OVT, r0, r1);
1372
1373   // ixor r10, r10, r11
1374   r10 = DAG.getNode(ISD::XOR, DL, OVT, r10, r11);
1375
1376   // iadd r0, r0, r10
1377   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1378
1379   // ixor DST, r0, r10
1380   SDValue DST = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1381   return DST;
1382 }
1383
1384 SDValue AMDGPUTargetLowering::LowerSDIV64(SDValue Op, SelectionDAG &DAG) const {
1385   return SDValue(Op.getNode(), 0);
1386 }
1387
1388 SDValue AMDGPUTargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
1389   EVT OVT = Op.getValueType().getScalarType();
1390
1391   if (OVT == MVT::i64)
1392     return LowerSDIV64(Op, DAG);
1393
1394   if (OVT.getScalarType() == MVT::i32)
1395     return LowerSDIV32(Op, DAG);
1396
1397   if (OVT == MVT::i16 || OVT == MVT::i8) {
1398     // FIXME: We should be checking for the masked bits. This isn't reached
1399     // because i8 and i16 are not legal types.
1400     return LowerSDIV24(Op, DAG);
1401   }
1402
1403   return SDValue(Op.getNode(), 0);
1404 }
1405
1406 SDValue AMDGPUTargetLowering::LowerSREM32(SDValue Op, SelectionDAG &DAG) const {
1407   SDLoc DL(Op);
1408   EVT OVT = Op.getValueType();
1409   SDValue LHS = Op.getOperand(0);
1410   SDValue RHS = Op.getOperand(1);
1411   // The LowerSREM32 function generates equivalent to the following IL.
1412   // mov r0, LHS
1413   // mov r1, RHS
1414   // ilt r10, r0, 0
1415   // ilt r11, r1, 0
1416   // iadd r0, r0, r10
1417   // iadd r1, r1, r11
1418   // ixor r0, r0, r10
1419   // ixor r1, r1, r11
1420   // udiv r20, r0, r1
1421   // umul r20, r20, r1
1422   // sub r0, r0, r20
1423   // iadd r0, r0, r10
1424   // ixor DST, r0, r10
1425
1426   // mov r0, LHS
1427   SDValue r0 = LHS;
1428
1429   // mov r1, RHS
1430   SDValue r1 = RHS;
1431
1432   // ilt r10, r0, 0
1433   SDValue r10 = DAG.getSetCC(DL, OVT, r0, DAG.getConstant(0, OVT), ISD::SETLT);
1434
1435   // ilt r11, r1, 0
1436   SDValue r11 = DAG.getSetCC(DL, OVT, r1, DAG.getConstant(0, OVT), ISD::SETLT);
1437
1438   // iadd r0, r0, r10
1439   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1440
1441   // iadd r1, r1, r11
1442   r1 = DAG.getNode(ISD::ADD, DL, OVT, r1, r11);
1443
1444   // ixor r0, r0, r10
1445   r0 = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1446
1447   // ixor r1, r1, r11
1448   r1 = DAG.getNode(ISD::XOR, DL, OVT, r1, r11);
1449
1450   // udiv r20, r0, r1
1451   SDValue r20 = DAG.getNode(ISD::UREM, DL, OVT, r0, r1);
1452
1453   // umul r20, r20, r1
1454   r20 = DAG.getNode(AMDGPUISD::UMUL, DL, OVT, r20, r1);
1455
1456   // sub r0, r0, r20
1457   r0 = DAG.getNode(ISD::SUB, DL, OVT, r0, r20);
1458
1459   // iadd r0, r0, r10
1460   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1461
1462   // ixor DST, r0, r10
1463   SDValue DST = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1464   return DST;
1465 }
1466
1467 SDValue AMDGPUTargetLowering::LowerSREM64(SDValue Op, SelectionDAG &DAG) const {
1468   return SDValue(Op.getNode(), 0);
1469 }
1470
1471 SDValue AMDGPUTargetLowering::LowerSREM(SDValue Op, SelectionDAG &DAG) const {
1472   EVT OVT = Op.getValueType();
1473
1474   if (OVT.getScalarType() == MVT::i64)
1475     return LowerSREM64(Op, DAG);
1476
1477   if (OVT.getScalarType() == MVT::i32)
1478     return LowerSREM32(Op, DAG);
1479
1480   return SDValue(Op.getNode(), 0);
1481 }
1482
1483 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1484                                            SelectionDAG &DAG) const {
1485   SDLoc DL(Op);
1486   EVT VT = Op.getValueType();
1487
1488   SDValue Num = Op.getOperand(0);
1489   SDValue Den = Op.getOperand(1);
1490
1491   // RCP =  URECIP(Den) = 2^32 / Den + e
1492   // e is rounding error.
1493   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1494
1495   // RCP_LO = umulo(RCP, Den) */
1496   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
1497
1498   // RCP_HI = mulhu (RCP, Den) */
1499   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1500
1501   // NEG_RCP_LO = -RCP_LO
1502   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
1503                                                      RCP_LO);
1504
1505   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1506   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1507                                            NEG_RCP_LO, RCP_LO,
1508                                            ISD::SETEQ);
1509   // Calculate the rounding error from the URECIP instruction
1510   // E = mulhu(ABS_RCP_LO, RCP)
1511   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1512
1513   // RCP_A_E = RCP + E
1514   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1515
1516   // RCP_S_E = RCP - E
1517   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1518
1519   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1520   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1521                                      RCP_A_E, RCP_S_E,
1522                                      ISD::SETEQ);
1523   // Quotient = mulhu(Tmp0, Num)
1524   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1525
1526   // Num_S_Remainder = Quotient * Den
1527   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
1528
1529   // Remainder = Num - Num_S_Remainder
1530   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1531
1532   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1533   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1534                                                  DAG.getConstant(-1, VT),
1535                                                  DAG.getConstant(0, VT),
1536                                                  ISD::SETUGE);
1537   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1538   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1539                                                   Num_S_Remainder,
1540                                                   DAG.getConstant(-1, VT),
1541                                                   DAG.getConstant(0, VT),
1542                                                   ISD::SETUGE);
1543   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1544   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1545                                                Remainder_GE_Zero);
1546
1547   // Calculate Division result:
1548
1549   // Quotient_A_One = Quotient + 1
1550   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1551                                                          DAG.getConstant(1, VT));
1552
1553   // Quotient_S_One = Quotient - 1
1554   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1555                                                          DAG.getConstant(1, VT));
1556
1557   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1558   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1559                                      Quotient, Quotient_A_One, ISD::SETEQ);
1560
1561   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1562   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1563                             Quotient_S_One, Div, ISD::SETEQ);
1564
1565   // Calculate Rem result:
1566
1567   // Remainder_S_Den = Remainder - Den
1568   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1569
1570   // Remainder_A_Den = Remainder + Den
1571   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1572
1573   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1574   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1575                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1576
1577   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1578   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1579                             Remainder_A_Den, Rem, ISD::SETEQ);
1580   SDValue Ops[2] = {
1581     Div,
1582     Rem
1583   };
1584   return DAG.getMergeValues(Ops, DL);
1585 }
1586
1587 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1588                                            SelectionDAG &DAG) const {
1589   SDLoc DL(Op);
1590   EVT VT = Op.getValueType();
1591
1592   SDValue Zero = DAG.getConstant(0, VT);
1593   SDValue NegOne = DAG.getConstant(-1, VT);
1594
1595   SDValue LHS = Op.getOperand(0);
1596   SDValue RHS = Op.getOperand(1);
1597
1598   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1599   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1600   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1601   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1602
1603   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1604   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1605
1606   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1607   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1608
1609   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1610   SDValue Rem = Div.getValue(1);
1611
1612   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1613   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1614
1615   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1616   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1617
1618   SDValue Res[2] = {
1619     Div,
1620     Rem
1621   };
1622   return DAG.getMergeValues(Res, DL);
1623 }
1624
1625 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1626   SDLoc SL(Op);
1627   SDValue Src = Op.getOperand(0);
1628
1629   // result = trunc(src)
1630   // if (src > 0.0 && src != result)
1631   //   result += 1.0
1632
1633   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1634
1635   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1636   const SDValue One = DAG.getConstantFP(1.0, MVT::f64);
1637
1638   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1639
1640   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1641   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1642   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1643
1644   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1645   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1646 }
1647
1648 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1649   SDLoc SL(Op);
1650   SDValue Src = Op.getOperand(0);
1651
1652   assert(Op.getValueType() == MVT::f64);
1653
1654   const SDValue Zero = DAG.getConstant(0, MVT::i32);
1655   const SDValue One = DAG.getConstant(1, MVT::i32);
1656
1657   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1658
1659   // Extract the upper half, since this is where we will find the sign and
1660   // exponent.
1661   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1662
1663   const unsigned FractBits = 52;
1664   const unsigned ExpBits = 11;
1665
1666   // Extract the exponent.
1667   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_I32, SL, MVT::i32,
1668                                 Hi,
1669                                 DAG.getConstant(FractBits - 32, MVT::i32),
1670                                 DAG.getConstant(ExpBits, MVT::i32));
1671   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1672                             DAG.getConstant(1023, MVT::i32));
1673
1674   // Extract the sign bit.
1675   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, MVT::i32);
1676   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1677
1678   // Extend back to to 64-bits.
1679   SDValue SignBit64 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
1680                                   Zero, SignBit);
1681   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1682
1683   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1684   const SDValue FractMask
1685     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, MVT::i64);
1686
1687   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1688   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1689   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1690
1691   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::i32);
1692
1693   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, MVT::i32);
1694
1695   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1696   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1697
1698   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1699   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
1700
1701   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
1702 }
1703
1704 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
1705   SDLoc SL(Op);
1706   SDValue Src = Op.getOperand(0);
1707
1708   assert(Op.getValueType() == MVT::f64);
1709
1710   APFloat C1Val(APFloat::IEEEdouble, "0x1.0p+52");
1711   SDValue C1 = DAG.getConstantFP(C1Val, MVT::f64);
1712   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
1713
1714   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
1715   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
1716
1717   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
1718
1719   APFloat C2Val(APFloat::IEEEdouble, "0x1.fffffffffffffp+51");
1720   SDValue C2 = DAG.getConstantFP(C2Val, MVT::f64);
1721
1722   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1723   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
1724
1725   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
1726 }
1727
1728 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
1729   // FNEARBYINT and FRINT are the same, except in their handling of FP
1730   // exceptions. Those aren't really meaningful for us, and OpenCL only has
1731   // rint, so just treat them as equivalent.
1732   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
1733 }
1734
1735 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
1736   SDLoc SL(Op);
1737   SDValue Src = Op.getOperand(0);
1738
1739   // result = trunc(src);
1740   // if (src < 0.0 && src != result)
1741   //   result += -1.0.
1742
1743   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1744
1745   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1746   const SDValue NegOne = DAG.getConstantFP(-1.0, MVT::f64);
1747
1748   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1749
1750   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
1751   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1752   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1753
1754   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
1755   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1756 }
1757
1758 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
1759                                                SelectionDAG &DAG) const {
1760   SDValue S0 = Op.getOperand(0);
1761   SDLoc DL(Op);
1762   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
1763     return SDValue();
1764
1765   // f32 uint_to_fp i64
1766   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1767                            DAG.getConstant(0, MVT::i32));
1768   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
1769   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1770                            DAG.getConstant(1, MVT::i32));
1771   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
1772   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
1773                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
1774   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
1775 }
1776
1777 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
1778                                                       unsigned BitsDiff,
1779                                                       SelectionDAG &DAG) const {
1780   MVT VT = Op.getSimpleValueType();
1781   SDLoc DL(Op);
1782   SDValue Shift = DAG.getConstant(BitsDiff, VT);
1783   // Shift left by 'Shift' bits.
1784   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
1785   // Signed shift Right by 'Shift' bits.
1786   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
1787 }
1788
1789 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1790                                                      SelectionDAG &DAG) const {
1791   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1792   MVT VT = Op.getSimpleValueType();
1793   MVT ScalarVT = VT.getScalarType();
1794
1795   if (!VT.isVector())
1796     return SDValue();
1797
1798   SDValue Src = Op.getOperand(0);
1799   SDLoc DL(Op);
1800
1801   // TODO: Don't scalarize on Evergreen?
1802   unsigned NElts = VT.getVectorNumElements();
1803   SmallVector<SDValue, 8> Args;
1804   DAG.ExtractVectorElements(Src, Args, 0, NElts);
1805
1806   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
1807   for (unsigned I = 0; I < NElts; ++I)
1808     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
1809
1810   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);
1811 }
1812
1813 //===----------------------------------------------------------------------===//
1814 // Custom DAG optimizations
1815 //===----------------------------------------------------------------------===//
1816
1817 static bool isU24(SDValue Op, SelectionDAG &DAG) {
1818   APInt KnownZero, KnownOne;
1819   EVT VT = Op.getValueType();
1820   DAG.computeKnownBits(Op, KnownZero, KnownOne);
1821
1822   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
1823 }
1824
1825 static bool isI24(SDValue Op, SelectionDAG &DAG) {
1826   EVT VT = Op.getValueType();
1827
1828   // In order for this to be a signed 24-bit value, bit 23, must
1829   // be a sign bit.
1830   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
1831                                      // as unsigned 24-bit values.
1832          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
1833 }
1834
1835 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
1836
1837   SelectionDAG &DAG = DCI.DAG;
1838   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1839   EVT VT = Op.getValueType();
1840
1841   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
1842   APInt KnownZero, KnownOne;
1843   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
1844   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
1845     DCI.CommitTargetLoweringOpt(TLO);
1846 }
1847
1848 template <typename IntTy>
1849 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0,
1850                                uint32_t Offset, uint32_t Width) {
1851   if (Width + Offset < 32) {
1852     IntTy Result = (Src0 << (32 - Offset - Width)) >> (32 - Width);
1853     return DAG.getConstant(Result, MVT::i32);
1854   }
1855
1856   return DAG.getConstant(Src0 >> Offset, MVT::i32);
1857 }
1858
1859 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
1860                                                 DAGCombinerInfo &DCI) const {
1861   EVT VT = N->getValueType(0);
1862
1863   if (VT.isVector() || VT.getSizeInBits() > 32)
1864     return SDValue();
1865
1866   SelectionDAG &DAG = DCI.DAG;
1867   SDLoc DL(N);
1868
1869   SDValue N0 = N->getOperand(0);
1870   SDValue N1 = N->getOperand(1);
1871   SDValue Mul;
1872
1873   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
1874     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
1875     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
1876     Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
1877   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
1878     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
1879     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
1880     Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
1881   } else {
1882     return SDValue();
1883   }
1884
1885   // We need to use sext even for MUL_U24, because MUL_U24 is used
1886   // for signed multiply of 8 and 16-bit types.
1887   return DAG.getSExtOrTrunc(Mul, DL, VT);
1888 }
1889
1890 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
1891                                             DAGCombinerInfo &DCI) const {
1892   SelectionDAG &DAG = DCI.DAG;
1893   SDLoc DL(N);
1894
1895   switch(N->getOpcode()) {
1896     default: break;
1897     case ISD::MUL:
1898       return performMulCombine(N, DCI);
1899     case AMDGPUISD::MUL_I24:
1900     case AMDGPUISD::MUL_U24: {
1901       SDValue N0 = N->getOperand(0);
1902       SDValue N1 = N->getOperand(1);
1903       simplifyI24(N0, DCI);
1904       simplifyI24(N1, DCI);
1905       return SDValue();
1906     }
1907     case ISD::SELECT_CC: {
1908       return CombineMinMax(N, DAG);
1909     }
1910   case AMDGPUISD::BFE_I32:
1911   case AMDGPUISD::BFE_U32: {
1912     assert(!N->getValueType(0).isVector() &&
1913            "Vector handling of BFE not implemented");
1914     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
1915     if (!Width)
1916       break;
1917
1918     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
1919     if (WidthVal == 0)
1920       return DAG.getConstant(0, MVT::i32);
1921
1922     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
1923     if (!Offset)
1924       break;
1925
1926     SDValue BitsFrom = N->getOperand(0);
1927     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
1928
1929     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
1930
1931     if (OffsetVal == 0) {
1932       // This is already sign / zero extended, so try to fold away extra BFEs.
1933       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
1934
1935       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
1936       if (OpSignBits >= SignBits)
1937         return BitsFrom;
1938
1939       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
1940       if (Signed) {
1941         // This is a sign_extend_inreg. Replace it to take advantage of existing
1942         // DAG Combines. If not eliminated, we will match back to BFE during
1943         // selection.
1944
1945         // TODO: The sext_inreg of extended types ends, although we can could
1946         // handle them in a single BFE.
1947         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
1948                            DAG.getValueType(SmallVT));
1949       }
1950
1951       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
1952     }
1953
1954     if (ConstantSDNode *Val = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
1955       if (Signed) {
1956         return constantFoldBFE<int32_t>(DAG,
1957                                         Val->getSExtValue(),
1958                                         OffsetVal,
1959                                         WidthVal);
1960       }
1961
1962       return constantFoldBFE<uint32_t>(DAG,
1963                                        Val->getZExtValue(),
1964                                        OffsetVal,
1965                                        WidthVal);
1966     }
1967
1968     APInt Demanded = APInt::getBitsSet(32,
1969                                        OffsetVal,
1970                                        OffsetVal + WidthVal);
1971
1972     if ((OffsetVal + WidthVal) >= 32) {
1973       SDValue ShiftVal = DAG.getConstant(OffsetVal, MVT::i32);
1974       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1975                          BitsFrom, ShiftVal);
1976     }
1977
1978     APInt KnownZero, KnownOne;
1979     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1980                                           !DCI.isBeforeLegalizeOps());
1981     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1982     if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
1983         TLI.SimplifyDemandedBits(BitsFrom, Demanded, KnownZero, KnownOne, TLO)) {
1984       DCI.CommitTargetLoweringOpt(TLO);
1985     }
1986
1987     break;
1988   }
1989   }
1990   return SDValue();
1991 }
1992
1993 //===----------------------------------------------------------------------===//
1994 // Helper functions
1995 //===----------------------------------------------------------------------===//
1996
1997 void AMDGPUTargetLowering::getOriginalFunctionArgs(
1998                                SelectionDAG &DAG,
1999                                const Function *F,
2000                                const SmallVectorImpl<ISD::InputArg> &Ins,
2001                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
2002
2003   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
2004     if (Ins[i].ArgVT == Ins[i].VT) {
2005       OrigIns.push_back(Ins[i]);
2006       continue;
2007     }
2008
2009     EVT VT;
2010     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
2011       // Vector has been split into scalars.
2012       VT = Ins[i].ArgVT.getVectorElementType();
2013     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
2014                Ins[i].ArgVT.getVectorElementType() !=
2015                Ins[i].VT.getVectorElementType()) {
2016       // Vector elements have been promoted
2017       VT = Ins[i].ArgVT;
2018     } else {
2019       // Vector has been spilt into smaller vectors.
2020       VT = Ins[i].VT;
2021     }
2022
2023     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
2024                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
2025     OrigIns.push_back(Arg);
2026   }
2027 }
2028
2029 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
2030   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2031     return CFP->isExactlyValue(1.0);
2032   }
2033   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2034     return C->isAllOnesValue();
2035   }
2036   return false;
2037 }
2038
2039 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
2040   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2041     return CFP->getValueAPF().isZero();
2042   }
2043   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2044     return C->isNullValue();
2045   }
2046   return false;
2047 }
2048
2049 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2050                                                   const TargetRegisterClass *RC,
2051                                                    unsigned Reg, EVT VT) const {
2052   MachineFunction &MF = DAG.getMachineFunction();
2053   MachineRegisterInfo &MRI = MF.getRegInfo();
2054   unsigned VirtualRegister;
2055   if (!MRI.isLiveIn(Reg)) {
2056     VirtualRegister = MRI.createVirtualRegister(RC);
2057     MRI.addLiveIn(Reg, VirtualRegister);
2058   } else {
2059     VirtualRegister = MRI.getLiveInVirtReg(Reg);
2060   }
2061   return DAG.getRegister(VirtualRegister, VT);
2062 }
2063
2064 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
2065
2066 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
2067   switch (Opcode) {
2068   default: return nullptr;
2069   // AMDIL DAG nodes
2070   NODE_NAME_CASE(CALL);
2071   NODE_NAME_CASE(UMUL);
2072   NODE_NAME_CASE(RET_FLAG);
2073   NODE_NAME_CASE(BRANCH_COND);
2074
2075   // AMDGPU DAG nodes
2076   NODE_NAME_CASE(DWORDADDR)
2077   NODE_NAME_CASE(FRACT)
2078   NODE_NAME_CASE(CLAMP)
2079   NODE_NAME_CASE(FMAX)
2080   NODE_NAME_CASE(SMAX)
2081   NODE_NAME_CASE(UMAX)
2082   NODE_NAME_CASE(FMIN)
2083   NODE_NAME_CASE(SMIN)
2084   NODE_NAME_CASE(UMIN)
2085   NODE_NAME_CASE(URECIP)
2086   NODE_NAME_CASE(DIV_SCALE)
2087   NODE_NAME_CASE(DIV_FMAS)
2088   NODE_NAME_CASE(DIV_FIXUP)
2089   NODE_NAME_CASE(TRIG_PREOP)
2090   NODE_NAME_CASE(RCP)
2091   NODE_NAME_CASE(RSQ)
2092   NODE_NAME_CASE(RSQ_LEGACY)
2093   NODE_NAME_CASE(RSQ_CLAMPED)
2094   NODE_NAME_CASE(DOT4)
2095   NODE_NAME_CASE(BFE_U32)
2096   NODE_NAME_CASE(BFE_I32)
2097   NODE_NAME_CASE(BFI)
2098   NODE_NAME_CASE(BFM)
2099   NODE_NAME_CASE(BREV)
2100   NODE_NAME_CASE(MUL_U24)
2101   NODE_NAME_CASE(MUL_I24)
2102   NODE_NAME_CASE(MAD_U24)
2103   NODE_NAME_CASE(MAD_I24)
2104   NODE_NAME_CASE(EXPORT)
2105   NODE_NAME_CASE(CONST_ADDRESS)
2106   NODE_NAME_CASE(REGISTER_LOAD)
2107   NODE_NAME_CASE(REGISTER_STORE)
2108   NODE_NAME_CASE(LOAD_CONSTANT)
2109   NODE_NAME_CASE(LOAD_INPUT)
2110   NODE_NAME_CASE(SAMPLE)
2111   NODE_NAME_CASE(SAMPLEB)
2112   NODE_NAME_CASE(SAMPLED)
2113   NODE_NAME_CASE(SAMPLEL)
2114   NODE_NAME_CASE(CVT_F32_UBYTE0)
2115   NODE_NAME_CASE(CVT_F32_UBYTE1)
2116   NODE_NAME_CASE(CVT_F32_UBYTE2)
2117   NODE_NAME_CASE(CVT_F32_UBYTE3)
2118   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
2119   NODE_NAME_CASE(STORE_MSKOR)
2120   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
2121   }
2122 }
2123
2124 static void computeKnownBitsForMinMax(const SDValue Op0,
2125                                       const SDValue Op1,
2126                                       APInt &KnownZero,
2127                                       APInt &KnownOne,
2128                                       const SelectionDAG &DAG,
2129                                       unsigned Depth) {
2130   APInt Op0Zero, Op0One;
2131   APInt Op1Zero, Op1One;
2132   DAG.computeKnownBits(Op0, Op0Zero, Op0One, Depth);
2133   DAG.computeKnownBits(Op1, Op1Zero, Op1One, Depth);
2134
2135   KnownZero = Op0Zero & Op1Zero;
2136   KnownOne = Op0One & Op1One;
2137 }
2138
2139 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
2140   const SDValue Op,
2141   APInt &KnownZero,
2142   APInt &KnownOne,
2143   const SelectionDAG &DAG,
2144   unsigned Depth) const {
2145
2146   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
2147
2148   APInt KnownZero2;
2149   APInt KnownOne2;
2150   unsigned Opc = Op.getOpcode();
2151
2152   switch (Opc) {
2153   default:
2154     break;
2155   case ISD::INTRINSIC_WO_CHAIN: {
2156     // FIXME: The intrinsic should just use the node.
2157     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
2158     case AMDGPUIntrinsic::AMDGPU_imax:
2159     case AMDGPUIntrinsic::AMDGPU_umax:
2160     case AMDGPUIntrinsic::AMDGPU_imin:
2161     case AMDGPUIntrinsic::AMDGPU_umin:
2162       computeKnownBitsForMinMax(Op.getOperand(1), Op.getOperand(2),
2163                                 KnownZero, KnownOne, DAG, Depth);
2164       break;
2165     default:
2166       break;
2167     }
2168
2169     break;
2170   }
2171   case AMDGPUISD::SMAX:
2172   case AMDGPUISD::UMAX:
2173   case AMDGPUISD::SMIN:
2174   case AMDGPUISD::UMIN:
2175     computeKnownBitsForMinMax(Op.getOperand(0), Op.getOperand(1),
2176                               KnownZero, KnownOne, DAG, Depth);
2177     break;
2178
2179   case AMDGPUISD::BFE_I32:
2180   case AMDGPUISD::BFE_U32: {
2181     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2182     if (!CWidth)
2183       return;
2184
2185     unsigned BitWidth = 32;
2186     uint32_t Width = CWidth->getZExtValue() & 0x1f;
2187     if (Width == 0) {
2188       KnownZero = APInt::getAllOnesValue(BitWidth);
2189       KnownOne = APInt::getNullValue(BitWidth);
2190       return;
2191     }
2192
2193     // FIXME: This could do a lot more. If offset is 0, should be the same as
2194     // sign_extend_inreg implementation, but that involves duplicating it.
2195     if (Opc == AMDGPUISD::BFE_I32)
2196       KnownOne = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2197     else
2198       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2199
2200     break;
2201   }
2202   }
2203 }
2204
2205 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
2206   SDValue Op,
2207   const SelectionDAG &DAG,
2208   unsigned Depth) const {
2209   switch (Op.getOpcode()) {
2210   case AMDGPUISD::BFE_I32: {
2211     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2212     if (!Width)
2213       return 1;
2214
2215     unsigned SignBits = 32 - Width->getZExtValue() + 1;
2216     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2217     if (!Offset || !Offset->isNullValue())
2218       return SignBits;
2219
2220     // TODO: Could probably figure something out with non-0 offsets.
2221     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2222     return std::max(SignBits, Op0SignBits);
2223   }
2224
2225   case AMDGPUISD::BFE_U32: {
2226     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2227     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
2228   }
2229
2230   default:
2231     return 1;
2232   }
2233 }