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