95ff0ca5b1ca2ada0e64b178bbd9cfb3c2a155c7
[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   setTargetDAGCombine(ISD::MUL);
232 }
233
234 //===----------------------------------------------------------------------===//
235 // Target Information
236 //===----------------------------------------------------------------------===//
237
238 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
239   return MVT::i32;
240 }
241
242 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
243                                                    EVT CastTy) const {
244   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
245     return true;
246
247   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
248   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
249
250   return ((LScalarSize <= CastScalarSize) ||
251           (CastScalarSize >= 32) ||
252           (LScalarSize < 32));
253 }
254
255 //===---------------------------------------------------------------------===//
256 // Target Properties
257 //===---------------------------------------------------------------------===//
258
259 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
260   assert(VT.isFloatingPoint());
261   return VT == MVT::f32;
262 }
263
264 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
265   assert(VT.isFloatingPoint());
266   return VT == MVT::f32;
267 }
268
269 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
270   // Truncate is just accessing a subregister.
271   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
272 }
273
274 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
275   // Truncate is just accessing a subregister.
276   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
277          (Dest->getPrimitiveSizeInBits() % 32 == 0);
278 }
279
280 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
281   const DataLayout *DL = getDataLayout();
282   unsigned SrcSize = DL->getTypeSizeInBits(Src->getScalarType());
283   unsigned DestSize = DL->getTypeSizeInBits(Dest->getScalarType());
284
285   return SrcSize == 32 && DestSize == 64;
286 }
287
288 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
289   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
290   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
291   // this will enable reducing 64-bit operations the 32-bit, which is always
292   // good.
293   return Src == MVT::i32 && Dest == MVT::i64;
294 }
295
296 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
297   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
298   // limited number of native 64-bit operations. Shrinking an operation to fit
299   // in a single 32-bit register should always be helpful. As currently used,
300   // this is much less general than the name suggests, and is only used in
301   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
302   // not profitable, and may actually be harmful.
303   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
304 }
305
306 //===---------------------------------------------------------------------===//
307 // TargetLowering Callbacks
308 //===---------------------------------------------------------------------===//
309
310 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
311                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
312
313   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
314 }
315
316 SDValue AMDGPUTargetLowering::LowerReturn(
317                                      SDValue Chain,
318                                      CallingConv::ID CallConv,
319                                      bool isVarArg,
320                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
321                                      const SmallVectorImpl<SDValue> &OutVals,
322                                      SDLoc DL, SelectionDAG &DAG) const {
323   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
324 }
325
326 //===---------------------------------------------------------------------===//
327 // Target specific lowering
328 //===---------------------------------------------------------------------===//
329
330 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG)
331     const {
332   switch (Op.getOpcode()) {
333   default:
334     Op.getNode()->dump();
335     llvm_unreachable("Custom lowering code for this"
336                      "instruction is not implemented yet!");
337     break;
338   // AMDIL DAG lowering
339   case ISD::SDIV: return LowerSDIV(Op, DAG);
340   case ISD::SREM: return LowerSREM(Op, DAG);
341   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
342   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
343   // AMDGPU DAG lowering
344   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
345   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
346   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
347   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
348   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
349   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
350   }
351   return Op;
352 }
353
354 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
355                                               SmallVectorImpl<SDValue> &Results,
356                                               SelectionDAG &DAG) const {
357   switch (N->getOpcode()) {
358   case ISD::SIGN_EXTEND_INREG:
359     // Different parts of legalization seem to interpret which type of
360     // sign_extend_inreg is the one to check for custom lowering. The extended
361     // from type is what really matters, but some places check for custom
362     // lowering of the result type. This results in trying to use
363     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
364     // nothing here and let the illegal result integer be handled normally.
365     return;
366
367   default:
368     return;
369   }
370 }
371
372 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
373                                                        const GlobalValue *GV,
374                                                        const SDValue &InitPtr,
375                                                        SDValue Chain,
376                                                        SelectionDAG &DAG) const {
377   const DataLayout *TD = getTargetMachine().getDataLayout();
378   SDLoc DL(InitPtr);
379   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
380     EVT VT = EVT::getEVT(CI->getType());
381     PointerType *PtrTy = PointerType::get(CI->getType(), 0);
382     return DAG.getStore(Chain, DL,  DAG.getConstant(*CI, VT), InitPtr,
383                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
384                  TD->getPrefTypeAlignment(CI->getType()));
385   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
386     EVT VT = EVT::getEVT(CFP->getType());
387     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
388     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
389                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
390                  TD->getPrefTypeAlignment(CFP->getType()));
391   } else if (Init->getType()->isAggregateType()) {
392     EVT PtrVT = InitPtr.getValueType();
393     unsigned NumElements = Init->getType()->getArrayNumElements();
394     SmallVector<SDValue, 8> Chains;
395     for (unsigned i = 0; i < NumElements; ++i) {
396       SDValue Offset = DAG.getConstant(i * TD->getTypeAllocSize(
397           Init->getType()->getArrayElementType()), PtrVT);
398       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
399       Chains.push_back(LowerConstantInitializer(Init->getAggregateElement(i),
400                        GV, Ptr, Chain, DAG));
401     }
402     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
403                        Chains.data(), Chains.size());
404   } else {
405     Init->dump();
406     llvm_unreachable("Unhandled constant initializer");
407   }
408 }
409
410 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
411                                                  SDValue Op,
412                                                  SelectionDAG &DAG) const {
413
414   const DataLayout *TD = getTargetMachine().getDataLayout();
415   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
416   const GlobalValue *GV = G->getGlobal();
417
418   switch (G->getAddressSpace()) {
419   default: llvm_unreachable("Global Address lowering not implemented for this "
420                             "address space");
421   case AMDGPUAS::LOCAL_ADDRESS: {
422     // XXX: What does the value of G->getOffset() mean?
423     assert(G->getOffset() == 0 &&
424          "Do not know what to do with an non-zero offset");
425
426     unsigned Offset;
427     if (MFI->LocalMemoryObjects.count(GV) == 0) {
428       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
429       Offset = MFI->LDSSize;
430       MFI->LocalMemoryObjects[GV] = Offset;
431       // XXX: Account for alignment?
432       MFI->LDSSize += Size;
433     } else {
434       Offset = MFI->LocalMemoryObjects[GV];
435     }
436
437     return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
438   }
439   case AMDGPUAS::CONSTANT_ADDRESS: {
440     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
441     Type *EltType = GV->getType()->getElementType();
442     unsigned Size = TD->getTypeAllocSize(EltType);
443     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
444
445     const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV);
446     const Constant *Init = Var->getInitializer();
447     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
448     SDValue InitPtr = DAG.getFrameIndex(FI,
449         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
450     SmallVector<SDNode*, 8> WorkList;
451
452     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
453                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
454       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
455         continue;
456       WorkList.push_back(*I);
457     }
458     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
459     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
460                                            E = WorkList.end(); I != E; ++I) {
461       SmallVector<SDValue, 8> Ops;
462       Ops.push_back(Chain);
463       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
464         Ops.push_back((*I)->getOperand(i));
465       }
466       DAG.UpdateNodeOperands(*I, Ops.data(), Ops.size());
467     }
468     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op),
469         getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
470   }
471   }
472 }
473
474 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
475                                                   SelectionDAG &DAG) const {
476   SmallVector<SDValue, 8> Args;
477   SDValue A = Op.getOperand(0);
478   SDValue B = Op.getOperand(1);
479
480   DAG.ExtractVectorElements(A, Args);
481   DAG.ExtractVectorElements(B, Args);
482
483   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
484                      Args.data(), Args.size());
485 }
486
487 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
488                                                      SelectionDAG &DAG) const {
489
490   SmallVector<SDValue, 8> Args;
491   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
492   EVT VT = Op.getValueType();
493   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
494                             VT.getVectorNumElements());
495
496   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
497                      Args.data(), Args.size());
498 }
499
500 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
501                                               SelectionDAG &DAG) const {
502
503   MachineFunction &MF = DAG.getMachineFunction();
504   const AMDGPUFrameLowering *TFL =
505    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
506
507   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
508   assert(FIN);
509
510   unsigned FrameIndex = FIN->getIndex();
511   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
512   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
513                          Op.getValueType());
514 }
515
516 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
517     SelectionDAG &DAG) const {
518   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
519   SDLoc DL(Op);
520   EVT VT = Op.getValueType();
521
522   switch (IntrinsicID) {
523     default: return Op;
524     case AMDGPUIntrinsic::AMDIL_abs:
525       return LowerIntrinsicIABS(Op, DAG);
526     case AMDGPUIntrinsic::AMDIL_exp:
527       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
528     case AMDGPUIntrinsic::AMDGPU_lrp:
529       return LowerIntrinsicLRP(Op, DAG);
530     case AMDGPUIntrinsic::AMDIL_fraction:
531       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
532     case AMDGPUIntrinsic::AMDIL_max:
533       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, Op.getOperand(1),
534                                                   Op.getOperand(2));
535     case AMDGPUIntrinsic::AMDGPU_imax:
536       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
537                                                   Op.getOperand(2));
538     case AMDGPUIntrinsic::AMDGPU_umax:
539       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
540                                                   Op.getOperand(2));
541     case AMDGPUIntrinsic::AMDIL_min:
542       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, Op.getOperand(1),
543                                                   Op.getOperand(2));
544     case AMDGPUIntrinsic::AMDGPU_imin:
545       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
546                                                   Op.getOperand(2));
547     case AMDGPUIntrinsic::AMDGPU_umin:
548       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
549                                                   Op.getOperand(2));
550
551     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
552       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
553                          Op.getOperand(1),
554                          Op.getOperand(2),
555                          Op.getOperand(3));
556
557     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
558       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
559                          Op.getOperand(1),
560                          Op.getOperand(2),
561                          Op.getOperand(3));
562
563     case AMDGPUIntrinsic::AMDGPU_bfi:
564       return DAG.getNode(AMDGPUISD::BFI, DL, VT,
565                          Op.getOperand(1),
566                          Op.getOperand(2),
567                          Op.getOperand(3));
568
569     case AMDGPUIntrinsic::AMDGPU_bfm:
570       return DAG.getNode(AMDGPUISD::BFM, DL, VT,
571                          Op.getOperand(1),
572                          Op.getOperand(2));
573
574     case AMDGPUIntrinsic::AMDIL_round_nearest:
575       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
576   }
577 }
578
579 ///IABS(a) = SMAX(sub(0, a), a)
580 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
581     SelectionDAG &DAG) const {
582
583   SDLoc DL(Op);
584   EVT VT = Op.getValueType();
585   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
586                                               Op.getOperand(1));
587
588   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
589 }
590
591 /// Linear Interpolation
592 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
593 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
594     SelectionDAG &DAG) const {
595   SDLoc DL(Op);
596   EVT VT = Op.getValueType();
597   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
598                                 DAG.getConstantFP(1.0f, MVT::f32),
599                                 Op.getOperand(1));
600   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
601                                                     Op.getOperand(3));
602   return DAG.getNode(ISD::FADD, DL, VT,
603       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
604       OneSubAC);
605 }
606
607 /// \brief Generate Min/Max node
608 SDValue AMDGPUTargetLowering::LowerMinMax(SDValue Op,
609     SelectionDAG &DAG) const {
610   SDLoc DL(Op);
611   EVT VT = Op.getValueType();
612
613   SDValue LHS = Op.getOperand(0);
614   SDValue RHS = Op.getOperand(1);
615   SDValue True = Op.getOperand(2);
616   SDValue False = Op.getOperand(3);
617   SDValue CC = Op.getOperand(4);
618
619   if (VT != MVT::f32 ||
620       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
621     return SDValue();
622   }
623
624   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
625   switch (CCOpcode) {
626   case ISD::SETOEQ:
627   case ISD::SETONE:
628   case ISD::SETUNE:
629   case ISD::SETNE:
630   case ISD::SETUEQ:
631   case ISD::SETEQ:
632   case ISD::SETFALSE:
633   case ISD::SETFALSE2:
634   case ISD::SETTRUE:
635   case ISD::SETTRUE2:
636   case ISD::SETUO:
637   case ISD::SETO:
638     llvm_unreachable("Operation should already be optimised!");
639   case ISD::SETULE:
640   case ISD::SETULT:
641   case ISD::SETOLE:
642   case ISD::SETOLT:
643   case ISD::SETLE:
644   case ISD::SETLT: {
645     if (LHS == True)
646       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
647     else
648       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
649   }
650   case ISD::SETGT:
651   case ISD::SETGE:
652   case ISD::SETUGE:
653   case ISD::SETOGE:
654   case ISD::SETUGT:
655   case ISD::SETOGT: {
656     if (LHS == True)
657       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
658     else
659       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
660   }
661   case ISD::SETCC_INVALID:
662     llvm_unreachable("Invalid setcc condcode!");
663   }
664   return Op;
665 }
666
667 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
668                                               SelectionDAG &DAG) const {
669   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
670   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
671   EVT EltVT = Op.getValueType().getVectorElementType();
672   EVT PtrVT = Load->getBasePtr().getValueType();
673   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
674   SmallVector<SDValue, 8> Loads;
675   SDLoc SL(Op);
676
677   for (unsigned i = 0, e = NumElts; i != e; ++i) {
678     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
679                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
680     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
681                         Load->getChain(), Ptr,
682                         MachinePointerInfo(Load->getMemOperand()->getValue()),
683                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
684                         Load->getAlignment()));
685   }
686   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(),
687                      Loads.data(), Loads.size());
688 }
689
690 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
691                                                SelectionDAG &DAG) const {
692   StoreSDNode *Store = dyn_cast<StoreSDNode>(Op);
693   EVT MemVT = Store->getMemoryVT();
694   unsigned MemBits = MemVT.getSizeInBits();
695
696   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
697   // truncating store into an i32 store.
698   // XXX: We could also handle optimize other vector bitwidths.
699   if (!MemVT.isVector() || MemBits > 32) {
700     return SDValue();
701   }
702
703   SDLoc DL(Op);
704   const SDValue &Value = Store->getValue();
705   EVT VT = Value.getValueType();
706   const SDValue &Ptr = Store->getBasePtr();
707   EVT MemEltVT = MemVT.getVectorElementType();
708   unsigned MemEltBits = MemEltVT.getSizeInBits();
709   unsigned MemNumElements = MemVT.getVectorNumElements();
710   EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
711   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, PackedVT);
712
713   SDValue PackedValue;
714   for (unsigned i = 0; i < MemNumElements; ++i) {
715     EVT ElemVT = VT.getVectorElementType();
716     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
717                               DAG.getConstant(i, MVT::i32));
718     Elt = DAG.getZExtOrTrunc(Elt, DL, PackedVT);
719     Elt = DAG.getNode(ISD::AND, DL, PackedVT, Elt, Mask);
720     SDValue Shift = DAG.getConstant(MemEltBits * i, PackedVT);
721     Elt = DAG.getNode(ISD::SHL, DL, PackedVT, Elt, Shift);
722     if (i == 0) {
723       PackedValue = Elt;
724     } else {
725       PackedValue = DAG.getNode(ISD::OR, DL, PackedVT, PackedValue, Elt);
726     }
727   }
728   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
729                       MachinePointerInfo(Store->getMemOperand()->getValue()),
730                       Store->isVolatile(),  Store->isNonTemporal(),
731                       Store->getAlignment());
732 }
733
734 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
735                                             SelectionDAG &DAG) const {
736   StoreSDNode *Store = cast<StoreSDNode>(Op);
737   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
738   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
739   EVT PtrVT = Store->getBasePtr().getValueType();
740   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
741   SDLoc SL(Op);
742
743   SmallVector<SDValue, 8> Chains;
744
745   for (unsigned i = 0, e = NumElts; i != e; ++i) {
746     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
747                               Store->getValue(), DAG.getConstant(i, MVT::i32));
748     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
749                               Store->getBasePtr(),
750                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
751                                             PtrVT));
752     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
753                          MachinePointerInfo(Store->getMemOperand()->getValue()),
754                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
755                          Store->getAlignment()));
756   }
757   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains.data(), NumElts);
758 }
759
760 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
761   SDLoc DL(Op);
762   LoadSDNode *Load = cast<LoadSDNode>(Op);
763   ISD::LoadExtType ExtType = Load->getExtensionType();
764   EVT VT = Op.getValueType();
765   EVT MemVT = Load->getMemoryVT();
766
767   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
768     // We can do the extload to 32-bits, and then need to separately extend to
769     // 64-bits.
770
771     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
772                                        Load->getChain(),
773                                        Load->getBasePtr(),
774                                        MemVT,
775                                        Load->getMemOperand());
776     return DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32);
777   }
778
779   // Lower loads constant address space global variable loads
780   if (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
781       isa<GlobalVariable>(GetUnderlyingObject(Load->getPointerInfo().V))) {
782
783     SDValue Ptr = DAG.getZExtOrTrunc(Load->getBasePtr(), DL,
784         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
785     Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr,
786         DAG.getConstant(2, MVT::i32));
787     return DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
788                        Load->getChain(), Ptr,
789                        DAG.getTargetConstant(0, MVT::i32), Op.getOperand(2));
790   }
791
792   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
793       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
794     return SDValue();
795
796
797   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
798                             DAG.getConstant(2, MVT::i32));
799   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
800                             Load->getChain(), Ptr,
801                             DAG.getTargetConstant(0, MVT::i32),
802                             Op.getOperand(2));
803   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
804                                 Load->getBasePtr(),
805                                 DAG.getConstant(0x3, MVT::i32));
806   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
807                                  DAG.getConstant(3, MVT::i32));
808
809   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
810
811   EVT MemEltVT = MemVT.getScalarType();
812   if (ExtType == ISD::SEXTLOAD) {
813     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
814     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode);
815   }
816
817   return DAG.getZeroExtendInReg(Ret, DL, MemEltVT);
818 }
819
820 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
821   SDLoc DL(Op);
822   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
823   if (Result.getNode()) {
824     return Result;
825   }
826
827   StoreSDNode *Store = cast<StoreSDNode>(Op);
828   SDValue Chain = Store->getChain();
829   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
830        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
831       Store->getValue().getValueType().isVector()) {
832     return SplitVectorStore(Op, DAG);
833   }
834
835   EVT MemVT = Store->getMemoryVT();
836   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
837       MemVT.bitsLT(MVT::i32)) {
838     unsigned Mask = 0;
839     if (Store->getMemoryVT() == MVT::i8) {
840       Mask = 0xff;
841     } else if (Store->getMemoryVT() == MVT::i16) {
842       Mask = 0xffff;
843     }
844     SDValue BasePtr = Store->getBasePtr();
845     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
846                               DAG.getConstant(2, MVT::i32));
847     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
848                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
849
850     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
851                                   DAG.getConstant(0x3, MVT::i32));
852
853     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
854                                    DAG.getConstant(3, MVT::i32));
855
856     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
857                                     Store->getValue());
858
859     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
860
861     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
862                                        MaskedValue, ShiftAmt);
863
864     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
865                                   ShiftAmt);
866     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
867                           DAG.getConstant(0xffffffff, MVT::i32));
868     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
869
870     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
871     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
872                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
873   }
874   return SDValue();
875 }
876
877 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
878     SelectionDAG &DAG) const {
879   SDLoc DL(Op);
880   EVT VT = Op.getValueType();
881
882   SDValue Num = Op.getOperand(0);
883   SDValue Den = Op.getOperand(1);
884
885   SmallVector<SDValue, 8> Results;
886
887   // RCP =  URECIP(Den) = 2^32 / Den + e
888   // e is rounding error.
889   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
890
891   // RCP_LO = umulo(RCP, Den) */
892   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
893
894   // RCP_HI = mulhu (RCP, Den) */
895   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
896
897   // NEG_RCP_LO = -RCP_LO
898   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
899                                                      RCP_LO);
900
901   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
902   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
903                                            NEG_RCP_LO, RCP_LO,
904                                            ISD::SETEQ);
905   // Calculate the rounding error from the URECIP instruction
906   // E = mulhu(ABS_RCP_LO, RCP)
907   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
908
909   // RCP_A_E = RCP + E
910   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
911
912   // RCP_S_E = RCP - E
913   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
914
915   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
916   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
917                                      RCP_A_E, RCP_S_E,
918                                      ISD::SETEQ);
919   // Quotient = mulhu(Tmp0, Num)
920   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
921
922   // Num_S_Remainder = Quotient * Den
923   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
924
925   // Remainder = Num - Num_S_Remainder
926   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
927
928   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
929   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
930                                                  DAG.getConstant(-1, VT),
931                                                  DAG.getConstant(0, VT),
932                                                  ISD::SETUGE);
933   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
934   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
935                                                   Num_S_Remainder,
936                                                   DAG.getConstant(-1, VT),
937                                                   DAG.getConstant(0, VT),
938                                                   ISD::SETUGE);
939   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
940   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
941                                                Remainder_GE_Zero);
942
943   // Calculate Division result:
944
945   // Quotient_A_One = Quotient + 1
946   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
947                                                          DAG.getConstant(1, VT));
948
949   // Quotient_S_One = Quotient - 1
950   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
951                                                          DAG.getConstant(1, VT));
952
953   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
954   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
955                                      Quotient, Quotient_A_One, ISD::SETEQ);
956
957   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
958   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
959                             Quotient_S_One, Div, ISD::SETEQ);
960
961   // Calculate Rem result:
962
963   // Remainder_S_Den = Remainder - Den
964   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
965
966   // Remainder_A_Den = Remainder + Den
967   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
968
969   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
970   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
971                                     Remainder, Remainder_S_Den, ISD::SETEQ);
972
973   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
974   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
975                             Remainder_A_Den, Rem, ISD::SETEQ);
976   SDValue Ops[2] = {
977     Div,
978     Rem
979   };
980   return DAG.getMergeValues(Ops, 2, DL);
981 }
982
983 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
984                                                SelectionDAG &DAG) const {
985   SDValue S0 = Op.getOperand(0);
986   SDLoc DL(Op);
987   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
988     return SDValue();
989
990   // f32 uint_to_fp i64
991   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
992                            DAG.getConstant(0, MVT::i32));
993   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
994   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
995                            DAG.getConstant(1, MVT::i32));
996   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
997   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
998                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
999   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
1000
1001 }
1002
1003 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
1004                                                       unsigned BitsDiff,
1005                                                       SelectionDAG &DAG) const {
1006   MVT VT = Op.getSimpleValueType();
1007   SDLoc DL(Op);
1008   SDValue Shift = DAG.getConstant(BitsDiff, VT);
1009   // Shift left by 'Shift' bits.
1010   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
1011   // Signed shift Right by 'Shift' bits.
1012   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
1013 }
1014
1015 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1016                                                      SelectionDAG &DAG) const {
1017   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1018   MVT VT = Op.getSimpleValueType();
1019   MVT ScalarVT = VT.getScalarType();
1020
1021   unsigned SrcBits = ExtraVT.getScalarType().getSizeInBits();
1022   unsigned DestBits = ScalarVT.getSizeInBits();
1023   unsigned BitsDiff = DestBits - SrcBits;
1024
1025   if (!Subtarget->hasBFE())
1026     return ExpandSIGN_EXTEND_INREG(Op, BitsDiff, DAG);
1027
1028   SDValue Src = Op.getOperand(0);
1029   if (VT.isVector()) {
1030     SDLoc DL(Op);
1031     // Need to scalarize this, and revisit each of the scalars later.
1032     // TODO: Don't scalarize on Evergreen?
1033     unsigned NElts = VT.getVectorNumElements();
1034     SmallVector<SDValue, 8> Args;
1035     DAG.ExtractVectorElements(Src, Args);
1036
1037     SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
1038     for (unsigned I = 0; I < NElts; ++I)
1039       Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
1040
1041     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args.data(), Args.size());
1042   }
1043
1044   if (SrcBits == 32) {
1045     SDLoc DL(Op);
1046
1047     // If the source is 32-bits, this is really half of a 2-register pair, and
1048     // we need to discard the unused half of the pair.
1049     SDValue TruncSrc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
1050     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, TruncSrc);
1051   }
1052
1053   unsigned NElts = VT.isVector() ? VT.getVectorNumElements() : 1;
1054
1055   // TODO: Match 64-bit BFE. SI has a 64-bit BFE, but it's scalar only so it
1056   // might not be worth the effort, and will need to expand to shifts when
1057   // fixing SGPR copies.
1058   if (SrcBits < 32 && DestBits <= 32) {
1059     SDLoc DL(Op);
1060     MVT ExtVT = (NElts == 1) ? MVT::i32 : MVT::getVectorVT(MVT::i32, NElts);
1061
1062     if (DestBits != 32)
1063       Src = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Src);
1064
1065     // FIXME: This should use TargetConstant, but that hits assertions for
1066     // Evergreen.
1067     SDValue Ext = DAG.getNode(AMDGPUISD::BFE_I32, DL, ExtVT,
1068                               Op.getOperand(0), // Operand
1069                               DAG.getConstant(0, ExtVT), // Offset
1070                               DAG.getConstant(SrcBits, ExtVT)); // Width
1071
1072     // Truncate to the original type if necessary.
1073     if (ScalarVT == MVT::i32)
1074       return Ext;
1075     return DAG.getNode(ISD::TRUNCATE, DL, VT, Ext);
1076   }
1077
1078   // For small types, extend to 32-bits first.
1079   if (SrcBits < 32) {
1080     SDLoc DL(Op);
1081     MVT ExtVT = (NElts == 1) ? MVT::i32 : MVT::getVectorVT(MVT::i32, NElts);
1082
1083     SDValue TruncSrc = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, Src);
1084     SDValue Ext32 = DAG.getNode(AMDGPUISD::BFE_I32,
1085                                 DL,
1086                                 ExtVT,
1087                                 TruncSrc, // Operand
1088                                 DAG.getConstant(0, ExtVT), // Offset
1089                                 DAG.getConstant(SrcBits, ExtVT)); // Width
1090
1091     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Ext32);
1092   }
1093
1094   // For everything else, use the standard bitshift expansion.
1095   return ExpandSIGN_EXTEND_INREG(Op, BitsDiff, DAG);
1096 }
1097
1098 //===----------------------------------------------------------------------===//
1099 // Custom DAG optimizations
1100 //===----------------------------------------------------------------------===//
1101
1102 static bool isU24(SDValue Op, SelectionDAG &DAG) {
1103   APInt KnownZero, KnownOne;
1104   EVT VT = Op.getValueType();
1105   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
1106
1107   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
1108 }
1109
1110 static bool isI24(SDValue Op, SelectionDAG &DAG) {
1111   EVT VT = Op.getValueType();
1112
1113   // In order for this to be a signed 24-bit value, bit 23, must
1114   // be a sign bit.
1115   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
1116                                      // as unsigned 24-bit values.
1117          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
1118 }
1119
1120 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
1121
1122   SelectionDAG &DAG = DCI.DAG;
1123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1124   EVT VT = Op.getValueType();
1125
1126   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
1127   APInt KnownZero, KnownOne;
1128   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
1129   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
1130     DCI.CommitTargetLoweringOpt(TLO);
1131 }
1132
1133 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
1134                                             DAGCombinerInfo &DCI) const {
1135   SelectionDAG &DAG = DCI.DAG;
1136   SDLoc DL(N);
1137
1138   switch(N->getOpcode()) {
1139     default: break;
1140     case ISD::MUL: {
1141       EVT VT = N->getValueType(0);
1142       SDValue N0 = N->getOperand(0);
1143       SDValue N1 = N->getOperand(1);
1144       SDValue Mul;
1145
1146       // FIXME: Add support for 24-bit multiply with 64-bit output on SI.
1147       if (VT.isVector() || VT.getSizeInBits() > 32)
1148         break;
1149
1150       if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
1151         N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
1152         N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
1153         Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
1154       } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
1155         N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
1156         N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
1157         Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
1158       } else {
1159         break;
1160       }
1161
1162       SDValue Reg = DAG.getSExtOrTrunc(Mul, DL, VT);
1163
1164       return Reg;
1165     }
1166     case AMDGPUISD::MUL_I24:
1167     case AMDGPUISD::MUL_U24: {
1168       SDValue N0 = N->getOperand(0);
1169       SDValue N1 = N->getOperand(1);
1170       simplifyI24(N0, DCI);
1171       simplifyI24(N1, DCI);
1172       return SDValue();
1173     }
1174   }
1175   return SDValue();
1176 }
1177
1178 //===----------------------------------------------------------------------===//
1179 // Helper functions
1180 //===----------------------------------------------------------------------===//
1181
1182 void AMDGPUTargetLowering::getOriginalFunctionArgs(
1183                                SelectionDAG &DAG,
1184                                const Function *F,
1185                                const SmallVectorImpl<ISD::InputArg> &Ins,
1186                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
1187
1188   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1189     if (Ins[i].ArgVT == Ins[i].VT) {
1190       OrigIns.push_back(Ins[i]);
1191       continue;
1192     }
1193
1194     EVT VT;
1195     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
1196       // Vector has been split into scalars.
1197       VT = Ins[i].ArgVT.getVectorElementType();
1198     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
1199                Ins[i].ArgVT.getVectorElementType() !=
1200                Ins[i].VT.getVectorElementType()) {
1201       // Vector elements have been promoted
1202       VT = Ins[i].ArgVT;
1203     } else {
1204       // Vector has been spilt into smaller vectors.
1205       VT = Ins[i].VT;
1206     }
1207
1208     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
1209                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
1210     OrigIns.push_back(Arg);
1211   }
1212 }
1213
1214 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
1215   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1216     return CFP->isExactlyValue(1.0);
1217   }
1218   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1219     return C->isAllOnesValue();
1220   }
1221   return false;
1222 }
1223
1224 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
1225   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1226     return CFP->getValueAPF().isZero();
1227   }
1228   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1229     return C->isNullValue();
1230   }
1231   return false;
1232 }
1233
1234 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1235                                                   const TargetRegisterClass *RC,
1236                                                    unsigned Reg, EVT VT) const {
1237   MachineFunction &MF = DAG.getMachineFunction();
1238   MachineRegisterInfo &MRI = MF.getRegInfo();
1239   unsigned VirtualRegister;
1240   if (!MRI.isLiveIn(Reg)) {
1241     VirtualRegister = MRI.createVirtualRegister(RC);
1242     MRI.addLiveIn(Reg, VirtualRegister);
1243   } else {
1244     VirtualRegister = MRI.getLiveInVirtReg(Reg);
1245   }
1246   return DAG.getRegister(VirtualRegister, VT);
1247 }
1248
1249 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
1250
1251 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
1252   switch (Opcode) {
1253   default: return 0;
1254   // AMDIL DAG nodes
1255   NODE_NAME_CASE(CALL);
1256   NODE_NAME_CASE(UMUL);
1257   NODE_NAME_CASE(DIV_INF);
1258   NODE_NAME_CASE(RET_FLAG);
1259   NODE_NAME_CASE(BRANCH_COND);
1260
1261   // AMDGPU DAG nodes
1262   NODE_NAME_CASE(DWORDADDR)
1263   NODE_NAME_CASE(FRACT)
1264   NODE_NAME_CASE(FMAX)
1265   NODE_NAME_CASE(SMAX)
1266   NODE_NAME_CASE(UMAX)
1267   NODE_NAME_CASE(FMIN)
1268   NODE_NAME_CASE(SMIN)
1269   NODE_NAME_CASE(UMIN)
1270   NODE_NAME_CASE(BFE_U32)
1271   NODE_NAME_CASE(BFE_I32)
1272   NODE_NAME_CASE(BFI)
1273   NODE_NAME_CASE(BFM)
1274   NODE_NAME_CASE(MUL_U24)
1275   NODE_NAME_CASE(MUL_I24)
1276   NODE_NAME_CASE(URECIP)
1277   NODE_NAME_CASE(DOT4)
1278   NODE_NAME_CASE(EXPORT)
1279   NODE_NAME_CASE(CONST_ADDRESS)
1280   NODE_NAME_CASE(REGISTER_LOAD)
1281   NODE_NAME_CASE(REGISTER_STORE)
1282   NODE_NAME_CASE(LOAD_CONSTANT)
1283   NODE_NAME_CASE(LOAD_INPUT)
1284   NODE_NAME_CASE(SAMPLE)
1285   NODE_NAME_CASE(SAMPLEB)
1286   NODE_NAME_CASE(SAMPLED)
1287   NODE_NAME_CASE(SAMPLEL)
1288   NODE_NAME_CASE(STORE_MSKOR)
1289   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
1290   }
1291 }
1292
1293 static void computeMaskedBitsForMinMax(const SDValue Op0,
1294                                        const SDValue Op1,
1295                                        APInt &KnownZero,
1296                                        APInt &KnownOne,
1297                                        const SelectionDAG &DAG,
1298                                        unsigned Depth) {
1299   APInt Op0Zero, Op0One;
1300   APInt Op1Zero, Op1One;
1301   DAG.ComputeMaskedBits(Op0, Op0Zero, Op0One, Depth);
1302   DAG.ComputeMaskedBits(Op1, Op1Zero, Op1One, Depth);
1303
1304   KnownZero = Op0Zero & Op1Zero;
1305   KnownOne = Op0One & Op1One;
1306 }
1307
1308 void AMDGPUTargetLowering::computeMaskedBitsForTargetNode(
1309   const SDValue Op,
1310   APInt &KnownZero,
1311   APInt &KnownOne,
1312   const SelectionDAG &DAG,
1313   unsigned Depth) const {
1314
1315   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
1316   unsigned Opc = Op.getOpcode();
1317   switch (Opc) {
1318   case ISD::INTRINSIC_WO_CHAIN: {
1319     // FIXME: The intrinsic should just use the node.
1320     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
1321     case AMDGPUIntrinsic::AMDGPU_imax:
1322     case AMDGPUIntrinsic::AMDGPU_umax:
1323     case AMDGPUIntrinsic::AMDGPU_imin:
1324     case AMDGPUIntrinsic::AMDGPU_umin:
1325       computeMaskedBitsForMinMax(Op.getOperand(1), Op.getOperand(2),
1326                                  KnownZero, KnownOne, DAG, Depth);
1327       break;
1328     default:
1329       break;
1330     }
1331
1332     break;
1333   }
1334   case AMDGPUISD::SMAX:
1335   case AMDGPUISD::UMAX:
1336   case AMDGPUISD::SMIN:
1337   case AMDGPUISD::UMIN:
1338     computeMaskedBitsForMinMax(Op.getOperand(0), Op.getOperand(1),
1339                                KnownZero, KnownOne, DAG, Depth);
1340     break;
1341   default:
1342     break;
1343   }
1344 }