R600: Add a testcase for sext_in_reg I missed.
[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 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
337                                                        const GlobalValue *GV,
338                                                        const SDValue &InitPtr,
339                                                        SDValue Chain,
340                                                        SelectionDAG &DAG) const {
341   const DataLayout *TD = getTargetMachine().getDataLayout();
342   SDLoc DL(InitPtr);
343   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
344     EVT VT = EVT::getEVT(CI->getType());
345     PointerType *PtrTy = PointerType::get(CI->getType(), 0);
346     return DAG.getStore(Chain, DL,  DAG.getConstant(*CI, VT), InitPtr,
347                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
348                  TD->getPrefTypeAlignment(CI->getType()));
349   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
350     EVT VT = EVT::getEVT(CFP->getType());
351     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
352     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
353                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
354                  TD->getPrefTypeAlignment(CFP->getType()));
355   } else if (Init->getType()->isAggregateType()) {
356     EVT PtrVT = InitPtr.getValueType();
357     unsigned NumElements = Init->getType()->getArrayNumElements();
358     SmallVector<SDValue, 8> Chains;
359     for (unsigned i = 0; i < NumElements; ++i) {
360       SDValue Offset = DAG.getConstant(i * TD->getTypeAllocSize(
361           Init->getType()->getArrayElementType()), PtrVT);
362       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
363       Chains.push_back(LowerConstantInitializer(Init->getAggregateElement(i),
364                        GV, Ptr, Chain, DAG));
365     }
366     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
367                        Chains.size());
368   } else {
369     Init->dump();
370     llvm_unreachable("Unhandled constant initializer");
371   }
372 }
373
374 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
375                                                  SDValue Op,
376                                                  SelectionDAG &DAG) const {
377
378   const DataLayout *TD = getTargetMachine().getDataLayout();
379   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
380   const GlobalValue *GV = G->getGlobal();
381
382   switch (G->getAddressSpace()) {
383   default: llvm_unreachable("Global Address lowering not implemented for this "
384                             "address space");
385   case AMDGPUAS::LOCAL_ADDRESS: {
386     // XXX: What does the value of G->getOffset() mean?
387     assert(G->getOffset() == 0 &&
388          "Do not know what to do with an non-zero offset");
389
390     unsigned Offset;
391     if (MFI->LocalMemoryObjects.count(GV) == 0) {
392       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
393       Offset = MFI->LDSSize;
394       MFI->LocalMemoryObjects[GV] = Offset;
395       // XXX: Account for alignment?
396       MFI->LDSSize += Size;
397     } else {
398       Offset = MFI->LocalMemoryObjects[GV];
399     }
400
401     return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
402   }
403   case AMDGPUAS::CONSTANT_ADDRESS: {
404     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
405     Type *EltType = GV->getType()->getElementType();
406     unsigned Size = TD->getTypeAllocSize(EltType);
407     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
408
409     const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV);
410     const Constant *Init = Var->getInitializer();
411     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
412     SDValue InitPtr = DAG.getFrameIndex(FI,
413         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
414     SmallVector<SDNode*, 8> WorkList;
415
416     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
417                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
418       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
419         continue;
420       WorkList.push_back(*I);
421     }
422     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
423     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
424                                            E = WorkList.end(); I != E; ++I) {
425       SmallVector<SDValue, 8> Ops;
426       Ops.push_back(Chain);
427       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
428         Ops.push_back((*I)->getOperand(i));
429       }
430       DAG.UpdateNodeOperands(*I, &Ops[0], Ops.size());
431     }
432     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op),
433         getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
434   }
435   }
436 }
437
438 void AMDGPUTargetLowering::ExtractVectorElements(SDValue Op, SelectionDAG &DAG,
439                                          SmallVectorImpl<SDValue> &Args,
440                                          unsigned Start,
441                                          unsigned Count) const {
442   EVT VT = Op.getValueType();
443   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
444     Args.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
445                                VT.getVectorElementType(),
446                                Op, DAG.getConstant(i, MVT::i32)));
447   }
448 }
449
450 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
451                                                   SelectionDAG &DAG) const {
452   SmallVector<SDValue, 8> Args;
453   SDValue A = Op.getOperand(0);
454   SDValue B = Op.getOperand(1);
455
456   ExtractVectorElements(A, DAG, Args, 0,
457                         A.getValueType().getVectorNumElements());
458   ExtractVectorElements(B, DAG, Args, 0,
459                         B.getValueType().getVectorNumElements());
460
461   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
462                      &Args[0], Args.size());
463 }
464
465 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
466                                                      SelectionDAG &DAG) const {
467
468   SmallVector<SDValue, 8> Args;
469   EVT VT = Op.getValueType();
470   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
471   ExtractVectorElements(Op.getOperand(0), DAG, Args, Start,
472                         VT.getVectorNumElements());
473
474   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
475                      &Args[0], Args.size());
476 }
477
478 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
479                                               SelectionDAG &DAG) const {
480
481   MachineFunction &MF = DAG.getMachineFunction();
482   const AMDGPUFrameLowering *TFL =
483    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
484
485   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
486   assert(FIN);
487
488   unsigned FrameIndex = FIN->getIndex();
489   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
490   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
491                          Op.getValueType());
492 }
493
494 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
495     SelectionDAG &DAG) const {
496   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
497   SDLoc DL(Op);
498   EVT VT = Op.getValueType();
499
500   switch (IntrinsicID) {
501     default: return Op;
502     case AMDGPUIntrinsic::AMDIL_abs:
503       return LowerIntrinsicIABS(Op, DAG);
504     case AMDGPUIntrinsic::AMDIL_exp:
505       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
506     case AMDGPUIntrinsic::AMDGPU_lrp:
507       return LowerIntrinsicLRP(Op, DAG);
508     case AMDGPUIntrinsic::AMDIL_fraction:
509       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
510     case AMDGPUIntrinsic::AMDIL_max:
511       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, Op.getOperand(1),
512                                                   Op.getOperand(2));
513     case AMDGPUIntrinsic::AMDGPU_imax:
514       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
515                                                   Op.getOperand(2));
516     case AMDGPUIntrinsic::AMDGPU_umax:
517       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
518                                                   Op.getOperand(2));
519     case AMDGPUIntrinsic::AMDIL_min:
520       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, Op.getOperand(1),
521                                                   Op.getOperand(2));
522     case AMDGPUIntrinsic::AMDGPU_imin:
523       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
524                                                   Op.getOperand(2));
525     case AMDGPUIntrinsic::AMDGPU_umin:
526       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
527                                                   Op.getOperand(2));
528     case AMDGPUIntrinsic::AMDIL_round_nearest:
529       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
530   }
531 }
532
533 ///IABS(a) = SMAX(sub(0, a), a)
534 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
535     SelectionDAG &DAG) const {
536
537   SDLoc DL(Op);
538   EVT VT = Op.getValueType();
539   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
540                                               Op.getOperand(1));
541
542   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
543 }
544
545 /// Linear Interpolation
546 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
547 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
548     SelectionDAG &DAG) const {
549   SDLoc DL(Op);
550   EVT VT = Op.getValueType();
551   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
552                                 DAG.getConstantFP(1.0f, MVT::f32),
553                                 Op.getOperand(1));
554   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
555                                                     Op.getOperand(3));
556   return DAG.getNode(ISD::FADD, DL, VT,
557       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
558       OneSubAC);
559 }
560
561 /// \brief Generate Min/Max node
562 SDValue AMDGPUTargetLowering::LowerMinMax(SDValue Op,
563     SelectionDAG &DAG) const {
564   SDLoc DL(Op);
565   EVT VT = Op.getValueType();
566
567   SDValue LHS = Op.getOperand(0);
568   SDValue RHS = Op.getOperand(1);
569   SDValue True = Op.getOperand(2);
570   SDValue False = Op.getOperand(3);
571   SDValue CC = Op.getOperand(4);
572
573   if (VT != MVT::f32 ||
574       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
575     return SDValue();
576   }
577
578   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
579   switch (CCOpcode) {
580   case ISD::SETOEQ:
581   case ISD::SETONE:
582   case ISD::SETUNE:
583   case ISD::SETNE:
584   case ISD::SETUEQ:
585   case ISD::SETEQ:
586   case ISD::SETFALSE:
587   case ISD::SETFALSE2:
588   case ISD::SETTRUE:
589   case ISD::SETTRUE2:
590   case ISD::SETUO:
591   case ISD::SETO:
592     llvm_unreachable("Operation should already be optimised!");
593   case ISD::SETULE:
594   case ISD::SETULT:
595   case ISD::SETOLE:
596   case ISD::SETOLT:
597   case ISD::SETLE:
598   case ISD::SETLT: {
599     if (LHS == True)
600       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
601     else
602       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
603   }
604   case ISD::SETGT:
605   case ISD::SETGE:
606   case ISD::SETUGE:
607   case ISD::SETOGE:
608   case ISD::SETUGT:
609   case ISD::SETOGT: {
610     if (LHS == True)
611       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
612     else
613       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
614   }
615   case ISD::SETCC_INVALID:
616     llvm_unreachable("Invalid setcc condcode!");
617   }
618   return Op;
619 }
620
621 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
622                                               SelectionDAG &DAG) const {
623   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
624   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
625   EVT EltVT = Op.getValueType().getVectorElementType();
626   EVT PtrVT = Load->getBasePtr().getValueType();
627   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
628   SmallVector<SDValue, 8> Loads;
629   SDLoc SL(Op);
630
631   for (unsigned i = 0, e = NumElts; i != e; ++i) {
632     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
633                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
634     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
635                         Load->getChain(), Ptr,
636                         MachinePointerInfo(Load->getMemOperand()->getValue()),
637                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
638                         Load->getAlignment()));
639   }
640   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(),
641                      Loads.data(), Loads.size());
642 }
643
644 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
645                                                SelectionDAG &DAG) const {
646   StoreSDNode *Store = dyn_cast<StoreSDNode>(Op);
647   EVT MemVT = Store->getMemoryVT();
648   unsigned MemBits = MemVT.getSizeInBits();
649
650   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
651   // truncating store into an i32 store.
652   // XXX: We could also handle optimize other vector bitwidths.
653   if (!MemVT.isVector() || MemBits > 32) {
654     return SDValue();
655   }
656
657   SDLoc DL(Op);
658   const SDValue &Value = Store->getValue();
659   EVT VT = Value.getValueType();
660   const SDValue &Ptr = Store->getBasePtr();
661   EVT MemEltVT = MemVT.getVectorElementType();
662   unsigned MemEltBits = MemEltVT.getSizeInBits();
663   unsigned MemNumElements = MemVT.getVectorNumElements();
664   EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
665   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, PackedVT);
666
667   SDValue PackedValue;
668   for (unsigned i = 0; i < MemNumElements; ++i) {
669     EVT ElemVT = VT.getVectorElementType();
670     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
671                               DAG.getConstant(i, MVT::i32));
672     Elt = DAG.getZExtOrTrunc(Elt, DL, PackedVT);
673     Elt = DAG.getNode(ISD::AND, DL, PackedVT, Elt, Mask);
674     SDValue Shift = DAG.getConstant(MemEltBits * i, PackedVT);
675     Elt = DAG.getNode(ISD::SHL, DL, PackedVT, Elt, Shift);
676     if (i == 0) {
677       PackedValue = Elt;
678     } else {
679       PackedValue = DAG.getNode(ISD::OR, DL, PackedVT, PackedValue, Elt);
680     }
681   }
682   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
683                       MachinePointerInfo(Store->getMemOperand()->getValue()),
684                       Store->isVolatile(),  Store->isNonTemporal(),
685                       Store->getAlignment());
686 }
687
688 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
689                                             SelectionDAG &DAG) const {
690   StoreSDNode *Store = cast<StoreSDNode>(Op);
691   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
692   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
693   EVT PtrVT = Store->getBasePtr().getValueType();
694   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
695   SDLoc SL(Op);
696
697   SmallVector<SDValue, 8> Chains;
698
699   for (unsigned i = 0, e = NumElts; i != e; ++i) {
700     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
701                               Store->getValue(), DAG.getConstant(i, MVT::i32));
702     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
703                               Store->getBasePtr(),
704                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
705                                             PtrVT));
706     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
707                          MachinePointerInfo(Store->getMemOperand()->getValue()),
708                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
709                          Store->getAlignment()));
710   }
711   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, &Chains[0], NumElts);
712 }
713
714 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
715   SDLoc DL(Op);
716   LoadSDNode *Load = cast<LoadSDNode>(Op);
717   ISD::LoadExtType ExtType = Load->getExtensionType();
718   EVT VT = Op.getValueType();
719   EVT MemVT = Load->getMemoryVT();
720
721   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
722     // We can do the extload to 32-bits, and then need to separately extend to
723     // 64-bits.
724
725     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
726                                        Load->getChain(),
727                                        Load->getBasePtr(),
728                                        MemVT,
729                                        Load->getMemOperand());
730     return DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32);
731   }
732
733   // Lower loads constant address space global variable loads
734   if (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
735       isa<GlobalVariable>(GetUnderlyingObject(Load->getPointerInfo().V))) {
736
737     SDValue Ptr = DAG.getZExtOrTrunc(Load->getBasePtr(), DL,
738         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
739     Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr,
740         DAG.getConstant(2, MVT::i32));
741     return DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
742                        Load->getChain(), Ptr,
743                        DAG.getTargetConstant(0, MVT::i32), Op.getOperand(2));
744   }
745
746   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
747       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
748     return SDValue();
749
750
751   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
752                             DAG.getConstant(2, MVT::i32));
753   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
754                             Load->getChain(), Ptr,
755                             DAG.getTargetConstant(0, MVT::i32),
756                             Op.getOperand(2));
757   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
758                                 Load->getBasePtr(),
759                                 DAG.getConstant(0x3, MVT::i32));
760   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
761                                  DAG.getConstant(3, MVT::i32));
762
763   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
764
765   EVT MemEltVT = MemVT.getScalarType();
766   if (ExtType == ISD::SEXTLOAD) {
767     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
768     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode);
769   }
770
771   return DAG.getZeroExtendInReg(Ret, DL, MemEltVT);
772 }
773
774 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
775   SDLoc DL(Op);
776   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
777   if (Result.getNode()) {
778     return Result;
779   }
780
781   StoreSDNode *Store = cast<StoreSDNode>(Op);
782   SDValue Chain = Store->getChain();
783   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
784        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
785       Store->getValue().getValueType().isVector()) {
786     return SplitVectorStore(Op, DAG);
787   }
788
789   EVT MemVT = Store->getMemoryVT();
790   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
791       MemVT.bitsLT(MVT::i32)) {
792     unsigned Mask = 0;
793     if (Store->getMemoryVT() == MVT::i8) {
794       Mask = 0xff;
795     } else if (Store->getMemoryVT() == MVT::i16) {
796       Mask = 0xffff;
797     }
798     SDValue BasePtr = Store->getBasePtr();
799     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
800                               DAG.getConstant(2, MVT::i32));
801     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
802                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
803
804     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
805                                   DAG.getConstant(0x3, MVT::i32));
806
807     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
808                                    DAG.getConstant(3, MVT::i32));
809
810     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
811                                     Store->getValue());
812
813     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
814
815     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
816                                        MaskedValue, ShiftAmt);
817
818     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
819                                   ShiftAmt);
820     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
821                           DAG.getConstant(0xffffffff, MVT::i32));
822     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
823
824     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
825     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
826                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
827   }
828   return SDValue();
829 }
830
831 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
832     SelectionDAG &DAG) const {
833   SDLoc DL(Op);
834   EVT VT = Op.getValueType();
835
836   SDValue Num = Op.getOperand(0);
837   SDValue Den = Op.getOperand(1);
838
839   SmallVector<SDValue, 8> Results;
840
841   // RCP =  URECIP(Den) = 2^32 / Den + e
842   // e is rounding error.
843   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
844
845   // RCP_LO = umulo(RCP, Den) */
846   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
847
848   // RCP_HI = mulhu (RCP, Den) */
849   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
850
851   // NEG_RCP_LO = -RCP_LO
852   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
853                                                      RCP_LO);
854
855   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
856   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
857                                            NEG_RCP_LO, RCP_LO,
858                                            ISD::SETEQ);
859   // Calculate the rounding error from the URECIP instruction
860   // E = mulhu(ABS_RCP_LO, RCP)
861   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
862
863   // RCP_A_E = RCP + E
864   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
865
866   // RCP_S_E = RCP - E
867   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
868
869   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
870   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
871                                      RCP_A_E, RCP_S_E,
872                                      ISD::SETEQ);
873   // Quotient = mulhu(Tmp0, Num)
874   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
875
876   // Num_S_Remainder = Quotient * Den
877   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
878
879   // Remainder = Num - Num_S_Remainder
880   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
881
882   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
883   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
884                                                  DAG.getConstant(-1, VT),
885                                                  DAG.getConstant(0, VT),
886                                                  ISD::SETUGE);
887   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
888   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
889                                                   Num_S_Remainder,
890                                                   DAG.getConstant(-1, VT),
891                                                   DAG.getConstant(0, VT),
892                                                   ISD::SETUGE);
893   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
894   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
895                                                Remainder_GE_Zero);
896
897   // Calculate Division result:
898
899   // Quotient_A_One = Quotient + 1
900   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
901                                                          DAG.getConstant(1, VT));
902
903   // Quotient_S_One = Quotient - 1
904   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
905                                                          DAG.getConstant(1, VT));
906
907   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
908   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
909                                      Quotient, Quotient_A_One, ISD::SETEQ);
910
911   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
912   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
913                             Quotient_S_One, Div, ISD::SETEQ);
914
915   // Calculate Rem result:
916
917   // Remainder_S_Den = Remainder - Den
918   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
919
920   // Remainder_A_Den = Remainder + Den
921   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
922
923   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
924   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
925                                     Remainder, Remainder_S_Den, ISD::SETEQ);
926
927   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
928   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
929                             Remainder_A_Den, Rem, ISD::SETEQ);
930   SDValue Ops[2];
931   Ops[0] = Div;
932   Ops[1] = Rem;
933   return DAG.getMergeValues(Ops, 2, DL);
934 }
935
936 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
937                                                SelectionDAG &DAG) const {
938   SDValue S0 = Op.getOperand(0);
939   SDLoc DL(Op);
940   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
941     return SDValue();
942
943   // f32 uint_to_fp i64
944   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
945                            DAG.getConstant(0, MVT::i32));
946   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
947   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
948                            DAG.getConstant(1, MVT::i32));
949   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
950   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
951                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
952   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
953
954 }
955
956 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
957                                                       unsigned BitsDiff,
958                                                       SelectionDAG &DAG) const {
959   MVT VT = Op.getSimpleValueType();
960   SDLoc DL(Op);
961   SDValue Shift = DAG.getConstant(BitsDiff, VT);
962   // Shift left by 'Shift' bits.
963   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
964   // Signed shift Right by 'Shift' bits.
965   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
966 }
967
968 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
969                                                      SelectionDAG &DAG) const {
970   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
971   MVT VT = Op.getSimpleValueType();
972   MVT ScalarVT = VT.getScalarType();
973
974   unsigned SrcBits = ExtraVT.getScalarType().getSizeInBits();
975   unsigned DestBits = ScalarVT.getSizeInBits();
976   unsigned BitsDiff = DestBits - SrcBits;
977
978   if (!Subtarget->hasBFE())
979     return ExpandSIGN_EXTEND_INREG(Op, BitsDiff, DAG);
980
981   SDValue Src = Op.getOperand(0);
982   if (VT.isVector()) {
983     SDLoc DL(Op);
984     // Need to scalarize this, and revisit each of the scalars later.
985     // TODO: Don't scalarize on Evergreen?
986     unsigned NElts = VT.getVectorNumElements();
987     SmallVector<SDValue, 8> Args;
988     ExtractVectorElements(Src, DAG, Args, 0, NElts);
989
990     SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
991     for (unsigned I = 0; I < NElts; ++I)
992       Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
993
994     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args.data(), Args.size());
995   }
996
997   if (SrcBits == 32) {
998     SDLoc DL(Op);
999
1000     // If the source is 32-bits, this is really half of a 2-register pair, and
1001     // we need to discard the unused half of the pair.
1002     SDValue TruncSrc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
1003     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, TruncSrc);
1004   }
1005
1006   unsigned NElts = VT.isVector() ? VT.getVectorNumElements() : 1;
1007
1008   // TODO: Match 64-bit BFE. SI has a 64-bit BFE, but it's scalar only so it
1009   // might not be worth the effort, and will need to expand to shifts when
1010   // fixing SGPR copies.
1011   if (SrcBits < 32 && DestBits <= 32) {
1012     SDLoc DL(Op);
1013     MVT ExtVT = (NElts == 1) ? MVT::i32 : MVT::getVectorVT(MVT::i32, NElts);
1014
1015     if (DestBits != 32)
1016       Src = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Src);
1017
1018     // FIXME: This should use TargetConstant, but that hits assertions for
1019     // Evergreen.
1020     SDValue Ext = DAG.getNode(AMDGPUISD::BFE_I32, DL, ExtVT,
1021                               Op.getOperand(0), // Operand
1022                               DAG.getConstant(0, ExtVT), // Offset
1023                               DAG.getConstant(SrcBits, ExtVT)); // Width
1024
1025     // Truncate to the original type if necessary.
1026     if (ScalarVT == MVT::i32)
1027       return Ext;
1028     return DAG.getNode(ISD::TRUNCATE, DL, VT, Ext);
1029   }
1030
1031   // For small types, extend to 32-bits first.
1032   if (SrcBits < 32) {
1033     SDLoc DL(Op);
1034     MVT ExtVT = (NElts == 1) ? MVT::i32 : MVT::getVectorVT(MVT::i32, NElts);
1035
1036     SDValue TruncSrc = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, Src);
1037     SDValue Ext32 = DAG.getNode(AMDGPUISD::BFE_I32,
1038                                 DL,
1039                                 ExtVT,
1040                                 TruncSrc, // Operand
1041                                 DAG.getConstant(0, ExtVT), // Offset
1042                                 DAG.getConstant(SrcBits, ExtVT)); // Width
1043
1044     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Ext32);
1045   }
1046
1047   // For everything else, use the standard bitshift expansion.
1048   return ExpandSIGN_EXTEND_INREG(Op, BitsDiff, DAG);
1049 }
1050
1051 //===----------------------------------------------------------------------===//
1052 // Helper functions
1053 //===----------------------------------------------------------------------===//
1054
1055 void AMDGPUTargetLowering::getOriginalFunctionArgs(
1056                                SelectionDAG &DAG,
1057                                const Function *F,
1058                                const SmallVectorImpl<ISD::InputArg> &Ins,
1059                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
1060
1061   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1062     if (Ins[i].ArgVT == Ins[i].VT) {
1063       OrigIns.push_back(Ins[i]);
1064       continue;
1065     }
1066
1067     EVT VT;
1068     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
1069       // Vector has been split into scalars.
1070       VT = Ins[i].ArgVT.getVectorElementType();
1071     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
1072                Ins[i].ArgVT.getVectorElementType() !=
1073                Ins[i].VT.getVectorElementType()) {
1074       // Vector elements have been promoted
1075       VT = Ins[i].ArgVT;
1076     } else {
1077       // Vector has been spilt into smaller vectors.
1078       VT = Ins[i].VT;
1079     }
1080
1081     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
1082                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
1083     OrigIns.push_back(Arg);
1084   }
1085 }
1086
1087 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
1088   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1089     return CFP->isExactlyValue(1.0);
1090   }
1091   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1092     return C->isAllOnesValue();
1093   }
1094   return false;
1095 }
1096
1097 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
1098   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1099     return CFP->getValueAPF().isZero();
1100   }
1101   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1102     return C->isNullValue();
1103   }
1104   return false;
1105 }
1106
1107 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1108                                                   const TargetRegisterClass *RC,
1109                                                    unsigned Reg, EVT VT) const {
1110   MachineFunction &MF = DAG.getMachineFunction();
1111   MachineRegisterInfo &MRI = MF.getRegInfo();
1112   unsigned VirtualRegister;
1113   if (!MRI.isLiveIn(Reg)) {
1114     VirtualRegister = MRI.createVirtualRegister(RC);
1115     MRI.addLiveIn(Reg, VirtualRegister);
1116   } else {
1117     VirtualRegister = MRI.getLiveInVirtReg(Reg);
1118   }
1119   return DAG.getRegister(VirtualRegister, VT);
1120 }
1121
1122 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
1123
1124 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
1125   switch (Opcode) {
1126   default: return 0;
1127   // AMDIL DAG nodes
1128   NODE_NAME_CASE(CALL);
1129   NODE_NAME_CASE(UMUL);
1130   NODE_NAME_CASE(DIV_INF);
1131   NODE_NAME_CASE(RET_FLAG);
1132   NODE_NAME_CASE(BRANCH_COND);
1133
1134   // AMDGPU DAG nodes
1135   NODE_NAME_CASE(DWORDADDR)
1136   NODE_NAME_CASE(FRACT)
1137   NODE_NAME_CASE(FMAX)
1138   NODE_NAME_CASE(SMAX)
1139   NODE_NAME_CASE(UMAX)
1140   NODE_NAME_CASE(FMIN)
1141   NODE_NAME_CASE(SMIN)
1142   NODE_NAME_CASE(UMIN)
1143   NODE_NAME_CASE(BFE_U32)
1144   NODE_NAME_CASE(BFE_I32)
1145   NODE_NAME_CASE(URECIP)
1146   NODE_NAME_CASE(DOT4)
1147   NODE_NAME_CASE(EXPORT)
1148   NODE_NAME_CASE(CONST_ADDRESS)
1149   NODE_NAME_CASE(REGISTER_LOAD)
1150   NODE_NAME_CASE(REGISTER_STORE)
1151   NODE_NAME_CASE(LOAD_CONSTANT)
1152   NODE_NAME_CASE(LOAD_INPUT)
1153   NODE_NAME_CASE(SAMPLE)
1154   NODE_NAME_CASE(SAMPLEB)
1155   NODE_NAME_CASE(SAMPLED)
1156   NODE_NAME_CASE(SAMPLEL)
1157   NODE_NAME_CASE(STORE_MSKOR)
1158   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
1159   }
1160 }
1161
1162 void AMDGPUTargetLowering::computeMaskedBitsForTargetNode(
1163   const SDValue Op,
1164   APInt &KnownZero,
1165   APInt &KnownOne,
1166   const SelectionDAG &DAG,
1167   unsigned Depth) const {
1168   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
1169 }