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