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