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