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