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