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