R600/SI: Fix unreachable with a sext_in_reg to an illegal type.
[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
32 using namespace llvm;
33 static bool allocateStack(unsigned ValNo, MVT ValVT, MVT LocVT,
34                       CCValAssign::LocInfo LocInfo,
35                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
36   unsigned Offset = State.AllocateStack(ValVT.getStoreSize(),
37                                         ArgFlags.getOrigAlign());
38   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
39
40   return true;
41 }
42
43 #include "AMDGPUGenCallingConv.inc"
44
45 AMDGPUTargetLowering::AMDGPUTargetLowering(TargetMachine &TM) :
46   TargetLowering(TM, new TargetLoweringObjectFileELF()) {
47
48   Subtarget = &TM.getSubtarget<AMDGPUSubtarget>();
49
50   // Initialize target lowering borrowed from AMDIL
51   InitAMDILLowering();
52
53   // We need to custom lower some of the intrinsics
54   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
55
56   // Library functions.  These default to Expand, but we have instructions
57   // for them.
58   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
59   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
60   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
61   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
62   setOperationAction(ISD::FABS,   MVT::f32, Legal);
63   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
64   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
65   setOperationAction(ISD::FROUND, MVT::f32, Legal);
66   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
67
68   // The hardware supports ROTR, but not ROTL
69   setOperationAction(ISD::ROTL, MVT::i32, Expand);
70
71   // Lower floating point store/load to integer store/load to reduce the number
72   // of patterns in tablegen.
73   setOperationAction(ISD::STORE, MVT::f32, Promote);
74   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
75
76   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
77   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
78
79   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
80   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
81
82   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
83   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
84
85   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
86   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
87
88   setOperationAction(ISD::STORE, MVT::f64, Promote);
89   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
90
91   // Custom lowering of vector stores is required for local address space
92   // stores.
93   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
94   // XXX: Native v2i32 local address space stores are possible, but not
95   // currently implemented.
96   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
97
98   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
99   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
100   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
101
102   // XXX: This can be change to Custom, once ExpandVectorStores can
103   // handle 64-bit stores.
104   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
105
106   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
107   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
108   setTruncStoreAction(MVT::v4i64, MVT::v4i1, Expand);
109
110
111   setOperationAction(ISD::LOAD, MVT::f32, Promote);
112   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
113
114   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
115   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
116
117   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
118   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
119
120   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
121   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
122
123   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
124   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
125
126   setOperationAction(ISD::LOAD, MVT::f64, Promote);
127   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::i64);
128
129   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
130   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
131   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
132   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
133   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
134   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
135   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
136   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
137   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
138   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
139
140   setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Expand);
141   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Expand);
142   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i8, Expand);
143   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
144   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Expand);
145   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Expand);
146   setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Expand);
147   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Expand);
148   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, Expand);
149   setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Expand);
150   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Expand);
151   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, Expand);
152
153   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
154
155   setOperationAction(ISD::FNEG, MVT::v2f32, Expand);
156   setOperationAction(ISD::FNEG, MVT::v4f32, Expand);
157
158   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
159
160   setOperationAction(ISD::MUL, MVT::i64, Expand);
161
162   setOperationAction(ISD::UDIV, MVT::i32, Expand);
163   setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
164   setOperationAction(ISD::UREM, MVT::i32, Expand);
165   setOperationAction(ISD::VSELECT, MVT::v2f32, Expand);
166   setOperationAction(ISD::VSELECT, MVT::v4f32, Expand);
167
168   static const MVT::SimpleValueType IntTypes[] = {
169     MVT::v2i32, MVT::v4i32
170   };
171   const size_t NumIntTypes = array_lengthof(IntTypes);
172
173   for (unsigned int x  = 0; x < NumIntTypes; ++x) {
174     MVT::SimpleValueType VT = IntTypes[x];
175     //Expand the following operations for the current type by default
176     setOperationAction(ISD::ADD,  VT, Expand);
177     setOperationAction(ISD::AND,  VT, Expand);
178     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
179     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
180     setOperationAction(ISD::MUL,  VT, Expand);
181     setOperationAction(ISD::OR,   VT, Expand);
182     setOperationAction(ISD::SHL,  VT, Expand);
183     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
184     setOperationAction(ISD::SRL,  VT, Expand);
185     setOperationAction(ISD::SRA,  VT, Expand);
186     setOperationAction(ISD::SUB,  VT, Expand);
187     setOperationAction(ISD::UDIV, VT, Expand);
188     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
189     setOperationAction(ISD::UREM, VT, Expand);
190     setOperationAction(ISD::SELECT, VT, Expand);
191     setOperationAction(ISD::VSELECT, VT, Expand);
192     setOperationAction(ISD::XOR,  VT, Expand);
193   }
194
195   static const MVT::SimpleValueType FloatTypes[] = {
196     MVT::v2f32, MVT::v4f32
197   };
198   const size_t NumFloatTypes = array_lengthof(FloatTypes);
199
200   for (unsigned int x = 0; x < NumFloatTypes; ++x) {
201     MVT::SimpleValueType VT = FloatTypes[x];
202     setOperationAction(ISD::FABS, VT, Expand);
203     setOperationAction(ISD::FADD, VT, Expand);
204     setOperationAction(ISD::FDIV, VT, Expand);
205     setOperationAction(ISD::FPOW, VT, Expand);
206     setOperationAction(ISD::FFLOOR, VT, Expand);
207     setOperationAction(ISD::FTRUNC, VT, Expand);
208     setOperationAction(ISD::FMUL, VT, Expand);
209     setOperationAction(ISD::FRINT, VT, Expand);
210     setOperationAction(ISD::FSQRT, VT, Expand);
211     setOperationAction(ISD::FSUB, VT, Expand);
212     setOperationAction(ISD::SELECT, VT, Expand);
213   }
214
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
218
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Custom);
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
221   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
222
223   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Custom);
224   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
225   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
226
227   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
228
229   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
230 }
231
232 //===----------------------------------------------------------------------===//
233 // Target Information
234 //===----------------------------------------------------------------------===//
235
236 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
237   return MVT::i32;
238 }
239
240 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
241                                                    EVT CastTy) const {
242   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
243     return true;
244
245   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
246   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
247
248   return ((LScalarSize <= CastScalarSize) ||
249           (CastScalarSize >= 32) ||
250           (LScalarSize < 32));
251 }
252
253 //===---------------------------------------------------------------------===//
254 // Target Properties
255 //===---------------------------------------------------------------------===//
256
257 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
258   assert(VT.isFloatingPoint());
259   return VT == MVT::f32;
260 }
261
262 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
263   assert(VT.isFloatingPoint());
264   return VT == MVT::f32;
265 }
266
267 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
268   // Truncate is just accessing a subregister.
269   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
270 }
271
272 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
273   // Truncate is just accessing a subregister.
274   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
275          (Dest->getPrimitiveSizeInBits() % 32 == 0);
276 }
277
278 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
279   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
280   // limited number of native 64-bit operations. Shrinking an operation to fit
281   // in a single 32-bit register should always be helpful. As currently used,
282   // this is much less general than the name suggests, and is only used in
283   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
284   // not profitable, and may actually be harmful.
285   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
286 }
287
288 //===---------------------------------------------------------------------===//
289 // TargetLowering Callbacks
290 //===---------------------------------------------------------------------===//
291
292 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
293                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
294
295   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
296 }
297
298 SDValue AMDGPUTargetLowering::LowerReturn(
299                                      SDValue Chain,
300                                      CallingConv::ID CallConv,
301                                      bool isVarArg,
302                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
303                                      const SmallVectorImpl<SDValue> &OutVals,
304                                      SDLoc DL, SelectionDAG &DAG) const {
305   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
306 }
307
308 //===---------------------------------------------------------------------===//
309 // Target specific lowering
310 //===---------------------------------------------------------------------===//
311
312 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG)
313     const {
314   switch (Op.getOpcode()) {
315   default:
316     Op.getNode()->dump();
317     llvm_unreachable("Custom lowering code for this"
318                      "instruction is not implemented yet!");
319     break;
320   // AMDIL DAG lowering
321   case ISD::SDIV: return LowerSDIV(Op, DAG);
322   case ISD::SREM: return LowerSREM(Op, DAG);
323   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
324   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
325   // AMDGPU DAG lowering
326   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
327   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
328   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
329   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
330   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
331   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
332   }
333   return Op;
334 }
335
336 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
337                                               SmallVectorImpl<SDValue> &Results,
338                                               SelectionDAG &DAG) const {
339   switch (N->getOpcode()) {
340   case ISD::SIGN_EXTEND_INREG:
341     // Different parts of legalization seem to interpret which type of
342     // sign_extend_inreg is the one to check for custom lowering. The extended
343     // from type is what really matters, but some places check for custom
344     // lowering of the result type. This results in trying to use
345     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
346     // nothing here and let the illegal result integer be handled normally.
347     return;
348
349   default:
350     return;
351   }
352 }
353
354 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
355                                                        const GlobalValue *GV,
356                                                        const SDValue &InitPtr,
357                                                        SDValue Chain,
358                                                        SelectionDAG &DAG) const {
359   const DataLayout *TD = getTargetMachine().getDataLayout();
360   SDLoc DL(InitPtr);
361   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
362     EVT VT = EVT::getEVT(CI->getType());
363     PointerType *PtrTy = PointerType::get(CI->getType(), 0);
364     return DAG.getStore(Chain, DL,  DAG.getConstant(*CI, VT), InitPtr,
365                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
366                  TD->getPrefTypeAlignment(CI->getType()));
367   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
368     EVT VT = EVT::getEVT(CFP->getType());
369     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
370     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
371                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
372                  TD->getPrefTypeAlignment(CFP->getType()));
373   } else if (Init->getType()->isAggregateType()) {
374     EVT PtrVT = InitPtr.getValueType();
375     unsigned NumElements = Init->getType()->getArrayNumElements();
376     SmallVector<SDValue, 8> Chains;
377     for (unsigned i = 0; i < NumElements; ++i) {
378       SDValue Offset = DAG.getConstant(i * TD->getTypeAllocSize(
379           Init->getType()->getArrayElementType()), PtrVT);
380       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
381       Chains.push_back(LowerConstantInitializer(Init->getAggregateElement(i),
382                        GV, Ptr, Chain, DAG));
383     }
384     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
385                        Chains.size());
386   } else {
387     Init->dump();
388     llvm_unreachable("Unhandled constant initializer");
389   }
390 }
391
392 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
393                                                  SDValue Op,
394                                                  SelectionDAG &DAG) const {
395
396   const DataLayout *TD = getTargetMachine().getDataLayout();
397   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
398   const GlobalValue *GV = G->getGlobal();
399
400   switch (G->getAddressSpace()) {
401   default: llvm_unreachable("Global Address lowering not implemented for this "
402                             "address space");
403   case AMDGPUAS::LOCAL_ADDRESS: {
404     // XXX: What does the value of G->getOffset() mean?
405     assert(G->getOffset() == 0 &&
406          "Do not know what to do with an non-zero offset");
407
408     unsigned Offset;
409     if (MFI->LocalMemoryObjects.count(GV) == 0) {
410       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
411       Offset = MFI->LDSSize;
412       MFI->LocalMemoryObjects[GV] = Offset;
413       // XXX: Account for alignment?
414       MFI->LDSSize += Size;
415     } else {
416       Offset = MFI->LocalMemoryObjects[GV];
417     }
418
419     return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
420   }
421   case AMDGPUAS::CONSTANT_ADDRESS: {
422     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
423     Type *EltType = GV->getType()->getElementType();
424     unsigned Size = TD->getTypeAllocSize(EltType);
425     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
426
427     const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV);
428     const Constant *Init = Var->getInitializer();
429     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
430     SDValue InitPtr = DAG.getFrameIndex(FI,
431         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
432     SmallVector<SDNode*, 8> WorkList;
433
434     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
435                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
436       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
437         continue;
438       WorkList.push_back(*I);
439     }
440     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
441     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
442                                            E = WorkList.end(); I != E; ++I) {
443       SmallVector<SDValue, 8> Ops;
444       Ops.push_back(Chain);
445       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
446         Ops.push_back((*I)->getOperand(i));
447       }
448       DAG.UpdateNodeOperands(*I, &Ops[0], Ops.size());
449     }
450     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op),
451         getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
452   }
453   }
454 }
455
456 void AMDGPUTargetLowering::ExtractVectorElements(SDValue Op, SelectionDAG &DAG,
457                                          SmallVectorImpl<SDValue> &Args,
458                                          unsigned Start,
459                                          unsigned Count) const {
460   EVT VT = Op.getValueType();
461   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
462     Args.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
463                                VT.getVectorElementType(),
464                                Op, DAG.getConstant(i, MVT::i32)));
465   }
466 }
467
468 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
469                                                   SelectionDAG &DAG) const {
470   SmallVector<SDValue, 8> Args;
471   SDValue A = Op.getOperand(0);
472   SDValue B = Op.getOperand(1);
473
474   ExtractVectorElements(A, DAG, Args, 0,
475                         A.getValueType().getVectorNumElements());
476   ExtractVectorElements(B, DAG, Args, 0,
477                         B.getValueType().getVectorNumElements());
478
479   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
480                      &Args[0], Args.size());
481 }
482
483 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
484                                                      SelectionDAG &DAG) const {
485
486   SmallVector<SDValue, 8> Args;
487   EVT VT = Op.getValueType();
488   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
489   ExtractVectorElements(Op.getOperand(0), DAG, Args, Start,
490                         VT.getVectorNumElements());
491
492   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
493                      &Args[0], Args.size());
494 }
495
496 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
497                                               SelectionDAG &DAG) const {
498
499   MachineFunction &MF = DAG.getMachineFunction();
500   const AMDGPUFrameLowering *TFL =
501    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
502
503   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
504   assert(FIN);
505
506   unsigned FrameIndex = FIN->getIndex();
507   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
508   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
509                          Op.getValueType());
510 }
511
512 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
513     SelectionDAG &DAG) const {
514   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
515   SDLoc DL(Op);
516   EVT VT = Op.getValueType();
517
518   switch (IntrinsicID) {
519     default: return Op;
520     case AMDGPUIntrinsic::AMDIL_abs:
521       return LowerIntrinsicIABS(Op, DAG);
522     case AMDGPUIntrinsic::AMDIL_exp:
523       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
524     case AMDGPUIntrinsic::AMDGPU_lrp:
525       return LowerIntrinsicLRP(Op, DAG);
526     case AMDGPUIntrinsic::AMDIL_fraction:
527       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
528     case AMDGPUIntrinsic::AMDIL_max:
529       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, Op.getOperand(1),
530                                                   Op.getOperand(2));
531     case AMDGPUIntrinsic::AMDGPU_imax:
532       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
533                                                   Op.getOperand(2));
534     case AMDGPUIntrinsic::AMDGPU_umax:
535       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
536                                                   Op.getOperand(2));
537     case AMDGPUIntrinsic::AMDIL_min:
538       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, Op.getOperand(1),
539                                                   Op.getOperand(2));
540     case AMDGPUIntrinsic::AMDGPU_imin:
541       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
542                                                   Op.getOperand(2));
543     case AMDGPUIntrinsic::AMDGPU_umin:
544       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
545                                                   Op.getOperand(2));
546     case AMDGPUIntrinsic::AMDIL_round_nearest:
547       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
548   }
549 }
550
551 ///IABS(a) = SMAX(sub(0, a), a)
552 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
553     SelectionDAG &DAG) const {
554
555   SDLoc DL(Op);
556   EVT VT = Op.getValueType();
557   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
558                                               Op.getOperand(1));
559
560   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
561 }
562
563 /// Linear Interpolation
564 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
565 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
566     SelectionDAG &DAG) const {
567   SDLoc DL(Op);
568   EVT VT = Op.getValueType();
569   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
570                                 DAG.getConstantFP(1.0f, MVT::f32),
571                                 Op.getOperand(1));
572   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
573                                                     Op.getOperand(3));
574   return DAG.getNode(ISD::FADD, DL, VT,
575       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
576       OneSubAC);
577 }
578
579 /// \brief Generate Min/Max node
580 SDValue AMDGPUTargetLowering::LowerMinMax(SDValue Op,
581     SelectionDAG &DAG) const {
582   SDLoc DL(Op);
583   EVT VT = Op.getValueType();
584
585   SDValue LHS = Op.getOperand(0);
586   SDValue RHS = Op.getOperand(1);
587   SDValue True = Op.getOperand(2);
588   SDValue False = Op.getOperand(3);
589   SDValue CC = Op.getOperand(4);
590
591   if (VT != MVT::f32 ||
592       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
593     return SDValue();
594   }
595
596   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
597   switch (CCOpcode) {
598   case ISD::SETOEQ:
599   case ISD::SETONE:
600   case ISD::SETUNE:
601   case ISD::SETNE:
602   case ISD::SETUEQ:
603   case ISD::SETEQ:
604   case ISD::SETFALSE:
605   case ISD::SETFALSE2:
606   case ISD::SETTRUE:
607   case ISD::SETTRUE2:
608   case ISD::SETUO:
609   case ISD::SETO:
610     llvm_unreachable("Operation should already be optimised!");
611   case ISD::SETULE:
612   case ISD::SETULT:
613   case ISD::SETOLE:
614   case ISD::SETOLT:
615   case ISD::SETLE:
616   case ISD::SETLT: {
617     if (LHS == True)
618       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
619     else
620       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
621   }
622   case ISD::SETGT:
623   case ISD::SETGE:
624   case ISD::SETUGE:
625   case ISD::SETOGE:
626   case ISD::SETUGT:
627   case ISD::SETOGT: {
628     if (LHS == True)
629       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
630     else
631       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
632   }
633   case ISD::SETCC_INVALID:
634     llvm_unreachable("Invalid setcc condcode!");
635   }
636   return Op;
637 }
638
639 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
640                                               SelectionDAG &DAG) const {
641   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
642   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
643   EVT EltVT = Op.getValueType().getVectorElementType();
644   EVT PtrVT = Load->getBasePtr().getValueType();
645   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
646   SmallVector<SDValue, 8> Loads;
647   SDLoc SL(Op);
648
649   for (unsigned i = 0, e = NumElts; i != e; ++i) {
650     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
651                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
652     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
653                         Load->getChain(), Ptr,
654                         MachinePointerInfo(Load->getMemOperand()->getValue()),
655                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
656                         Load->getAlignment()));
657   }
658   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(),
659                      Loads.data(), Loads.size());
660 }
661
662 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
663                                                SelectionDAG &DAG) const {
664   StoreSDNode *Store = dyn_cast<StoreSDNode>(Op);
665   EVT MemVT = Store->getMemoryVT();
666   unsigned MemBits = MemVT.getSizeInBits();
667
668   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
669   // truncating store into an i32 store.
670   // XXX: We could also handle optimize other vector bitwidths.
671   if (!MemVT.isVector() || MemBits > 32) {
672     return SDValue();
673   }
674
675   SDLoc DL(Op);
676   const SDValue &Value = Store->getValue();
677   EVT VT = Value.getValueType();
678   const SDValue &Ptr = Store->getBasePtr();
679   EVT MemEltVT = MemVT.getVectorElementType();
680   unsigned MemEltBits = MemEltVT.getSizeInBits();
681   unsigned MemNumElements = MemVT.getVectorNumElements();
682   EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
683   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, PackedVT);
684
685   SDValue PackedValue;
686   for (unsigned i = 0; i < MemNumElements; ++i) {
687     EVT ElemVT = VT.getVectorElementType();
688     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
689                               DAG.getConstant(i, MVT::i32));
690     Elt = DAG.getZExtOrTrunc(Elt, DL, PackedVT);
691     Elt = DAG.getNode(ISD::AND, DL, PackedVT, Elt, Mask);
692     SDValue Shift = DAG.getConstant(MemEltBits * i, PackedVT);
693     Elt = DAG.getNode(ISD::SHL, DL, PackedVT, Elt, Shift);
694     if (i == 0) {
695       PackedValue = Elt;
696     } else {
697       PackedValue = DAG.getNode(ISD::OR, DL, PackedVT, PackedValue, Elt);
698     }
699   }
700   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
701                       MachinePointerInfo(Store->getMemOperand()->getValue()),
702                       Store->isVolatile(),  Store->isNonTemporal(),
703                       Store->getAlignment());
704 }
705
706 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
707                                             SelectionDAG &DAG) const {
708   StoreSDNode *Store = cast<StoreSDNode>(Op);
709   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
710   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
711   EVT PtrVT = Store->getBasePtr().getValueType();
712   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
713   SDLoc SL(Op);
714
715   SmallVector<SDValue, 8> Chains;
716
717   for (unsigned i = 0, e = NumElts; i != e; ++i) {
718     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
719                               Store->getValue(), DAG.getConstant(i, MVT::i32));
720     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
721                               Store->getBasePtr(),
722                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
723                                             PtrVT));
724     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
725                          MachinePointerInfo(Store->getMemOperand()->getValue()),
726                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
727                          Store->getAlignment()));
728   }
729   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, &Chains[0], NumElts);
730 }
731
732 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
733   SDLoc DL(Op);
734   LoadSDNode *Load = cast<LoadSDNode>(Op);
735   ISD::LoadExtType ExtType = Load->getExtensionType();
736   EVT VT = Op.getValueType();
737   EVT MemVT = Load->getMemoryVT();
738
739   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
740     // We can do the extload to 32-bits, and then need to separately extend to
741     // 64-bits.
742
743     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
744                                        Load->getChain(),
745                                        Load->getBasePtr(),
746                                        MemVT,
747                                        Load->getMemOperand());
748     return DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32);
749   }
750
751   // Lower loads constant address space global variable loads
752   if (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
753       isa<GlobalVariable>(GetUnderlyingObject(Load->getPointerInfo().V))) {
754
755     SDValue Ptr = DAG.getZExtOrTrunc(Load->getBasePtr(), DL,
756         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
757     Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr,
758         DAG.getConstant(2, MVT::i32));
759     return DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
760                        Load->getChain(), Ptr,
761                        DAG.getTargetConstant(0, MVT::i32), Op.getOperand(2));
762   }
763
764   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
765       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
766     return SDValue();
767
768
769   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
770                             DAG.getConstant(2, MVT::i32));
771   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
772                             Load->getChain(), Ptr,
773                             DAG.getTargetConstant(0, MVT::i32),
774                             Op.getOperand(2));
775   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
776                                 Load->getBasePtr(),
777                                 DAG.getConstant(0x3, MVT::i32));
778   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
779                                  DAG.getConstant(3, MVT::i32));
780
781   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
782
783   EVT MemEltVT = MemVT.getScalarType();
784   if (ExtType == ISD::SEXTLOAD) {
785     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
786     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode);
787   }
788
789   return DAG.getZeroExtendInReg(Ret, DL, MemEltVT);
790 }
791
792 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
793   SDLoc DL(Op);
794   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
795   if (Result.getNode()) {
796     return Result;
797   }
798
799   StoreSDNode *Store = cast<StoreSDNode>(Op);
800   SDValue Chain = Store->getChain();
801   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
802        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
803       Store->getValue().getValueType().isVector()) {
804     return SplitVectorStore(Op, DAG);
805   }
806
807   EVT MemVT = Store->getMemoryVT();
808   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
809       MemVT.bitsLT(MVT::i32)) {
810     unsigned Mask = 0;
811     if (Store->getMemoryVT() == MVT::i8) {
812       Mask = 0xff;
813     } else if (Store->getMemoryVT() == MVT::i16) {
814       Mask = 0xffff;
815     }
816     SDValue BasePtr = Store->getBasePtr();
817     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
818                               DAG.getConstant(2, MVT::i32));
819     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
820                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
821
822     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
823                                   DAG.getConstant(0x3, MVT::i32));
824
825     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
826                                    DAG.getConstant(3, MVT::i32));
827
828     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
829                                     Store->getValue());
830
831     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
832
833     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
834                                        MaskedValue, ShiftAmt);
835
836     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
837                                   ShiftAmt);
838     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
839                           DAG.getConstant(0xffffffff, MVT::i32));
840     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
841
842     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
843     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
844                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
845   }
846   return SDValue();
847 }
848
849 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
850     SelectionDAG &DAG) const {
851   SDLoc DL(Op);
852   EVT VT = Op.getValueType();
853
854   SDValue Num = Op.getOperand(0);
855   SDValue Den = Op.getOperand(1);
856
857   SmallVector<SDValue, 8> Results;
858
859   // RCP =  URECIP(Den) = 2^32 / Den + e
860   // e is rounding error.
861   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
862
863   // RCP_LO = umulo(RCP, Den) */
864   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
865
866   // RCP_HI = mulhu (RCP, Den) */
867   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
868
869   // NEG_RCP_LO = -RCP_LO
870   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
871                                                      RCP_LO);
872
873   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
874   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
875                                            NEG_RCP_LO, RCP_LO,
876                                            ISD::SETEQ);
877   // Calculate the rounding error from the URECIP instruction
878   // E = mulhu(ABS_RCP_LO, RCP)
879   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
880
881   // RCP_A_E = RCP + E
882   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
883
884   // RCP_S_E = RCP - E
885   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
886
887   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
888   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
889                                      RCP_A_E, RCP_S_E,
890                                      ISD::SETEQ);
891   // Quotient = mulhu(Tmp0, Num)
892   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
893
894   // Num_S_Remainder = Quotient * Den
895   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
896
897   // Remainder = Num - Num_S_Remainder
898   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
899
900   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
901   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
902                                                  DAG.getConstant(-1, VT),
903                                                  DAG.getConstant(0, VT),
904                                                  ISD::SETUGE);
905   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
906   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
907                                                   Num_S_Remainder,
908                                                   DAG.getConstant(-1, VT),
909                                                   DAG.getConstant(0, VT),
910                                                   ISD::SETUGE);
911   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
912   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
913                                                Remainder_GE_Zero);
914
915   // Calculate Division result:
916
917   // Quotient_A_One = Quotient + 1
918   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
919                                                          DAG.getConstant(1, VT));
920
921   // Quotient_S_One = Quotient - 1
922   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
923                                                          DAG.getConstant(1, VT));
924
925   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
926   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
927                                      Quotient, Quotient_A_One, ISD::SETEQ);
928
929   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
930   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
931                             Quotient_S_One, Div, ISD::SETEQ);
932
933   // Calculate Rem result:
934
935   // Remainder_S_Den = Remainder - Den
936   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
937
938   // Remainder_A_Den = Remainder + Den
939   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
940
941   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
942   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
943                                     Remainder, Remainder_S_Den, ISD::SETEQ);
944
945   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
946   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
947                             Remainder_A_Den, Rem, ISD::SETEQ);
948   SDValue Ops[2];
949   Ops[0] = Div;
950   Ops[1] = Rem;
951   return DAG.getMergeValues(Ops, 2, DL);
952 }
953
954 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
955                                                SelectionDAG &DAG) const {
956   SDValue S0 = Op.getOperand(0);
957   SDLoc DL(Op);
958   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
959     return SDValue();
960
961   // f32 uint_to_fp i64
962   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
963                            DAG.getConstant(0, MVT::i32));
964   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
965   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
966                            DAG.getConstant(1, MVT::i32));
967   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
968   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
969                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
970   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
971
972 }
973
974 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
975                                                       unsigned BitsDiff,
976                                                       SelectionDAG &DAG) const {
977   MVT VT = Op.getSimpleValueType();
978   SDLoc DL(Op);
979   SDValue Shift = DAG.getConstant(BitsDiff, VT);
980   // Shift left by 'Shift' bits.
981   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
982   // Signed shift Right by 'Shift' bits.
983   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
984 }
985
986 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
987                                                      SelectionDAG &DAG) const {
988   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
989   MVT VT = Op.getSimpleValueType();
990   MVT ScalarVT = VT.getScalarType();
991
992   unsigned SrcBits = ExtraVT.getScalarType().getSizeInBits();
993   unsigned DestBits = ScalarVT.getSizeInBits();
994   unsigned BitsDiff = DestBits - SrcBits;
995
996   if (!Subtarget->hasBFE())
997     return ExpandSIGN_EXTEND_INREG(Op, BitsDiff, DAG);
998
999   SDValue Src = Op.getOperand(0);
1000   if (VT.isVector()) {
1001     SDLoc DL(Op);
1002     // Need to scalarize this, and revisit each of the scalars later.
1003     // TODO: Don't scalarize on Evergreen?
1004     unsigned NElts = VT.getVectorNumElements();
1005     SmallVector<SDValue, 8> Args;
1006     ExtractVectorElements(Src, DAG, Args, 0, NElts);
1007
1008     SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
1009     for (unsigned I = 0; I < NElts; ++I)
1010       Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
1011
1012     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args.data(), Args.size());
1013   }
1014
1015   if (SrcBits == 32) {
1016     SDLoc DL(Op);
1017
1018     // If the source is 32-bits, this is really half of a 2-register pair, and
1019     // we need to discard the unused half of the pair.
1020     SDValue TruncSrc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
1021     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, TruncSrc);
1022   }
1023
1024   unsigned NElts = VT.isVector() ? VT.getVectorNumElements() : 1;
1025
1026   // TODO: Match 64-bit BFE. SI has a 64-bit BFE, but it's scalar only so it
1027   // might not be worth the effort, and will need to expand to shifts when
1028   // fixing SGPR copies.
1029   if (SrcBits < 32 && DestBits <= 32) {
1030     SDLoc DL(Op);
1031     MVT ExtVT = (NElts == 1) ? MVT::i32 : MVT::getVectorVT(MVT::i32, NElts);
1032
1033     if (DestBits != 32)
1034       Src = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Src);
1035
1036     // FIXME: This should use TargetConstant, but that hits assertions for
1037     // Evergreen.
1038     SDValue Ext = DAG.getNode(AMDGPUISD::BFE_I32, DL, ExtVT,
1039                               Op.getOperand(0), // Operand
1040                               DAG.getConstant(0, ExtVT), // Offset
1041                               DAG.getConstant(SrcBits, ExtVT)); // Width
1042
1043     // Truncate to the original type if necessary.
1044     if (ScalarVT == MVT::i32)
1045       return Ext;
1046     return DAG.getNode(ISD::TRUNCATE, DL, VT, Ext);
1047   }
1048
1049   // For small types, extend to 32-bits first.
1050   if (SrcBits < 32) {
1051     SDLoc DL(Op);
1052     MVT ExtVT = (NElts == 1) ? MVT::i32 : MVT::getVectorVT(MVT::i32, NElts);
1053
1054     SDValue TruncSrc = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, Src);
1055     SDValue Ext32 = DAG.getNode(AMDGPUISD::BFE_I32,
1056                                 DL,
1057                                 ExtVT,
1058                                 TruncSrc, // Operand
1059                                 DAG.getConstant(0, ExtVT), // Offset
1060                                 DAG.getConstant(SrcBits, ExtVT)); // Width
1061
1062     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Ext32);
1063   }
1064
1065   // For everything else, use the standard bitshift expansion.
1066   return ExpandSIGN_EXTEND_INREG(Op, BitsDiff, DAG);
1067 }
1068
1069 //===----------------------------------------------------------------------===//
1070 // Helper functions
1071 //===----------------------------------------------------------------------===//
1072
1073 void AMDGPUTargetLowering::getOriginalFunctionArgs(
1074                                SelectionDAG &DAG,
1075                                const Function *F,
1076                                const SmallVectorImpl<ISD::InputArg> &Ins,
1077                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
1078
1079   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1080     if (Ins[i].ArgVT == Ins[i].VT) {
1081       OrigIns.push_back(Ins[i]);
1082       continue;
1083     }
1084
1085     EVT VT;
1086     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
1087       // Vector has been split into scalars.
1088       VT = Ins[i].ArgVT.getVectorElementType();
1089     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
1090                Ins[i].ArgVT.getVectorElementType() !=
1091                Ins[i].VT.getVectorElementType()) {
1092       // Vector elements have been promoted
1093       VT = Ins[i].ArgVT;
1094     } else {
1095       // Vector has been spilt into smaller vectors.
1096       VT = Ins[i].VT;
1097     }
1098
1099     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
1100                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
1101     OrigIns.push_back(Arg);
1102   }
1103 }
1104
1105 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
1106   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1107     return CFP->isExactlyValue(1.0);
1108   }
1109   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1110     return C->isAllOnesValue();
1111   }
1112   return false;
1113 }
1114
1115 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
1116   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1117     return CFP->getValueAPF().isZero();
1118   }
1119   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1120     return C->isNullValue();
1121   }
1122   return false;
1123 }
1124
1125 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1126                                                   const TargetRegisterClass *RC,
1127                                                    unsigned Reg, EVT VT) const {
1128   MachineFunction &MF = DAG.getMachineFunction();
1129   MachineRegisterInfo &MRI = MF.getRegInfo();
1130   unsigned VirtualRegister;
1131   if (!MRI.isLiveIn(Reg)) {
1132     VirtualRegister = MRI.createVirtualRegister(RC);
1133     MRI.addLiveIn(Reg, VirtualRegister);
1134   } else {
1135     VirtualRegister = MRI.getLiveInVirtReg(Reg);
1136   }
1137   return DAG.getRegister(VirtualRegister, VT);
1138 }
1139
1140 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
1141
1142 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
1143   switch (Opcode) {
1144   default: return 0;
1145   // AMDIL DAG nodes
1146   NODE_NAME_CASE(CALL);
1147   NODE_NAME_CASE(UMUL);
1148   NODE_NAME_CASE(DIV_INF);
1149   NODE_NAME_CASE(RET_FLAG);
1150   NODE_NAME_CASE(BRANCH_COND);
1151
1152   // AMDGPU DAG nodes
1153   NODE_NAME_CASE(DWORDADDR)
1154   NODE_NAME_CASE(FRACT)
1155   NODE_NAME_CASE(FMAX)
1156   NODE_NAME_CASE(SMAX)
1157   NODE_NAME_CASE(UMAX)
1158   NODE_NAME_CASE(FMIN)
1159   NODE_NAME_CASE(SMIN)
1160   NODE_NAME_CASE(UMIN)
1161   NODE_NAME_CASE(BFE_U32)
1162   NODE_NAME_CASE(BFE_I32)
1163   NODE_NAME_CASE(URECIP)
1164   NODE_NAME_CASE(DOT4)
1165   NODE_NAME_CASE(EXPORT)
1166   NODE_NAME_CASE(CONST_ADDRESS)
1167   NODE_NAME_CASE(REGISTER_LOAD)
1168   NODE_NAME_CASE(REGISTER_STORE)
1169   NODE_NAME_CASE(LOAD_CONSTANT)
1170   NODE_NAME_CASE(LOAD_INPUT)
1171   NODE_NAME_CASE(SAMPLE)
1172   NODE_NAME_CASE(SAMPLEB)
1173   NODE_NAME_CASE(SAMPLED)
1174   NODE_NAME_CASE(SAMPLEL)
1175   NODE_NAME_CASE(STORE_MSKOR)
1176   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
1177   }
1178 }
1179
1180 void AMDGPUTargetLowering::computeMaskedBitsForTargetNode(
1181   const SDValue Op,
1182   APInt &KnownZero,
1183   APInt &KnownOne,
1184   const SelectionDAG &DAG,
1185   unsigned Depth) const {
1186   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
1187 }