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