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