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