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