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