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