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