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