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