R600/SI: Add intrinsics for brev instructions
[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   // Lower floating point store/load to integer store/load to reduce the number
130   // of patterns in tablegen.
131   setOperationAction(ISD::STORE, MVT::f32, Promote);
132   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
133
134   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
135   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
136
137   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
138   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
139
140   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
141   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
142
143   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
144   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
145
146   setOperationAction(ISD::STORE, MVT::f64, Promote);
147   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
148
149   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
150   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v2i64);
151
152   // Custom lowering of vector stores is required for local address space
153   // stores.
154   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
155   // XXX: Native v2i32 local address space stores are possible, but not
156   // currently implemented.
157   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
158
159   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
160   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
161   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
162
163   // XXX: This can be change to Custom, once ExpandVectorStores can
164   // handle 64-bit stores.
165   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
166
167   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
168   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
169   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
170   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
171   setTruncStoreAction(MVT::v4i64, MVT::v4i1, Expand);
172
173
174   setOperationAction(ISD::LOAD, MVT::f32, Promote);
175   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
176
177   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
178   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
179
180   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
181   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
182
183   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
184   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
185
186   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
187   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
188
189   setOperationAction(ISD::LOAD, MVT::f64, Promote);
190   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::i64);
191
192   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
193   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v2i64);
194
195   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
196   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
197   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
198   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
199   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
200   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
201   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
202   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
203   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
204   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
205
206   setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Expand);
207   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Expand);
208   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i8, Expand);
209   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
210   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Expand);
211   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Expand);
212   setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Expand);
213   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Expand);
214   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, Expand);
215   setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Expand);
216   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Expand);
217   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, Expand);
218
219   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
220
221   if (Subtarget->getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
222     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
223     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
224     setOperationAction(ISD::FRINT, MVT::f64, Custom);
225     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
226   }
227
228   if (!Subtarget->hasBFI()) {
229     // fcopysign can be done in a single instruction with BFI.
230     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
231     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
232   }
233
234   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
235   for (MVT VT : ScalarIntVTs) {
236     setOperationAction(ISD::SREM, VT, Expand);
237     setOperationAction(ISD::SDIV, VT, Custom);
238
239     // GPU does not have divrem function for signed or unsigned.
240     setOperationAction(ISD::SDIVREM, VT, Expand);
241     setOperationAction(ISD::UDIVREM, VT, Custom);
242
243     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
244     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
245     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
246
247     setOperationAction(ISD::BSWAP, VT, Expand);
248     setOperationAction(ISD::CTTZ, VT, Expand);
249     setOperationAction(ISD::CTLZ, VT, Expand);
250   }
251
252   if (!Subtarget->hasBCNT(32))
253     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
254
255   if (!Subtarget->hasBCNT(64))
256     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
257
258   // The hardware supports 32-bit ROTR, but not ROTL.
259   setOperationAction(ISD::ROTL, MVT::i32, Expand);
260   setOperationAction(ISD::ROTL, MVT::i64, Expand);
261   setOperationAction(ISD::ROTR, MVT::i64, Expand);
262
263   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Expand);
264   setOperationAction(ISD::MUL, MVT::i64, Expand);
265   setOperationAction(ISD::MULHU, MVT::i64, Expand);
266   setOperationAction(ISD::MULHS, MVT::i64, Expand);
267   setOperationAction(ISD::SUB, MVT::i64, Expand);
268   setOperationAction(ISD::UDIV, MVT::i32, Expand);
269   setOperationAction(ISD::UREM, MVT::i32, Expand);
270   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
271   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
272
273   static const MVT::SimpleValueType VectorIntTypes[] = {
274     MVT::v2i32, MVT::v4i32
275   };
276
277   for (MVT VT : VectorIntTypes) {
278     // Expand the following operations for the current type by default.
279     setOperationAction(ISD::ADD,  VT, Expand);
280     setOperationAction(ISD::AND,  VT, Expand);
281     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
282     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
283     setOperationAction(ISD::MUL,  VT, Expand);
284     setOperationAction(ISD::OR,   VT, Expand);
285     setOperationAction(ISD::SHL,  VT, Expand);
286     setOperationAction(ISD::SRA,  VT, Expand);
287     setOperationAction(ISD::SRL,  VT, Expand);
288     setOperationAction(ISD::ROTL, VT, Expand);
289     setOperationAction(ISD::ROTR, VT, Expand);
290     setOperationAction(ISD::SUB,  VT, Expand);
291     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
292     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
293     // TODO: Implement custom UREM / SREM routines.
294     setOperationAction(ISD::SDIV, VT, Custom);
295     setOperationAction(ISD::UDIV, VT, Expand);
296     setOperationAction(ISD::SREM, VT, Expand);
297     setOperationAction(ISD::UREM, VT, Expand);
298     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
299     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
300     setOperationAction(ISD::SDIVREM, VT, Expand);
301     setOperationAction(ISD::UDIVREM, VT, Custom);
302     setOperationAction(ISD::SELECT, VT, Expand);
303     setOperationAction(ISD::VSELECT, VT, Expand);
304     setOperationAction(ISD::XOR,  VT, Expand);
305     setOperationAction(ISD::BSWAP, VT, Expand);
306     setOperationAction(ISD::CTPOP, VT, Expand);
307     setOperationAction(ISD::CTTZ, VT, Expand);
308     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
309     setOperationAction(ISD::CTLZ, VT, Expand);
310     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
311   }
312
313   static const MVT::SimpleValueType FloatVectorTypes[] = {
314     MVT::v2f32, MVT::v4f32
315   };
316
317   for (MVT VT : FloatVectorTypes) {
318     setOperationAction(ISD::FABS, VT, Expand);
319     setOperationAction(ISD::FADD, VT, Expand);
320     setOperationAction(ISD::FCOS, VT, Expand);
321     setOperationAction(ISD::FDIV, VT, Expand);
322     setOperationAction(ISD::FPOW, VT, Expand);
323     setOperationAction(ISD::FFLOOR, VT, Expand);
324     setOperationAction(ISD::FTRUNC, VT, Expand);
325     setOperationAction(ISD::FMUL, VT, Expand);
326     setOperationAction(ISD::FRINT, VT, Expand);
327     setOperationAction(ISD::FSQRT, VT, Expand);
328     setOperationAction(ISD::FSIN, VT, Expand);
329     setOperationAction(ISD::FSUB, VT, Expand);
330     setOperationAction(ISD::FNEG, VT, Expand);
331     setOperationAction(ISD::SELECT, VT, Expand);
332     setOperationAction(ISD::VSELECT, VT, Expand);
333     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
334   }
335
336   setTargetDAGCombine(ISD::MUL);
337   setTargetDAGCombine(ISD::SELECT_CC);
338
339   setSchedulingPreference(Sched::RegPressure);
340   setJumpIsExpensive(true);
341
342   // There are no integer divide instructions, and these expand to a pretty
343   // large sequence of instructions.
344   setIntDivIsCheap(false);
345
346   // TODO: Investigate this when 64-bit divides are implemented.
347   addBypassSlowDiv(64, 32);
348
349   // FIXME: Need to really handle these.
350   MaxStoresPerMemcpy  = 4096;
351   MaxStoresPerMemmove = 4096;
352   MaxStoresPerMemset  = 4096;
353 }
354
355 //===----------------------------------------------------------------------===//
356 // Target Information
357 //===----------------------------------------------------------------------===//
358
359 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
360   return MVT::i32;
361 }
362
363 // The backend supports 32 and 64 bit floating point immediates.
364 // FIXME: Why are we reporting vectors of FP immediates as legal?
365 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
366   EVT ScalarVT = VT.getScalarType();
367   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64);
368 }
369
370 // We don't want to shrink f64 / f32 constants.
371 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
372   EVT ScalarVT = VT.getScalarType();
373   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
374 }
375
376 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
377                                                    EVT CastTy) const {
378   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
379     return true;
380
381   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
382   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
383
384   return ((LScalarSize <= CastScalarSize) ||
385           (CastScalarSize >= 32) ||
386           (LScalarSize < 32));
387 }
388
389 //===---------------------------------------------------------------------===//
390 // Target Properties
391 //===---------------------------------------------------------------------===//
392
393 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
394   assert(VT.isFloatingPoint());
395   return VT == MVT::f32;
396 }
397
398 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
399   assert(VT.isFloatingPoint());
400   return VT == MVT::f32;
401 }
402
403 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
404   // Truncate is just accessing a subregister.
405   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
406 }
407
408 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
409   // Truncate is just accessing a subregister.
410   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
411          (Dest->getPrimitiveSizeInBits() % 32 == 0);
412 }
413
414 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
415   const DataLayout *DL = getDataLayout();
416   unsigned SrcSize = DL->getTypeSizeInBits(Src->getScalarType());
417   unsigned DestSize = DL->getTypeSizeInBits(Dest->getScalarType());
418
419   return SrcSize == 32 && DestSize == 64;
420 }
421
422 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
423   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
424   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
425   // this will enable reducing 64-bit operations the 32-bit, which is always
426   // good.
427   return Src == MVT::i32 && Dest == MVT::i64;
428 }
429
430 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
431   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
432   // limited number of native 64-bit operations. Shrinking an operation to fit
433   // in a single 32-bit register should always be helpful. As currently used,
434   // this is much less general than the name suggests, and is only used in
435   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
436   // not profitable, and may actually be harmful.
437   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
438 }
439
440 //===---------------------------------------------------------------------===//
441 // TargetLowering Callbacks
442 //===---------------------------------------------------------------------===//
443
444 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
445                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
446
447   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
448 }
449
450 SDValue AMDGPUTargetLowering::LowerReturn(
451                                      SDValue Chain,
452                                      CallingConv::ID CallConv,
453                                      bool isVarArg,
454                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
455                                      const SmallVectorImpl<SDValue> &OutVals,
456                                      SDLoc DL, SelectionDAG &DAG) const {
457   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
458 }
459
460 //===---------------------------------------------------------------------===//
461 // Target specific lowering
462 //===---------------------------------------------------------------------===//
463
464 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
465                                         SmallVectorImpl<SDValue> &InVals) const {
466   SDValue Callee = CLI.Callee;
467   SelectionDAG &DAG = CLI.DAG;
468
469   const Function &Fn = *DAG.getMachineFunction().getFunction();
470
471   StringRef FuncName("<unknown>");
472
473   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
474     FuncName = G->getSymbol();
475   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
476     FuncName = G->getGlobal()->getName();
477
478   DiagnosticInfoUnsupported NoCalls(Fn, "call to function " + FuncName);
479   DAG.getContext()->diagnose(NoCalls);
480   return SDValue();
481 }
482
483 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
484                                              SelectionDAG &DAG) const {
485   switch (Op.getOpcode()) {
486   default:
487     Op.getNode()->dump();
488     llvm_unreachable("Custom lowering code for this"
489                      "instruction is not implemented yet!");
490     break;
491   // AMDGPU DAG lowering.
492   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
493   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
494   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
495   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
496   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
497   case ISD::SDIV: return LowerSDIV(Op, DAG);
498   case ISD::SREM: return LowerSREM(Op, DAG);
499   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
500   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
501   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
502   case ISD::FRINT: return LowerFRINT(Op, DAG);
503   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
504   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
505
506   // AMDIL DAG lowering.
507   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
508   }
509   return Op;
510 }
511
512 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
513                                               SmallVectorImpl<SDValue> &Results,
514                                               SelectionDAG &DAG) const {
515   switch (N->getOpcode()) {
516   case ISD::SIGN_EXTEND_INREG:
517     // Different parts of legalization seem to interpret which type of
518     // sign_extend_inreg is the one to check for custom lowering. The extended
519     // from type is what really matters, but some places check for custom
520     // lowering of the result type. This results in trying to use
521     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
522     // nothing here and let the illegal result integer be handled normally.
523     return;
524   case ISD::UDIV: {
525     SDValue Op = SDValue(N, 0);
526     SDLoc DL(Op);
527     EVT VT = Op.getValueType();
528     SDValue UDIVREM = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT),
529       N->getOperand(0), N->getOperand(1));
530     Results.push_back(UDIVREM);
531     break;
532   }
533   case ISD::UREM: {
534     SDValue Op = SDValue(N, 0);
535     SDLoc DL(Op);
536     EVT VT = Op.getValueType();
537     SDValue UDIVREM = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT),
538       N->getOperand(0), N->getOperand(1));
539     Results.push_back(UDIVREM.getValue(1));
540     break;
541   }
542   case ISD::UDIVREM: {
543     SDValue Op = SDValue(N, 0);
544     SDLoc DL(Op);
545     EVT VT = Op.getValueType();
546     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
547
548     SDValue one = DAG.getConstant(1, HalfVT);
549     SDValue zero = DAG.getConstant(0, HalfVT);
550
551     //HiLo split
552     SDValue LHS = N->getOperand(0);
553     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
554     SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
555
556     SDValue RHS = N->getOperand(1);
557     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
558     SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
559
560     // Get Speculative values
561     SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
562     SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
563
564     SDValue REM_Hi = zero;
565     SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
566
567     SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
568     SDValue DIV_Lo = zero;
569
570     const unsigned halfBitWidth = HalfVT.getSizeInBits();
571
572     for (unsigned i = 0; i < halfBitWidth; ++i) {
573       SDValue POS = DAG.getConstant(halfBitWidth - i - 1, HalfVT);
574       // Get Value of high bit
575       SDValue HBit;
576       if (halfBitWidth == 32 && Subtarget->hasBFE()) {
577         HBit = DAG.getNode(AMDGPUISD::BFE_U32, DL, HalfVT, LHS_Lo, POS, one);
578       } else {
579         HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
580         HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
581       }
582
583       SDValue Carry = DAG.getNode(ISD::SRL, DL, HalfVT, REM_Lo,
584         DAG.getConstant(halfBitWidth - 1, HalfVT));
585       REM_Hi = DAG.getNode(ISD::SHL, DL, HalfVT, REM_Hi, one);
586       REM_Hi = DAG.getNode(ISD::OR, DL, HalfVT, REM_Hi, Carry);
587
588       REM_Lo = DAG.getNode(ISD::SHL, DL, HalfVT, REM_Lo, one);
589       REM_Lo = DAG.getNode(ISD::OR, DL, HalfVT, REM_Lo, HBit);
590
591
592       SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, REM_Hi);
593
594       SDValue BIT = DAG.getConstant(1 << (halfBitWidth - i - 1), HalfVT);
595       SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETGE);
596
597       DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
598
599       // Update REM
600
601       SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
602
603       REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETGE);
604       REM_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, REM, zero);
605       REM_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, REM, one);
606     }
607
608     SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, REM_Hi);
609     SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, DIV_Lo, DIV_Hi);
610     Results.push_back(DIV);
611     Results.push_back(REM);
612     break;
613   }
614   default:
615     return;
616   }
617 }
618
619 // FIXME: This implements accesses to initialized globals in the constant
620 // address space by copying them to private and accessing that. It does not
621 // properly handle illegal types or vectors. The private vector loads are not
622 // scalarized, and the illegal scalars hit an assertion. This technique will not
623 // work well with large initializers, and this should eventually be
624 // removed. Initialized globals should be placed into a data section that the
625 // runtime will load into a buffer before the kernel is executed. Uses of the
626 // global need to be replaced with a pointer loaded from an implicit kernel
627 // argument into this buffer holding the copy of the data, which will remove the
628 // need for any of this.
629 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
630                                                        const GlobalValue *GV,
631                                                        const SDValue &InitPtr,
632                                                        SDValue Chain,
633                                                        SelectionDAG &DAG) const {
634   const DataLayout *TD = getTargetMachine().getDataLayout();
635   SDLoc DL(InitPtr);
636   Type *InitTy = Init->getType();
637
638   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
639     EVT VT = EVT::getEVT(InitTy);
640     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
641     return DAG.getStore(Chain, DL, DAG.getConstant(*CI, VT), InitPtr,
642                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
643                         TD->getPrefTypeAlignment(InitTy));
644   }
645
646   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
647     EVT VT = EVT::getEVT(CFP->getType());
648     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
649     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
650                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
651                  TD->getPrefTypeAlignment(CFP->getType()));
652   }
653
654   if (StructType *ST = dyn_cast<StructType>(InitTy)) {
655     const StructLayout *SL = TD->getStructLayout(ST);
656
657     EVT PtrVT = InitPtr.getValueType();
658     SmallVector<SDValue, 8> Chains;
659
660     for (unsigned I = 0, N = ST->getNumElements(); I != N; ++I) {
661       SDValue Offset = DAG.getConstant(SL->getElementOffset(I), PtrVT);
662       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
663
664       Constant *Elt = Init->getAggregateElement(I);
665       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
666     }
667
668     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
669   }
670
671   if (SequentialType *SeqTy = dyn_cast<SequentialType>(InitTy)) {
672     EVT PtrVT = InitPtr.getValueType();
673
674     unsigned NumElements;
675     if (ArrayType *AT = dyn_cast<ArrayType>(SeqTy))
676       NumElements = AT->getNumElements();
677     else if (VectorType *VT = dyn_cast<VectorType>(SeqTy))
678       NumElements = VT->getNumElements();
679     else
680       llvm_unreachable("Unexpected type");
681
682     unsigned EltSize = TD->getTypeAllocSize(SeqTy->getElementType());
683     SmallVector<SDValue, 8> Chains;
684     for (unsigned i = 0; i < NumElements; ++i) {
685       SDValue Offset = DAG.getConstant(i * EltSize, PtrVT);
686       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
687
688       Constant *Elt = Init->getAggregateElement(i);
689       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
690     }
691
692     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
693   }
694
695   if (isa<UndefValue>(Init)) {
696     EVT VT = EVT::getEVT(InitTy);
697     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
698     return DAG.getStore(Chain, DL, DAG.getUNDEF(VT), InitPtr,
699                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
700                         TD->getPrefTypeAlignment(InitTy));
701   }
702
703   Init->dump();
704   llvm_unreachable("Unhandled constant initializer");
705 }
706
707 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
708                                                  SDValue Op,
709                                                  SelectionDAG &DAG) const {
710
711   const DataLayout *TD = getTargetMachine().getDataLayout();
712   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
713   const GlobalValue *GV = G->getGlobal();
714
715   switch (G->getAddressSpace()) {
716   default: llvm_unreachable("Global Address lowering not implemented for this "
717                             "address space");
718   case AMDGPUAS::LOCAL_ADDRESS: {
719     // XXX: What does the value of G->getOffset() mean?
720     assert(G->getOffset() == 0 &&
721          "Do not know what to do with an non-zero offset");
722
723     unsigned Offset;
724     if (MFI->LocalMemoryObjects.count(GV) == 0) {
725       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
726       Offset = MFI->LDSSize;
727       MFI->LocalMemoryObjects[GV] = Offset;
728       // XXX: Account for alignment?
729       MFI->LDSSize += Size;
730     } else {
731       Offset = MFI->LocalMemoryObjects[GV];
732     }
733
734     return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
735   }
736   case AMDGPUAS::CONSTANT_ADDRESS: {
737     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
738     Type *EltType = GV->getType()->getElementType();
739     unsigned Size = TD->getTypeAllocSize(EltType);
740     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
741
742     MVT PrivPtrVT = getPointerTy(AMDGPUAS::PRIVATE_ADDRESS);
743     MVT ConstPtrVT = getPointerTy(AMDGPUAS::CONSTANT_ADDRESS);
744
745     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
746     SDValue InitPtr = DAG.getFrameIndex(FI, PrivPtrVT);
747
748     const GlobalVariable *Var = cast<GlobalVariable>(GV);
749     if (!Var->hasInitializer()) {
750       // This has no use, but bugpoint will hit it.
751       return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
752     }
753
754     const Constant *Init = Var->getInitializer();
755     SmallVector<SDNode*, 8> WorkList;
756
757     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
758                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
759       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
760         continue;
761       WorkList.push_back(*I);
762     }
763     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
764     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
765                                            E = WorkList.end(); I != E; ++I) {
766       SmallVector<SDValue, 8> Ops;
767       Ops.push_back(Chain);
768       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
769         Ops.push_back((*I)->getOperand(i));
770       }
771       DAG.UpdateNodeOperands(*I, Ops);
772     }
773     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
774   }
775   }
776 }
777
778 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
779                                                   SelectionDAG &DAG) const {
780   SmallVector<SDValue, 8> Args;
781   SDValue A = Op.getOperand(0);
782   SDValue B = Op.getOperand(1);
783
784   DAG.ExtractVectorElements(A, Args);
785   DAG.ExtractVectorElements(B, Args);
786
787   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
788 }
789
790 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
791                                                      SelectionDAG &DAG) const {
792
793   SmallVector<SDValue, 8> Args;
794   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
795   EVT VT = Op.getValueType();
796   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
797                             VT.getVectorNumElements());
798
799   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
800 }
801
802 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
803                                               SelectionDAG &DAG) const {
804
805   MachineFunction &MF = DAG.getMachineFunction();
806   const AMDGPUFrameLowering *TFL =
807    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
808
809   FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op);
810
811   unsigned FrameIndex = FIN->getIndex();
812   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
813   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
814                          Op.getValueType());
815 }
816
817 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
818     SelectionDAG &DAG) const {
819   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
820   SDLoc DL(Op);
821   EVT VT = Op.getValueType();
822
823   switch (IntrinsicID) {
824     default: return Op;
825     case AMDGPUIntrinsic::AMDGPU_abs:
826     case AMDGPUIntrinsic::AMDIL_abs: // Legacy name.
827       return LowerIntrinsicIABS(Op, DAG);
828     case AMDGPUIntrinsic::AMDGPU_lrp:
829       return LowerIntrinsicLRP(Op, DAG);
830     case AMDGPUIntrinsic::AMDGPU_fract:
831     case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
832       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
833
834     case AMDGPUIntrinsic::AMDGPU_clamp:
835     case AMDGPUIntrinsic::AMDIL_clamp: // Legacy name.
836       return DAG.getNode(AMDGPUISD::CLAMP, DL, VT,
837                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
838
839     case AMDGPUIntrinsic::AMDGPU_imax:
840       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
841                                                   Op.getOperand(2));
842     case AMDGPUIntrinsic::AMDGPU_umax:
843       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
844                                                   Op.getOperand(2));
845     case AMDGPUIntrinsic::AMDGPU_imin:
846       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
847                                                   Op.getOperand(2));
848     case AMDGPUIntrinsic::AMDGPU_umin:
849       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
850                                                   Op.getOperand(2));
851
852     case AMDGPUIntrinsic::AMDGPU_umul24:
853       return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT,
854                          Op.getOperand(1), Op.getOperand(2));
855
856     case AMDGPUIntrinsic::AMDGPU_imul24:
857       return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT,
858                          Op.getOperand(1), Op.getOperand(2));
859
860     case AMDGPUIntrinsic::AMDGPU_umad24:
861       return DAG.getNode(AMDGPUISD::MAD_U24, DL, VT,
862                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
863
864     case AMDGPUIntrinsic::AMDGPU_imad24:
865       return DAG.getNode(AMDGPUISD::MAD_I24, DL, VT,
866                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
867
868     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0:
869       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1));
870
871     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1:
872       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1));
873
874     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2:
875       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1));
876
877     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3:
878       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1));
879
880     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
881       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
882                          Op.getOperand(1),
883                          Op.getOperand(2),
884                          Op.getOperand(3));
885
886     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
887       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
888                          Op.getOperand(1),
889                          Op.getOperand(2),
890                          Op.getOperand(3));
891
892     case AMDGPUIntrinsic::AMDGPU_bfi:
893       return DAG.getNode(AMDGPUISD::BFI, DL, VT,
894                          Op.getOperand(1),
895                          Op.getOperand(2),
896                          Op.getOperand(3));
897
898     case AMDGPUIntrinsic::AMDGPU_bfm:
899       return DAG.getNode(AMDGPUISD::BFM, DL, VT,
900                          Op.getOperand(1),
901                          Op.getOperand(2));
902
903     case AMDGPUIntrinsic::AMDGPU_brev:
904       return DAG.getNode(AMDGPUISD::BREV, DL, VT, Op.getOperand(1));
905
906     case AMDGPUIntrinsic::AMDIL_exp: // Legacy name.
907       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
908
909     case AMDGPUIntrinsic::AMDIL_round_nearest: // Legacy name.
910       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
911   }
912 }
913
914 ///IABS(a) = SMAX(sub(0, a), a)
915 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
916                                                  SelectionDAG &DAG) const {
917   SDLoc DL(Op);
918   EVT VT = Op.getValueType();
919   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
920                                               Op.getOperand(1));
921
922   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
923 }
924
925 /// Linear Interpolation
926 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
927 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
928                                                 SelectionDAG &DAG) const {
929   SDLoc DL(Op);
930   EVT VT = Op.getValueType();
931   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
932                                 DAG.getConstantFP(1.0f, MVT::f32),
933                                 Op.getOperand(1));
934   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
935                                                     Op.getOperand(3));
936   return DAG.getNode(ISD::FADD, DL, VT,
937       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
938       OneSubAC);
939 }
940
941 /// \brief Generate Min/Max node
942 SDValue AMDGPUTargetLowering::CombineMinMax(SDNode *N,
943                                             SelectionDAG &DAG) const {
944   SDLoc DL(N);
945   EVT VT = N->getValueType(0);
946
947   SDValue LHS = N->getOperand(0);
948   SDValue RHS = N->getOperand(1);
949   SDValue True = N->getOperand(2);
950   SDValue False = N->getOperand(3);
951   SDValue CC = N->getOperand(4);
952
953   if (VT != MVT::f32 ||
954       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
955     return SDValue();
956   }
957
958   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
959   switch (CCOpcode) {
960   case ISD::SETOEQ:
961   case ISD::SETONE:
962   case ISD::SETUNE:
963   case ISD::SETNE:
964   case ISD::SETUEQ:
965   case ISD::SETEQ:
966   case ISD::SETFALSE:
967   case ISD::SETFALSE2:
968   case ISD::SETTRUE:
969   case ISD::SETTRUE2:
970   case ISD::SETUO:
971   case ISD::SETO:
972     llvm_unreachable("Operation should already be optimised!");
973   case ISD::SETULE:
974   case ISD::SETULT:
975   case ISD::SETOLE:
976   case ISD::SETOLT:
977   case ISD::SETLE:
978   case ISD::SETLT: {
979     unsigned Opc = (LHS == True) ? AMDGPUISD::FMIN : AMDGPUISD::FMAX;
980     return DAG.getNode(Opc, DL, VT, LHS, RHS);
981   }
982   case ISD::SETGT:
983   case ISD::SETGE:
984   case ISD::SETUGE:
985   case ISD::SETOGE:
986   case ISD::SETUGT:
987   case ISD::SETOGT: {
988     unsigned Opc = (LHS == True) ? AMDGPUISD::FMAX : AMDGPUISD::FMIN;
989     return DAG.getNode(Opc, DL, VT, LHS, RHS);
990   }
991   case ISD::SETCC_INVALID:
992     llvm_unreachable("Invalid setcc condcode!");
993   }
994   return SDValue();
995 }
996
997 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
998                                               SelectionDAG &DAG) const {
999   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
1000   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
1001   EVT EltVT = Op.getValueType().getVectorElementType();
1002   EVT PtrVT = Load->getBasePtr().getValueType();
1003   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
1004   SmallVector<SDValue, 8> Loads;
1005   SDLoc SL(Op);
1006
1007   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1008     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
1009                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
1010     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
1011                         Load->getChain(), Ptr,
1012                         MachinePointerInfo(Load->getMemOperand()->getValue()),
1013                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
1014                         Load->getAlignment()));
1015   }
1016   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(), Loads);
1017 }
1018
1019 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
1020                                                SelectionDAG &DAG) const {
1021   StoreSDNode *Store = cast<StoreSDNode>(Op);
1022   EVT MemVT = Store->getMemoryVT();
1023   unsigned MemBits = MemVT.getSizeInBits();
1024
1025   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
1026   // truncating store into an i32 store.
1027   // XXX: We could also handle optimize other vector bitwidths.
1028   if (!MemVT.isVector() || MemBits > 32) {
1029     return SDValue();
1030   }
1031
1032   SDLoc DL(Op);
1033   SDValue Value = Store->getValue();
1034   EVT VT = Value.getValueType();
1035   EVT ElemVT = VT.getVectorElementType();
1036   SDValue Ptr = Store->getBasePtr();
1037   EVT MemEltVT = MemVT.getVectorElementType();
1038   unsigned MemEltBits = MemEltVT.getSizeInBits();
1039   unsigned MemNumElements = MemVT.getVectorNumElements();
1040   unsigned PackedSize = MemVT.getStoreSizeInBits();
1041   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, MVT::i32);
1042
1043   assert(Value.getValueType().getScalarSizeInBits() >= 32);
1044
1045   SDValue PackedValue;
1046   for (unsigned i = 0; i < MemNumElements; ++i) {
1047     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
1048                               DAG.getConstant(i, MVT::i32));
1049     Elt = DAG.getZExtOrTrunc(Elt, DL, MVT::i32);
1050     Elt = DAG.getNode(ISD::AND, DL, MVT::i32, Elt, Mask); // getZeroExtendInReg
1051
1052     SDValue Shift = DAG.getConstant(MemEltBits * i, MVT::i32);
1053     Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt, Shift);
1054
1055     if (i == 0) {
1056       PackedValue = Elt;
1057     } else {
1058       PackedValue = DAG.getNode(ISD::OR, DL, MVT::i32, PackedValue, Elt);
1059     }
1060   }
1061
1062   if (PackedSize < 32) {
1063     EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), PackedSize);
1064     return DAG.getTruncStore(Store->getChain(), DL, PackedValue, Ptr,
1065                              Store->getMemOperand()->getPointerInfo(),
1066                              PackedVT,
1067                              Store->isNonTemporal(), Store->isVolatile(),
1068                              Store->getAlignment());
1069   }
1070
1071   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
1072                       Store->getMemOperand()->getPointerInfo(),
1073                       Store->isVolatile(),  Store->isNonTemporal(),
1074                       Store->getAlignment());
1075 }
1076
1077 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1078                                             SelectionDAG &DAG) const {
1079   StoreSDNode *Store = cast<StoreSDNode>(Op);
1080   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
1081   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
1082   EVT PtrVT = Store->getBasePtr().getValueType();
1083   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
1084   SDLoc SL(Op);
1085
1086   SmallVector<SDValue, 8> Chains;
1087
1088   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1089     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
1090                               Store->getValue(), DAG.getConstant(i, MVT::i32));
1091     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
1092                               Store->getBasePtr(),
1093                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
1094                                             PtrVT));
1095     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
1096                          MachinePointerInfo(Store->getMemOperand()->getValue()),
1097                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
1098                          Store->getAlignment()));
1099   }
1100   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains);
1101 }
1102
1103 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1104   SDLoc DL(Op);
1105   LoadSDNode *Load = cast<LoadSDNode>(Op);
1106   ISD::LoadExtType ExtType = Load->getExtensionType();
1107   EVT VT = Op.getValueType();
1108   EVT MemVT = Load->getMemoryVT();
1109
1110   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
1111     // We can do the extload to 32-bits, and then need to separately extend to
1112     // 64-bits.
1113
1114     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
1115                                        Load->getChain(),
1116                                        Load->getBasePtr(),
1117                                        MemVT,
1118                                        Load->getMemOperand());
1119     return DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32);
1120   }
1121
1122   if (ExtType == ISD::NON_EXTLOAD && VT.getSizeInBits() < 32) {
1123     assert(VT == MVT::i1 && "Only i1 non-extloads expected");
1124     // FIXME: Copied from PPC
1125     // First, load into 32 bits, then truncate to 1 bit.
1126
1127     SDValue Chain = Load->getChain();
1128     SDValue BasePtr = Load->getBasePtr();
1129     MachineMemOperand *MMO = Load->getMemOperand();
1130
1131     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1132                                    BasePtr, MVT::i8, MMO);
1133     return DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1134   }
1135
1136   // Lower loads constant address space global variable loads
1137   if (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
1138       isa<GlobalVariable>(
1139           GetUnderlyingObject(Load->getMemOperand()->getValue()))) {
1140
1141     SDValue Ptr = DAG.getZExtOrTrunc(Load->getBasePtr(), DL,
1142         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
1143     Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr,
1144         DAG.getConstant(2, MVT::i32));
1145     return DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1146                        Load->getChain(), Ptr,
1147                        DAG.getTargetConstant(0, MVT::i32), Op.getOperand(2));
1148   }
1149
1150   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
1151       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
1152     return SDValue();
1153
1154
1155   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
1156                             DAG.getConstant(2, MVT::i32));
1157   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1158                             Load->getChain(), Ptr,
1159                             DAG.getTargetConstant(0, MVT::i32),
1160                             Op.getOperand(2));
1161   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
1162                                 Load->getBasePtr(),
1163                                 DAG.getConstant(0x3, MVT::i32));
1164   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1165                                  DAG.getConstant(3, MVT::i32));
1166
1167   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
1168
1169   EVT MemEltVT = MemVT.getScalarType();
1170   if (ExtType == ISD::SEXTLOAD) {
1171     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
1172     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode);
1173   }
1174
1175   return DAG.getZeroExtendInReg(Ret, DL, MemEltVT);
1176 }
1177
1178 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1179   SDLoc DL(Op);
1180   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
1181   if (Result.getNode()) {
1182     return Result;
1183   }
1184
1185   StoreSDNode *Store = cast<StoreSDNode>(Op);
1186   SDValue Chain = Store->getChain();
1187   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1188        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
1189       Store->getValue().getValueType().isVector()) {
1190     return SplitVectorStore(Op, DAG);
1191   }
1192
1193   EVT MemVT = Store->getMemoryVT();
1194   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
1195       MemVT.bitsLT(MVT::i32)) {
1196     unsigned Mask = 0;
1197     if (Store->getMemoryVT() == MVT::i8) {
1198       Mask = 0xff;
1199     } else if (Store->getMemoryVT() == MVT::i16) {
1200       Mask = 0xffff;
1201     }
1202     SDValue BasePtr = Store->getBasePtr();
1203     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
1204                               DAG.getConstant(2, MVT::i32));
1205     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
1206                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
1207
1208     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
1209                                   DAG.getConstant(0x3, MVT::i32));
1210
1211     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1212                                    DAG.getConstant(3, MVT::i32));
1213
1214     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
1215                                     Store->getValue());
1216
1217     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
1218
1219     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1220                                        MaskedValue, ShiftAmt);
1221
1222     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
1223                                   ShiftAmt);
1224     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
1225                           DAG.getConstant(0xffffffff, MVT::i32));
1226     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1227
1228     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1229     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1230                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
1231   }
1232   return SDValue();
1233 }
1234
1235 SDValue AMDGPUTargetLowering::LowerSDIV24(SDValue Op, SelectionDAG &DAG) const {
1236   SDLoc DL(Op);
1237   EVT OVT = Op.getValueType();
1238   SDValue LHS = Op.getOperand(0);
1239   SDValue RHS = Op.getOperand(1);
1240   MVT INTTY;
1241   MVT FLTTY;
1242   if (!OVT.isVector()) {
1243     INTTY = MVT::i32;
1244     FLTTY = MVT::f32;
1245   } else if (OVT.getVectorNumElements() == 2) {
1246     INTTY = MVT::v2i32;
1247     FLTTY = MVT::v2f32;
1248   } else if (OVT.getVectorNumElements() == 4) {
1249     INTTY = MVT::v4i32;
1250     FLTTY = MVT::v4f32;
1251   }
1252   unsigned bitsize = OVT.getScalarType().getSizeInBits();
1253   // char|short jq = ia ^ ib;
1254   SDValue jq = DAG.getNode(ISD::XOR, DL, OVT, LHS, RHS);
1255
1256   // jq = jq >> (bitsize - 2)
1257   jq = DAG.getNode(ISD::SRA, DL, OVT, jq, DAG.getConstant(bitsize - 2, OVT));
1258
1259   // jq = jq | 0x1
1260   jq = DAG.getNode(ISD::OR, DL, OVT, jq, DAG.getConstant(1, OVT));
1261
1262   // jq = (int)jq
1263   jq = DAG.getSExtOrTrunc(jq, DL, INTTY);
1264
1265   // int ia = (int)LHS;
1266   SDValue ia = DAG.getSExtOrTrunc(LHS, DL, INTTY);
1267
1268   // int ib, (int)RHS;
1269   SDValue ib = DAG.getSExtOrTrunc(RHS, DL, INTTY);
1270
1271   // float fa = (float)ia;
1272   SDValue fa = DAG.getNode(ISD::SINT_TO_FP, DL, FLTTY, ia);
1273
1274   // float fb = (float)ib;
1275   SDValue fb = DAG.getNode(ISD::SINT_TO_FP, DL, FLTTY, ib);
1276
1277   // float fq = native_divide(fa, fb);
1278   SDValue fq = DAG.getNode(AMDGPUISD::DIV_INF, DL, FLTTY, fa, fb);
1279
1280   // fq = trunc(fq);
1281   fq = DAG.getNode(ISD::FTRUNC, DL, FLTTY, fq);
1282
1283   // float fqneg = -fq;
1284   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FLTTY, fq);
1285
1286   // float fr = mad(fqneg, fb, fa);
1287   SDValue fr = DAG.getNode(ISD::FADD, DL, FLTTY,
1288       DAG.getNode(ISD::MUL, DL, FLTTY, fqneg, fb), fa);
1289
1290   // int iq = (int)fq;
1291   SDValue iq = DAG.getNode(ISD::FP_TO_SINT, DL, INTTY, fq);
1292
1293   // fr = fabs(fr);
1294   fr = DAG.getNode(ISD::FABS, DL, FLTTY, fr);
1295
1296   // fb = fabs(fb);
1297   fb = DAG.getNode(ISD::FABS, DL, FLTTY, fb);
1298
1299   // int cv = fr >= fb;
1300   SDValue cv;
1301   if (INTTY == MVT::i32) {
1302     cv = DAG.getSetCC(DL, INTTY, fr, fb, ISD::SETOGE);
1303   } else {
1304     cv = DAG.getSetCC(DL, INTTY, fr, fb, ISD::SETOGE);
1305   }
1306   // jq = (cv ? jq : 0);
1307   jq = DAG.getNode(ISD::SELECT, DL, OVT, cv, jq,
1308       DAG.getConstant(0, OVT));
1309   // dst = iq + jq;
1310   iq = DAG.getSExtOrTrunc(iq, DL, OVT);
1311   iq = DAG.getNode(ISD::ADD, DL, OVT, iq, jq);
1312   return iq;
1313 }
1314
1315 SDValue AMDGPUTargetLowering::LowerSDIV32(SDValue Op, SelectionDAG &DAG) const {
1316   SDLoc DL(Op);
1317   EVT OVT = Op.getValueType();
1318   SDValue LHS = Op.getOperand(0);
1319   SDValue RHS = Op.getOperand(1);
1320   // The LowerSDIV32 function generates equivalent to the following IL.
1321   // mov r0, LHS
1322   // mov r1, RHS
1323   // ilt r10, r0, 0
1324   // ilt r11, r1, 0
1325   // iadd r0, r0, r10
1326   // iadd r1, r1, r11
1327   // ixor r0, r0, r10
1328   // ixor r1, r1, r11
1329   // udiv r0, r0, r1
1330   // ixor r10, r10, r11
1331   // iadd r0, r0, r10
1332   // ixor DST, r0, r10
1333
1334   // mov r0, LHS
1335   SDValue r0 = LHS;
1336
1337   // mov r1, RHS
1338   SDValue r1 = RHS;
1339
1340   // ilt r10, r0, 0
1341   SDValue r10 = DAG.getSelectCC(DL,
1342       r0, DAG.getConstant(0, OVT),
1343       DAG.getConstant(-1, OVT),
1344       DAG.getConstant(0, OVT),
1345       ISD::SETLT);
1346
1347   // ilt r11, r1, 0
1348   SDValue r11 = DAG.getSelectCC(DL,
1349       r1, DAG.getConstant(0, OVT),
1350       DAG.getConstant(-1, OVT),
1351       DAG.getConstant(0, OVT),
1352       ISD::SETLT);
1353
1354   // iadd r0, r0, r10
1355   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1356
1357   // iadd r1, r1, r11
1358   r1 = DAG.getNode(ISD::ADD, DL, OVT, r1, r11);
1359
1360   // ixor r0, r0, r10
1361   r0 = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1362
1363   // ixor r1, r1, r11
1364   r1 = DAG.getNode(ISD::XOR, DL, OVT, r1, r11);
1365
1366   // udiv r0, r0, r1
1367   r0 = DAG.getNode(ISD::UDIV, DL, OVT, r0, r1);
1368
1369   // ixor r10, r10, r11
1370   r10 = DAG.getNode(ISD::XOR, DL, OVT, r10, r11);
1371
1372   // iadd r0, r0, r10
1373   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1374
1375   // ixor DST, r0, r10
1376   SDValue DST = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1377   return DST;
1378 }
1379
1380 SDValue AMDGPUTargetLowering::LowerSDIV64(SDValue Op, SelectionDAG &DAG) const {
1381   return SDValue(Op.getNode(), 0);
1382 }
1383
1384 SDValue AMDGPUTargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
1385   EVT OVT = Op.getValueType().getScalarType();
1386
1387   if (OVT == MVT::i64)
1388     return LowerSDIV64(Op, DAG);
1389
1390   if (OVT.getScalarType() == MVT::i32)
1391     return LowerSDIV32(Op, DAG);
1392
1393   if (OVT == MVT::i16 || OVT == MVT::i8) {
1394     // FIXME: We should be checking for the masked bits. This isn't reached
1395     // because i8 and i16 are not legal types.
1396     return LowerSDIV24(Op, DAG);
1397   }
1398
1399   return SDValue(Op.getNode(), 0);
1400 }
1401
1402 SDValue AMDGPUTargetLowering::LowerSREM32(SDValue Op, SelectionDAG &DAG) const {
1403   SDLoc DL(Op);
1404   EVT OVT = Op.getValueType();
1405   SDValue LHS = Op.getOperand(0);
1406   SDValue RHS = Op.getOperand(1);
1407   // The LowerSREM32 function generates equivalent to the following IL.
1408   // mov r0, LHS
1409   // mov r1, RHS
1410   // ilt r10, r0, 0
1411   // ilt r11, r1, 0
1412   // iadd r0, r0, r10
1413   // iadd r1, r1, r11
1414   // ixor r0, r0, r10
1415   // ixor r1, r1, r11
1416   // udiv r20, r0, r1
1417   // umul r20, r20, r1
1418   // sub r0, r0, r20
1419   // iadd r0, r0, r10
1420   // ixor DST, r0, r10
1421
1422   // mov r0, LHS
1423   SDValue r0 = LHS;
1424
1425   // mov r1, RHS
1426   SDValue r1 = RHS;
1427
1428   // ilt r10, r0, 0
1429   SDValue r10 = DAG.getSetCC(DL, OVT, r0, DAG.getConstant(0, OVT), ISD::SETLT);
1430
1431   // ilt r11, r1, 0
1432   SDValue r11 = DAG.getSetCC(DL, OVT, r1, DAG.getConstant(0, OVT), ISD::SETLT);
1433
1434   // iadd r0, r0, r10
1435   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1436
1437   // iadd r1, r1, r11
1438   r1 = DAG.getNode(ISD::ADD, DL, OVT, r1, r11);
1439
1440   // ixor r0, r0, r10
1441   r0 = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1442
1443   // ixor r1, r1, r11
1444   r1 = DAG.getNode(ISD::XOR, DL, OVT, r1, r11);
1445
1446   // udiv r20, r0, r1
1447   SDValue r20 = DAG.getNode(ISD::UREM, DL, OVT, r0, r1);
1448
1449   // umul r20, r20, r1
1450   r20 = DAG.getNode(AMDGPUISD::UMUL, DL, OVT, r20, r1);
1451
1452   // sub r0, r0, r20
1453   r0 = DAG.getNode(ISD::SUB, DL, OVT, r0, r20);
1454
1455   // iadd r0, r0, r10
1456   r0 = DAG.getNode(ISD::ADD, DL, OVT, r0, r10);
1457
1458   // ixor DST, r0, r10
1459   SDValue DST = DAG.getNode(ISD::XOR, DL, OVT, r0, r10);
1460   return DST;
1461 }
1462
1463 SDValue AMDGPUTargetLowering::LowerSREM64(SDValue Op, SelectionDAG &DAG) const {
1464   return SDValue(Op.getNode(), 0);
1465 }
1466
1467 SDValue AMDGPUTargetLowering::LowerSREM(SDValue Op, SelectionDAG &DAG) const {
1468   EVT OVT = Op.getValueType();
1469
1470   if (OVT.getScalarType() == MVT::i64)
1471     return LowerSREM64(Op, DAG);
1472
1473   if (OVT.getScalarType() == MVT::i32)
1474     return LowerSREM32(Op, DAG);
1475
1476   return SDValue(Op.getNode(), 0);
1477 }
1478
1479 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1480                                            SelectionDAG &DAG) const {
1481   SDLoc DL(Op);
1482   EVT VT = Op.getValueType();
1483
1484   SDValue Num = Op.getOperand(0);
1485   SDValue Den = Op.getOperand(1);
1486
1487   // RCP =  URECIP(Den) = 2^32 / Den + e
1488   // e is rounding error.
1489   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1490
1491   // RCP_LO = umulo(RCP, Den) */
1492   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
1493
1494   // RCP_HI = mulhu (RCP, Den) */
1495   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1496
1497   // NEG_RCP_LO = -RCP_LO
1498   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
1499                                                      RCP_LO);
1500
1501   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1502   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1503                                            NEG_RCP_LO, RCP_LO,
1504                                            ISD::SETEQ);
1505   // Calculate the rounding error from the URECIP instruction
1506   // E = mulhu(ABS_RCP_LO, RCP)
1507   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1508
1509   // RCP_A_E = RCP + E
1510   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1511
1512   // RCP_S_E = RCP - E
1513   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1514
1515   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1516   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1517                                      RCP_A_E, RCP_S_E,
1518                                      ISD::SETEQ);
1519   // Quotient = mulhu(Tmp0, Num)
1520   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1521
1522   // Num_S_Remainder = Quotient * Den
1523   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
1524
1525   // Remainder = Num - Num_S_Remainder
1526   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1527
1528   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1529   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1530                                                  DAG.getConstant(-1, VT),
1531                                                  DAG.getConstant(0, VT),
1532                                                  ISD::SETUGE);
1533   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1534   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1535                                                   Num_S_Remainder,
1536                                                   DAG.getConstant(-1, VT),
1537                                                   DAG.getConstant(0, VT),
1538                                                   ISD::SETUGE);
1539   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1540   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1541                                                Remainder_GE_Zero);
1542
1543   // Calculate Division result:
1544
1545   // Quotient_A_One = Quotient + 1
1546   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1547                                                          DAG.getConstant(1, VT));
1548
1549   // Quotient_S_One = Quotient - 1
1550   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1551                                                          DAG.getConstant(1, VT));
1552
1553   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1554   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1555                                      Quotient, Quotient_A_One, ISD::SETEQ);
1556
1557   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1558   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1559                             Quotient_S_One, Div, ISD::SETEQ);
1560
1561   // Calculate Rem result:
1562
1563   // Remainder_S_Den = Remainder - Den
1564   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1565
1566   // Remainder_A_Den = Remainder + Den
1567   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1568
1569   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1570   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1571                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1572
1573   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1574   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1575                             Remainder_A_Den, Rem, ISD::SETEQ);
1576   SDValue Ops[2] = {
1577     Div,
1578     Rem
1579   };
1580   return DAG.getMergeValues(Ops, DL);
1581 }
1582
1583 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1584   SDLoc SL(Op);
1585   SDValue Src = Op.getOperand(0);
1586
1587   // result = trunc(src)
1588   // if (src > 0.0 && src != result)
1589   //   result += 1.0
1590
1591   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1592
1593   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1594   const SDValue One = DAG.getConstantFP(1.0, MVT::f64);
1595
1596   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1597
1598   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1599   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1600   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1601
1602   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1603   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1604 }
1605
1606 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1607   SDLoc SL(Op);
1608   SDValue Src = Op.getOperand(0);
1609
1610   assert(Op.getValueType() == MVT::f64);
1611
1612   const SDValue Zero = DAG.getConstant(0, MVT::i32);
1613   const SDValue One = DAG.getConstant(1, MVT::i32);
1614
1615   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1616
1617   // Extract the upper half, since this is where we will find the sign and
1618   // exponent.
1619   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1620
1621   const unsigned FractBits = 52;
1622   const unsigned ExpBits = 11;
1623
1624   // Extract the exponent.
1625   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_I32, SL, MVT::i32,
1626                                 Hi,
1627                                 DAG.getConstant(FractBits - 32, MVT::i32),
1628                                 DAG.getConstant(ExpBits, MVT::i32));
1629   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1630                             DAG.getConstant(1023, MVT::i32));
1631
1632   // Extract the sign bit.
1633   const SDValue SignBitMask = DAG.getConstant(1ul << 31, MVT::i32);
1634   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1635
1636   // Extend back to to 64-bits.
1637   SDValue SignBit64 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
1638                                   Zero, SignBit);
1639   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1640
1641   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1642   const SDValue FractMask = DAG.getConstant((1L << FractBits) - 1, MVT::i64);
1643
1644   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1645   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1646   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1647
1648   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::i32);
1649
1650   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, MVT::i32);
1651
1652   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1653   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1654
1655   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1656   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
1657
1658   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
1659 }
1660
1661 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
1662   SDLoc SL(Op);
1663   SDValue Src = Op.getOperand(0);
1664
1665   assert(Op.getValueType() == MVT::f64);
1666
1667   SDValue C1 = DAG.getConstantFP(0x1.0p+52, MVT::f64);
1668   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
1669
1670   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
1671   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
1672
1673   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
1674   SDValue C2 = DAG.getConstantFP(0x1.fffffffffffffp+51, MVT::f64);
1675
1676   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1677   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
1678
1679   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
1680 }
1681
1682 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
1683   SDLoc SL(Op);
1684   SDValue Src = Op.getOperand(0);
1685
1686   // result = trunc(src);
1687   // if (src < 0.0 && src != result)
1688   //   result += -1.0.
1689
1690   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1691
1692   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1693   const SDValue NegOne = DAG.getConstantFP(-1.0, MVT::f64);
1694
1695   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1696
1697   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
1698   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1699   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1700
1701   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
1702   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1703 }
1704
1705 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
1706                                                SelectionDAG &DAG) const {
1707   SDValue S0 = Op.getOperand(0);
1708   SDLoc DL(Op);
1709   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
1710     return SDValue();
1711
1712   // f32 uint_to_fp i64
1713   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1714                            DAG.getConstant(0, MVT::i32));
1715   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
1716   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1717                            DAG.getConstant(1, MVT::i32));
1718   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
1719   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
1720                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
1721   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
1722 }
1723
1724 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
1725                                                       unsigned BitsDiff,
1726                                                       SelectionDAG &DAG) const {
1727   MVT VT = Op.getSimpleValueType();
1728   SDLoc DL(Op);
1729   SDValue Shift = DAG.getConstant(BitsDiff, VT);
1730   // Shift left by 'Shift' bits.
1731   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
1732   // Signed shift Right by 'Shift' bits.
1733   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
1734 }
1735
1736 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1737                                                      SelectionDAG &DAG) const {
1738   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1739   MVT VT = Op.getSimpleValueType();
1740   MVT ScalarVT = VT.getScalarType();
1741
1742   if (!VT.isVector())
1743     return SDValue();
1744
1745   SDValue Src = Op.getOperand(0);
1746   SDLoc DL(Op);
1747
1748   // TODO: Don't scalarize on Evergreen?
1749   unsigned NElts = VT.getVectorNumElements();
1750   SmallVector<SDValue, 8> Args;
1751   DAG.ExtractVectorElements(Src, Args, 0, NElts);
1752
1753   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
1754   for (unsigned I = 0; I < NElts; ++I)
1755     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
1756
1757   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);
1758 }
1759
1760 //===----------------------------------------------------------------------===//
1761 // Custom DAG optimizations
1762 //===----------------------------------------------------------------------===//
1763
1764 static bool isU24(SDValue Op, SelectionDAG &DAG) {
1765   APInt KnownZero, KnownOne;
1766   EVT VT = Op.getValueType();
1767   DAG.computeKnownBits(Op, KnownZero, KnownOne);
1768
1769   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
1770 }
1771
1772 static bool isI24(SDValue Op, SelectionDAG &DAG) {
1773   EVT VT = Op.getValueType();
1774
1775   // In order for this to be a signed 24-bit value, bit 23, must
1776   // be a sign bit.
1777   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
1778                                      // as unsigned 24-bit values.
1779          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
1780 }
1781
1782 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
1783
1784   SelectionDAG &DAG = DCI.DAG;
1785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1786   EVT VT = Op.getValueType();
1787
1788   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
1789   APInt KnownZero, KnownOne;
1790   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
1791   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
1792     DCI.CommitTargetLoweringOpt(TLO);
1793 }
1794
1795 template <typename IntTy>
1796 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0,
1797                                uint32_t Offset, uint32_t Width) {
1798   if (Width + Offset < 32) {
1799     IntTy Result = (Src0 << (32 - Offset - Width)) >> (32 - Width);
1800     return DAG.getConstant(Result, MVT::i32);
1801   }
1802
1803   return DAG.getConstant(Src0 >> Offset, MVT::i32);
1804 }
1805
1806 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
1807                                             DAGCombinerInfo &DCI) const {
1808   SelectionDAG &DAG = DCI.DAG;
1809   SDLoc DL(N);
1810
1811   switch(N->getOpcode()) {
1812     default: break;
1813     case ISD::MUL: {
1814       EVT VT = N->getValueType(0);
1815       SDValue N0 = N->getOperand(0);
1816       SDValue N1 = N->getOperand(1);
1817       SDValue Mul;
1818
1819       // FIXME: Add support for 24-bit multiply with 64-bit output on SI.
1820       if (VT.isVector() || VT.getSizeInBits() > 32)
1821         break;
1822
1823       if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
1824         N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
1825         N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
1826         Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
1827       } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
1828         N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
1829         N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
1830         Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
1831       } else {
1832         break;
1833       }
1834
1835       // We need to use sext even for MUL_U24, because MUL_U24 is used
1836       // for signed multiply of 8 and 16-bit types.
1837       SDValue Reg = DAG.getSExtOrTrunc(Mul, DL, VT);
1838
1839       return Reg;
1840     }
1841     case AMDGPUISD::MUL_I24:
1842     case AMDGPUISD::MUL_U24: {
1843       SDValue N0 = N->getOperand(0);
1844       SDValue N1 = N->getOperand(1);
1845       simplifyI24(N0, DCI);
1846       simplifyI24(N1, DCI);
1847       return SDValue();
1848     }
1849     case ISD::SELECT_CC: {
1850       return CombineMinMax(N, DAG);
1851     }
1852   case AMDGPUISD::BFE_I32:
1853   case AMDGPUISD::BFE_U32: {
1854     assert(!N->getValueType(0).isVector() &&
1855            "Vector handling of BFE not implemented");
1856     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
1857     if (!Width)
1858       break;
1859
1860     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
1861     if (WidthVal == 0)
1862       return DAG.getConstant(0, MVT::i32);
1863
1864     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
1865     if (!Offset)
1866       break;
1867
1868     SDValue BitsFrom = N->getOperand(0);
1869     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
1870
1871     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
1872
1873     if (OffsetVal == 0) {
1874       // This is already sign / zero extended, so try to fold away extra BFEs.
1875       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
1876
1877       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
1878       if (OpSignBits >= SignBits)
1879         return BitsFrom;
1880
1881       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
1882       if (Signed) {
1883         // This is a sign_extend_inreg. Replace it to take advantage of existing
1884         // DAG Combines. If not eliminated, we will match back to BFE during
1885         // selection.
1886
1887         // TODO: The sext_inreg of extended types ends, although we can could
1888         // handle them in a single BFE.
1889         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
1890                            DAG.getValueType(SmallVT));
1891       }
1892
1893       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
1894     }
1895
1896     if (ConstantSDNode *Val = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
1897       if (Signed) {
1898         return constantFoldBFE<int32_t>(DAG,
1899                                         Val->getSExtValue(),
1900                                         OffsetVal,
1901                                         WidthVal);
1902       }
1903
1904       return constantFoldBFE<uint32_t>(DAG,
1905                                        Val->getZExtValue(),
1906                                        OffsetVal,
1907                                        WidthVal);
1908     }
1909
1910     APInt Demanded = APInt::getBitsSet(32,
1911                                        OffsetVal,
1912                                        OffsetVal + WidthVal);
1913
1914     if ((OffsetVal + WidthVal) >= 32) {
1915       SDValue ShiftVal = DAG.getConstant(OffsetVal, MVT::i32);
1916       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1917                          BitsFrom, ShiftVal);
1918     }
1919
1920     APInt KnownZero, KnownOne;
1921     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1922                                           !DCI.isBeforeLegalizeOps());
1923     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1924     if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
1925         TLI.SimplifyDemandedBits(BitsFrom, Demanded, KnownZero, KnownOne, TLO)) {
1926       DCI.CommitTargetLoweringOpt(TLO);
1927     }
1928
1929     break;
1930   }
1931   }
1932   return SDValue();
1933 }
1934
1935 //===----------------------------------------------------------------------===//
1936 // Helper functions
1937 //===----------------------------------------------------------------------===//
1938
1939 void AMDGPUTargetLowering::getOriginalFunctionArgs(
1940                                SelectionDAG &DAG,
1941                                const Function *F,
1942                                const SmallVectorImpl<ISD::InputArg> &Ins,
1943                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
1944
1945   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1946     if (Ins[i].ArgVT == Ins[i].VT) {
1947       OrigIns.push_back(Ins[i]);
1948       continue;
1949     }
1950
1951     EVT VT;
1952     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
1953       // Vector has been split into scalars.
1954       VT = Ins[i].ArgVT.getVectorElementType();
1955     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
1956                Ins[i].ArgVT.getVectorElementType() !=
1957                Ins[i].VT.getVectorElementType()) {
1958       // Vector elements have been promoted
1959       VT = Ins[i].ArgVT;
1960     } else {
1961       // Vector has been spilt into smaller vectors.
1962       VT = Ins[i].VT;
1963     }
1964
1965     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
1966                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
1967     OrigIns.push_back(Arg);
1968   }
1969 }
1970
1971 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
1972   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1973     return CFP->isExactlyValue(1.0);
1974   }
1975   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1976     return C->isAllOnesValue();
1977   }
1978   return false;
1979 }
1980
1981 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
1982   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1983     return CFP->getValueAPF().isZero();
1984   }
1985   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1986     return C->isNullValue();
1987   }
1988   return false;
1989 }
1990
1991 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1992                                                   const TargetRegisterClass *RC,
1993                                                    unsigned Reg, EVT VT) const {
1994   MachineFunction &MF = DAG.getMachineFunction();
1995   MachineRegisterInfo &MRI = MF.getRegInfo();
1996   unsigned VirtualRegister;
1997   if (!MRI.isLiveIn(Reg)) {
1998     VirtualRegister = MRI.createVirtualRegister(RC);
1999     MRI.addLiveIn(Reg, VirtualRegister);
2000   } else {
2001     VirtualRegister = MRI.getLiveInVirtReg(Reg);
2002   }
2003   return DAG.getRegister(VirtualRegister, VT);
2004 }
2005
2006 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
2007
2008 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
2009   switch (Opcode) {
2010   default: return nullptr;
2011   // AMDIL DAG nodes
2012   NODE_NAME_CASE(CALL);
2013   NODE_NAME_CASE(UMUL);
2014   NODE_NAME_CASE(DIV_INF);
2015   NODE_NAME_CASE(RET_FLAG);
2016   NODE_NAME_CASE(BRANCH_COND);
2017
2018   // AMDGPU DAG nodes
2019   NODE_NAME_CASE(DWORDADDR)
2020   NODE_NAME_CASE(FRACT)
2021   NODE_NAME_CASE(CLAMP)
2022   NODE_NAME_CASE(FMAX)
2023   NODE_NAME_CASE(SMAX)
2024   NODE_NAME_CASE(UMAX)
2025   NODE_NAME_CASE(FMIN)
2026   NODE_NAME_CASE(SMIN)
2027   NODE_NAME_CASE(UMIN)
2028   NODE_NAME_CASE(BFE_U32)
2029   NODE_NAME_CASE(BFE_I32)
2030   NODE_NAME_CASE(BFI)
2031   NODE_NAME_CASE(BFM)
2032   NODE_NAME_CASE(BREV)
2033   NODE_NAME_CASE(MUL_U24)
2034   NODE_NAME_CASE(MUL_I24)
2035   NODE_NAME_CASE(MAD_U24)
2036   NODE_NAME_CASE(MAD_I24)
2037   NODE_NAME_CASE(URECIP)
2038   NODE_NAME_CASE(DOT4)
2039   NODE_NAME_CASE(EXPORT)
2040   NODE_NAME_CASE(CONST_ADDRESS)
2041   NODE_NAME_CASE(REGISTER_LOAD)
2042   NODE_NAME_CASE(REGISTER_STORE)
2043   NODE_NAME_CASE(LOAD_CONSTANT)
2044   NODE_NAME_CASE(LOAD_INPUT)
2045   NODE_NAME_CASE(SAMPLE)
2046   NODE_NAME_CASE(SAMPLEB)
2047   NODE_NAME_CASE(SAMPLED)
2048   NODE_NAME_CASE(SAMPLEL)
2049   NODE_NAME_CASE(CVT_F32_UBYTE0)
2050   NODE_NAME_CASE(CVT_F32_UBYTE1)
2051   NODE_NAME_CASE(CVT_F32_UBYTE2)
2052   NODE_NAME_CASE(CVT_F32_UBYTE3)
2053   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
2054   NODE_NAME_CASE(STORE_MSKOR)
2055   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
2056   }
2057 }
2058
2059 static void computeKnownBitsForMinMax(const SDValue Op0,
2060                                       const SDValue Op1,
2061                                       APInt &KnownZero,
2062                                       APInt &KnownOne,
2063                                       const SelectionDAG &DAG,
2064                                       unsigned Depth) {
2065   APInt Op0Zero, Op0One;
2066   APInt Op1Zero, Op1One;
2067   DAG.computeKnownBits(Op0, Op0Zero, Op0One, Depth);
2068   DAG.computeKnownBits(Op1, Op1Zero, Op1One, Depth);
2069
2070   KnownZero = Op0Zero & Op1Zero;
2071   KnownOne = Op0One & Op1One;
2072 }
2073
2074 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
2075   const SDValue Op,
2076   APInt &KnownZero,
2077   APInt &KnownOne,
2078   const SelectionDAG &DAG,
2079   unsigned Depth) const {
2080
2081   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
2082
2083   APInt KnownZero2;
2084   APInt KnownOne2;
2085   unsigned Opc = Op.getOpcode();
2086
2087   switch (Opc) {
2088   default:
2089     break;
2090   case ISD::INTRINSIC_WO_CHAIN: {
2091     // FIXME: The intrinsic should just use the node.
2092     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
2093     case AMDGPUIntrinsic::AMDGPU_imax:
2094     case AMDGPUIntrinsic::AMDGPU_umax:
2095     case AMDGPUIntrinsic::AMDGPU_imin:
2096     case AMDGPUIntrinsic::AMDGPU_umin:
2097       computeKnownBitsForMinMax(Op.getOperand(1), Op.getOperand(2),
2098                                 KnownZero, KnownOne, DAG, Depth);
2099       break;
2100     default:
2101       break;
2102     }
2103
2104     break;
2105   }
2106   case AMDGPUISD::SMAX:
2107   case AMDGPUISD::UMAX:
2108   case AMDGPUISD::SMIN:
2109   case AMDGPUISD::UMIN:
2110     computeKnownBitsForMinMax(Op.getOperand(0), Op.getOperand(1),
2111                               KnownZero, KnownOne, DAG, Depth);
2112     break;
2113
2114   case AMDGPUISD::BFE_I32:
2115   case AMDGPUISD::BFE_U32: {
2116     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2117     if (!CWidth)
2118       return;
2119
2120     unsigned BitWidth = 32;
2121     uint32_t Width = CWidth->getZExtValue() & 0x1f;
2122     if (Width == 0) {
2123       KnownZero = APInt::getAllOnesValue(BitWidth);
2124       KnownOne = APInt::getNullValue(BitWidth);
2125       return;
2126     }
2127
2128     // FIXME: This could do a lot more. If offset is 0, should be the same as
2129     // sign_extend_inreg implementation, but that involves duplicating it.
2130     if (Opc == AMDGPUISD::BFE_I32)
2131       KnownOne = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2132     else
2133       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2134
2135     break;
2136   }
2137   }
2138 }
2139
2140 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
2141   SDValue Op,
2142   const SelectionDAG &DAG,
2143   unsigned Depth) const {
2144   switch (Op.getOpcode()) {
2145   case AMDGPUISD::BFE_I32: {
2146     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2147     if (!Width)
2148       return 1;
2149
2150     unsigned SignBits = 32 - Width->getZExtValue() + 1;
2151     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2152     if (!Offset || !Offset->isNullValue())
2153       return SignBits;
2154
2155     // TODO: Could probably figure something out with non-0 offsets.
2156     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2157     return std::max(SignBits, Op0SignBits);
2158   }
2159
2160   case AMDGPUISD::BFE_U32: {
2161     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2162     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
2163   }
2164
2165   default:
2166     return 1;
2167   }
2168 }