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