AMDGPU/SI: Remove REGISTER_STORE/REGISTER_LOAD code which is now dead
[oota-llvm.git] / lib / Target / AMDGPU / AMDGPUISelDAGToDAG.cpp
1 //===-- AMDILISelDAGToDAG.cpp - A dag to dag inst selector for AMDIL ------===//
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 Defines an instruction selector for the AMDGPU target.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "AMDGPUInstrInfo.h"
15 #include "AMDGPUISelLowering.h" // For AMDGPUISD
16 #include "AMDGPURegisterInfo.h"
17 #include "AMDGPUSubtarget.h"
18 #include "R600InstrInfo.h"
19 #include "SIDefines.h"
20 #include "SIISelLowering.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/IR/Function.h"
29
30 using namespace llvm;
31
32 //===----------------------------------------------------------------------===//
33 // Instruction Selector Implementation
34 //===----------------------------------------------------------------------===//
35
36 namespace {
37 /// AMDGPU specific code to select AMDGPU machine instructions for
38 /// SelectionDAG operations.
39 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
40   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
41   // make the right decision when generating code for different targets.
42   const AMDGPUSubtarget *Subtarget;
43
44 public:
45   AMDGPUDAGToDAGISel(TargetMachine &TM);
46   virtual ~AMDGPUDAGToDAGISel();
47   bool runOnMachineFunction(MachineFunction &MF) override;
48   SDNode *Select(SDNode *N) override;
49   const char *getPassName() const override;
50   void PreprocessISelDAG() override;
51   void PostprocessISelDAG() override;
52
53 private:
54   bool isInlineImmediate(SDNode *N) const;
55   bool FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg, SDValue &Abs,
56                    const R600InstrInfo *TII);
57   bool FoldOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
58   bool FoldDotOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
59
60   // Complex pattern selectors
61   bool SelectADDRParam(SDValue Addr, SDValue& R1, SDValue& R2);
62   bool SelectADDR(SDValue N, SDValue &R1, SDValue &R2);
63   bool SelectADDR64(SDValue N, SDValue &R1, SDValue &R2);
64
65   static bool checkType(const Value *ptr, unsigned int addrspace);
66   static bool checkPrivateAddress(const MachineMemOperand *Op);
67
68   static bool isGlobalStore(const StoreSDNode *N);
69   static bool isFlatStore(const StoreSDNode *N);
70   static bool isPrivateStore(const StoreSDNode *N);
71   static bool isLocalStore(const StoreSDNode *N);
72   static bool isRegionStore(const StoreSDNode *N);
73
74   bool isCPLoad(const LoadSDNode *N) const;
75   bool isConstantLoad(const LoadSDNode *N, int cbID) const;
76   bool isGlobalLoad(const LoadSDNode *N) const;
77   bool isFlatLoad(const LoadSDNode *N) const;
78   bool isParamLoad(const LoadSDNode *N) const;
79   bool isPrivateLoad(const LoadSDNode *N) const;
80   bool isLocalLoad(const LoadSDNode *N) const;
81   bool isRegionLoad(const LoadSDNode *N) const;
82
83   SDNode *glueCopyToM0(SDNode *N) const;
84
85   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
86   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
87   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
88                                        SDValue& Offset);
89   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
90   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
91   bool isDSOffsetLegal(const SDValue &Base, unsigned Offset,
92                        unsigned OffsetBits) const;
93   bool SelectDS1Addr1Offset(SDValue Ptr, SDValue &Base, SDValue &Offset) const;
94   bool SelectDS64Bit4ByteAligned(SDValue Ptr, SDValue &Base, SDValue &Offset0,
95                                  SDValue &Offset1) const;
96   void SelectMUBUF(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
97                    SDValue &SOffset, SDValue &Offset, SDValue &Offen,
98                    SDValue &Idxen, SDValue &Addr64, SDValue &GLC, SDValue &SLC,
99                    SDValue &TFE) const;
100   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
101                          SDValue &SOffset, SDValue &Offset, SDValue &GLC,
102                          SDValue &SLC, SDValue &TFE) const;
103   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
104                          SDValue &VAddr, SDValue &SOffset, SDValue &Offset,
105                          SDValue &SLC) const;
106   bool SelectMUBUFScratch(SDValue Addr, SDValue &RSrc, SDValue &VAddr,
107                           SDValue &SOffset, SDValue &ImmOffset) const;
108   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &SOffset,
109                          SDValue &Offset, SDValue &GLC, SDValue &SLC,
110                          SDValue &TFE) const;
111   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
112                          SDValue &Offset, SDValue &GLC) const;
113   bool SelectSMRDOffset(SDValue ByteOffsetNode, SDValue &Offset,
114                         bool &Imm) const;
115   bool SelectSMRD(SDValue Addr, SDValue &SBase, SDValue &Offset,
116                   bool &Imm) const;
117   bool SelectSMRDImm(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
118   bool SelectSMRDImm32(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
119   bool SelectSMRDSgpr(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
120   bool SelectSMRDBufferImm(SDValue Addr, SDValue &Offset) const;
121   bool SelectSMRDBufferImm32(SDValue Addr, SDValue &Offset) const;
122   bool SelectSMRDBufferSgpr(SDValue Addr, SDValue &Offset) const;
123   SDNode *SelectAddrSpaceCast(SDNode *N);
124   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
125   bool SelectVOP3NoMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
126   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
127                        SDValue &Clamp, SDValue &Omod) const;
128   bool SelectVOP3NoMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
129                          SDValue &Clamp, SDValue &Omod) const;
130
131   bool SelectVOP3Mods0Clamp(SDValue In, SDValue &Src, SDValue &SrcMods,
132                             SDValue &Omod) const;
133   bool SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src, SDValue &SrcMods,
134                                  SDValue &Clamp,
135                                  SDValue &Omod) const;
136
137   SDNode *SelectADD_SUB_I64(SDNode *N);
138   SDNode *SelectDIV_SCALE(SDNode *N);
139
140   SDNode *getS_BFE(unsigned Opcode, SDLoc DL, SDValue Val,
141                    uint32_t Offset, uint32_t Width);
142   SDNode *SelectS_BFEFromShifts(SDNode *N);
143   SDNode *SelectS_BFE(SDNode *N);
144
145   // Include the pieces autogenerated from the target description.
146 #include "AMDGPUGenDAGISel.inc"
147 };
148 }  // end anonymous namespace
149
150 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
151 // DAG, ready for instruction scheduling.
152 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM) {
153   return new AMDGPUDAGToDAGISel(TM);
154 }
155
156 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
157     : SelectionDAGISel(TM) {}
158
159 bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
160   Subtarget = &static_cast<const AMDGPUSubtarget &>(MF.getSubtarget());
161   return SelectionDAGISel::runOnMachineFunction(MF);
162 }
163
164 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
165 }
166
167 bool AMDGPUDAGToDAGISel::isInlineImmediate(SDNode *N) const {
168   const SITargetLowering *TL
169       = static_cast<const SITargetLowering *>(getTargetLowering());
170   return TL->analyzeImmediate(N) == 0;
171 }
172
173 /// \brief Determine the register class for \p OpNo
174 /// \returns The register class of the virtual register that will be used for
175 /// the given operand number \OpNo or NULL if the register class cannot be
176 /// determined.
177 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
178                                                           unsigned OpNo) const {
179   if (!N->isMachineOpcode())
180     return nullptr;
181
182   switch (N->getMachineOpcode()) {
183   default: {
184     const MCInstrDesc &Desc =
185         Subtarget->getInstrInfo()->get(N->getMachineOpcode());
186     unsigned OpIdx = Desc.getNumDefs() + OpNo;
187     if (OpIdx >= Desc.getNumOperands())
188       return nullptr;
189     int RegClass = Desc.OpInfo[OpIdx].RegClass;
190     if (RegClass == -1)
191       return nullptr;
192
193     return Subtarget->getRegisterInfo()->getRegClass(RegClass);
194   }
195   case AMDGPU::REG_SEQUENCE: {
196     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
197     const TargetRegisterClass *SuperRC =
198         Subtarget->getRegisterInfo()->getRegClass(RCID);
199
200     SDValue SubRegOp = N->getOperand(OpNo + 1);
201     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
202     return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
203                                                               SubRegIdx);
204   }
205   }
206 }
207
208 bool AMDGPUDAGToDAGISel::SelectADDRParam(
209   SDValue Addr, SDValue& R1, SDValue& R2) {
210
211   if (Addr.getOpcode() == ISD::FrameIndex) {
212     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
213       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
214       R2 = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
215     } else {
216       R1 = Addr;
217       R2 = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
218     }
219   } else if (Addr.getOpcode() == ISD::ADD) {
220     R1 = Addr.getOperand(0);
221     R2 = Addr.getOperand(1);
222   } else {
223     R1 = Addr;
224     R2 = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
225   }
226   return true;
227 }
228
229 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
230   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
231       Addr.getOpcode() == ISD::TargetGlobalAddress) {
232     return false;
233   }
234   return SelectADDRParam(Addr, R1, R2);
235 }
236
237
238 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
239   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
240       Addr.getOpcode() == ISD::TargetGlobalAddress) {
241     return false;
242   }
243
244   if (Addr.getOpcode() == ISD::FrameIndex) {
245     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
246       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
247       R2 = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i64);
248     } else {
249       R1 = Addr;
250       R2 = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i64);
251     }
252   } else if (Addr.getOpcode() == ISD::ADD) {
253     R1 = Addr.getOperand(0);
254     R2 = Addr.getOperand(1);
255   } else {
256     R1 = Addr;
257     R2 = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i64);
258   }
259   return true;
260 }
261
262 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N) const {
263   if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
264       !checkType(cast<MemSDNode>(N)->getMemOperand()->getValue(),
265                  AMDGPUAS::LOCAL_ADDRESS))
266     return N;
267
268   const SITargetLowering& Lowering =
269       *static_cast<const SITargetLowering*>(getTargetLowering());
270
271   // Write max value to m0 before each load operation
272
273   SDValue M0 = Lowering.copyToM0(*CurDAG, CurDAG->getEntryNode(), SDLoc(N),
274                                  CurDAG->getTargetConstant(-1, SDLoc(N), MVT::i32));
275
276   SDValue Glue = M0.getValue(1);
277
278   SmallVector <SDValue, 8> Ops;
279   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
280      Ops.push_back(N->getOperand(i));
281   }
282   Ops.push_back(Glue);
283   CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), Ops);
284
285   return N;
286 }
287
288 static unsigned selectSGPRVectorRegClassID(unsigned NumVectorElts) {
289   switch (NumVectorElts) {
290   case 1:
291     return AMDGPU::SReg_32RegClassID;
292   case 2:
293     return AMDGPU::SReg_64RegClassID;
294   case 4:
295     return AMDGPU::SReg_128RegClassID;
296   case 8:
297     return AMDGPU::SReg_256RegClassID;
298   case 16:
299     return AMDGPU::SReg_512RegClassID;
300   }
301
302   llvm_unreachable("invalid vector size");
303 }
304
305 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
306   unsigned int Opc = N->getOpcode();
307   if (N->isMachineOpcode()) {
308     N->setNodeId(-1);
309     return nullptr;   // Already selected.
310   }
311
312   if (isa<AtomicSDNode>(N))
313     N = glueCopyToM0(N);
314
315   switch (Opc) {
316   default: break;
317   // We are selecting i64 ADD here instead of custom lower it during
318   // DAG legalization, so we can fold some i64 ADDs used for address
319   // calculation into the LOAD and STORE instructions.
320   case ISD::ADD:
321   case ISD::SUB: {
322     if (N->getValueType(0) != MVT::i64 ||
323         Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
324       break;
325
326     return SelectADD_SUB_I64(N);
327   }
328   case ISD::SCALAR_TO_VECTOR:
329   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
330   case ISD::BUILD_VECTOR: {
331     unsigned RegClassID;
332     const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
333     EVT VT = N->getValueType(0);
334     unsigned NumVectorElts = VT.getVectorNumElements();
335     EVT EltVT = VT.getVectorElementType();
336     assert(EltVT.bitsEq(MVT::i32));
337     if (Subtarget->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
338       RegClassID = selectSGPRVectorRegClassID(NumVectorElts);
339     } else {
340       // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
341       // that adds a 128 bits reg copy when going through TwoAddressInstructions
342       // pass. We want to avoid 128 bits copies as much as possible because they
343       // can't be bundled by our scheduler.
344       switch(NumVectorElts) {
345       case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
346       case 4:
347         if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
348           RegClassID = AMDGPU::R600_Reg128VerticalRegClassID;
349         else
350           RegClassID = AMDGPU::R600_Reg128RegClassID;
351         break;
352       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
353       }
354     }
355
356     SDLoc DL(N);
357     SDValue RegClass = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
358
359     if (NumVectorElts == 1) {
360       return CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT,
361                                   N->getOperand(0), RegClass);
362     }
363
364     assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
365                                   "supported yet");
366     // 16 = Max Num Vector Elements
367     // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
368     // 1 = Vector Register Class
369     SmallVector<SDValue, 16 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
370
371     RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
372     bool IsRegSeq = true;
373     unsigned NOps = N->getNumOperands();
374     for (unsigned i = 0; i < NOps; i++) {
375       // XXX: Why is this here?
376       if (isa<RegisterSDNode>(N->getOperand(i))) {
377         IsRegSeq = false;
378         break;
379       }
380       RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
381       RegSeqArgs[1 + (2 * i) + 1] =
382               CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), DL,
383                                         MVT::i32);
384     }
385
386     if (NOps != NumVectorElts) {
387       // Fill in the missing undef elements if this was a scalar_to_vector.
388       assert(Opc == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
389
390       MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
391                                                      DL, EltVT);
392       for (unsigned i = NOps; i < NumVectorElts; ++i) {
393         RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
394         RegSeqArgs[1 + (2 * i) + 1] =
395           CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), DL, MVT::i32);
396       }
397     }
398
399     if (!IsRegSeq)
400       break;
401     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
402                                 RegSeqArgs);
403   }
404   case ISD::BUILD_PAIR: {
405     SDValue RC, SubReg0, SubReg1;
406     if (Subtarget->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
407       break;
408     }
409     SDLoc DL(N);
410     if (N->getValueType(0) == MVT::i128) {
411       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32);
412       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32);
413       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32);
414     } else if (N->getValueType(0) == MVT::i64) {
415       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32);
416       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
417       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
418     } else {
419       llvm_unreachable("Unhandled value type for BUILD_PAIR");
420     }
421     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
422                             N->getOperand(1), SubReg1 };
423     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
424                                   DL, N->getValueType(0), Ops);
425   }
426
427   case ISD::Constant:
428   case ISD::ConstantFP: {
429     if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
430         N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
431       break;
432
433     uint64_t Imm;
434     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
435       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
436     else {
437       ConstantSDNode *C = cast<ConstantSDNode>(N);
438       Imm = C->getZExtValue();
439     }
440
441     SDLoc DL(N);
442     SDNode *Lo = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
443                                 CurDAG->getConstant(Imm & 0xFFFFFFFF, DL,
444                                                     MVT::i32));
445     SDNode *Hi = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
446                                 CurDAG->getConstant(Imm >> 32, DL, MVT::i32));
447     const SDValue Ops[] = {
448       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
449       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
450       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
451     };
452
453     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
454                                   N->getValueType(0), Ops);
455   }
456   case ISD::LOAD:
457   case ISD::STORE: {
458     N = glueCopyToM0(N);
459     break;
460   }
461
462   case AMDGPUISD::BFE_I32:
463   case AMDGPUISD::BFE_U32: {
464     if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
465       break;
466
467     // There is a scalar version available, but unlike the vector version which
468     // has a separate operand for the offset and width, the scalar version packs
469     // the width and offset into a single operand. Try to move to the scalar
470     // version if the offsets are constant, so that we can try to keep extended
471     // loads of kernel arguments in SGPRs.
472
473     // TODO: Technically we could try to pattern match scalar bitshifts of
474     // dynamic values, but it's probably not useful.
475     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
476     if (!Offset)
477       break;
478
479     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
480     if (!Width)
481       break;
482
483     bool Signed = Opc == AMDGPUISD::BFE_I32;
484
485     uint32_t OffsetVal = Offset->getZExtValue();
486     uint32_t WidthVal = Width->getZExtValue();
487
488     return getS_BFE(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32, SDLoc(N),
489                     N->getOperand(0), OffsetVal, WidthVal);
490   }
491   case AMDGPUISD::DIV_SCALE: {
492     return SelectDIV_SCALE(N);
493   }
494   case ISD::CopyToReg: {
495     const SITargetLowering& Lowering =
496       *static_cast<const SITargetLowering*>(getTargetLowering());
497     Lowering.legalizeTargetIndependentNode(N, *CurDAG);
498     break;
499   }
500   case ISD::ADDRSPACECAST:
501     return SelectAddrSpaceCast(N);
502   case ISD::AND:
503   case ISD::SRL:
504   case ISD::SRA:
505     if (N->getValueType(0) != MVT::i32 ||
506         Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
507       break;
508
509     return SelectS_BFE(N);
510   }
511
512   return SelectCode(N);
513 }
514
515 bool AMDGPUDAGToDAGISel::checkType(const Value *Ptr, unsigned AS) {
516   assert(AS != 0 && "Use checkPrivateAddress instead.");
517   if (!Ptr)
518     return false;
519
520   return Ptr->getType()->getPointerAddressSpace() == AS;
521 }
522
523 bool AMDGPUDAGToDAGISel::checkPrivateAddress(const MachineMemOperand *Op) {
524   if (Op->getPseudoValue())
525     return true;
526
527   if (PointerType *PT = dyn_cast<PointerType>(Op->getValue()->getType()))
528     return PT->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS;
529
530   return false;
531 }
532
533 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
534   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
535 }
536
537 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
538   const Value *MemVal = N->getMemOperand()->getValue();
539   return (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
540           !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
541           !checkType(MemVal, AMDGPUAS::REGION_ADDRESS));
542 }
543
544 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
545   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
546 }
547
548 bool AMDGPUDAGToDAGISel::isFlatStore(const StoreSDNode *N) {
549   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::FLAT_ADDRESS);
550 }
551
552 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
553   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
554 }
555
556 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int CbId) const {
557   const Value *MemVal = N->getMemOperand()->getValue();
558   if (CbId == -1)
559     return checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS);
560
561   return checkType(MemVal, AMDGPUAS::CONSTANT_BUFFER_0 + CbId);
562 }
563
564 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
565   if (N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS)
566     if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
567         N->getMemoryVT().bitsLT(MVT::i32))
568       return true;
569
570   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
571 }
572
573 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
574   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::PARAM_I_ADDRESS);
575 }
576
577 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
578   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
579 }
580
581 bool AMDGPUDAGToDAGISel::isFlatLoad(const  LoadSDNode *N) const {
582   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::FLAT_ADDRESS);
583 }
584
585 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
586   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
587 }
588
589 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
590   MachineMemOperand *MMO = N->getMemOperand();
591   if (checkPrivateAddress(N->getMemOperand())) {
592     if (MMO) {
593       const PseudoSourceValue *PSV = MMO->getPseudoValue();
594       if (PSV && PSV->isConstantPool()) {
595         return true;
596       }
597     }
598   }
599   return false;
600 }
601
602 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
603   if (checkPrivateAddress(N->getMemOperand())) {
604     // Check to make sure we are not a constant pool load or a constant load
605     // that is marked as a private load
606     if (isCPLoad(N) || isConstantLoad(N, -1)) {
607       return false;
608     }
609   }
610
611   const Value *MemVal = N->getMemOperand()->getValue();
612   if (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
613       !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
614       !checkType(MemVal, AMDGPUAS::FLAT_ADDRESS) &&
615       !checkType(MemVal, AMDGPUAS::REGION_ADDRESS) &&
616       !checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS) &&
617       !checkType(MemVal, AMDGPUAS::PARAM_D_ADDRESS) &&
618       !checkType(MemVal, AMDGPUAS::PARAM_I_ADDRESS)) {
619     return true;
620   }
621   return false;
622 }
623
624 const char *AMDGPUDAGToDAGISel::getPassName() const {
625   return "AMDGPU DAG->DAG Pattern Instruction Selection";
626 }
627
628 #ifdef DEBUGTMP
629 #undef INT64_C
630 #endif
631 #undef DEBUGTMP
632
633 //===----------------------------------------------------------------------===//
634 // Complex Patterns
635 //===----------------------------------------------------------------------===//
636
637 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
638                                                          SDValue& IntPtr) {
639   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
640     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, SDLoc(Addr),
641                                        true);
642     return true;
643   }
644   return false;
645 }
646
647 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
648     SDValue& BaseReg, SDValue &Offset) {
649   if (!isa<ConstantSDNode>(Addr)) {
650     BaseReg = Addr;
651     Offset = CurDAG->getIntPtrConstant(0, SDLoc(Addr), true);
652     return true;
653   }
654   return false;
655 }
656
657 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
658                                            SDValue &Offset) {
659   ConstantSDNode *IMMOffset;
660
661   if (Addr.getOpcode() == ISD::ADD
662       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
663       && isInt<16>(IMMOffset->getZExtValue())) {
664
665       Base = Addr.getOperand(0);
666       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
667                                          MVT::i32);
668       return true;
669   // If the pointer address is constant, we can move it to the offset field.
670   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
671              && isInt<16>(IMMOffset->getZExtValue())) {
672     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
673                                   SDLoc(CurDAG->getEntryNode()),
674                                   AMDGPU::ZERO, MVT::i32);
675     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
676                                        MVT::i32);
677     return true;
678   }
679
680   // Default case, no offset
681   Base = Addr;
682   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
683   return true;
684 }
685
686 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
687                                             SDValue &Offset) {
688   ConstantSDNode *C;
689   SDLoc DL(Addr);
690
691   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
692     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
693     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
694   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
695             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
696     Base = Addr.getOperand(0);
697     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
698   } else {
699     Base = Addr;
700     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
701   }
702
703   return true;
704 }
705
706 SDNode *AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
707   SDLoc DL(N);
708   SDValue LHS = N->getOperand(0);
709   SDValue RHS = N->getOperand(1);
710
711   bool IsAdd = (N->getOpcode() == ISD::ADD);
712
713   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
714   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
715
716   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
717                                        DL, MVT::i32, LHS, Sub0);
718   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
719                                        DL, MVT::i32, LHS, Sub1);
720
721   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
722                                        DL, MVT::i32, RHS, Sub0);
723   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
724                                        DL, MVT::i32, RHS, Sub1);
725
726   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
727   SDValue AddLoArgs[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
728
729
730   unsigned Opc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
731   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
732
733   SDNode *AddLo = CurDAG->getMachineNode( Opc, DL, VTList, AddLoArgs);
734   SDValue Carry(AddLo, 1);
735   SDNode *AddHi
736     = CurDAG->getMachineNode(CarryOpc, DL, MVT::i32,
737                              SDValue(Hi0, 0), SDValue(Hi1, 0), Carry);
738
739   SDValue Args[5] = {
740     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
741     SDValue(AddLo,0),
742     Sub0,
743     SDValue(AddHi,0),
744     Sub1,
745   };
746   return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, MVT::i64, Args);
747 }
748
749 // We need to handle this here because tablegen doesn't support matching
750 // instructions with multiple outputs.
751 SDNode *AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
752   SDLoc SL(N);
753   EVT VT = N->getValueType(0);
754
755   assert(VT == MVT::f32 || VT == MVT::f64);
756
757   unsigned Opc
758     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
759
760   // src0_modifiers, src0, src1_modifiers, src1, src2_modifiers, src2, clamp,
761   // omod
762   SDValue Ops[8];
763
764   SelectVOP3Mods0(N->getOperand(0), Ops[1], Ops[0], Ops[6], Ops[7]);
765   SelectVOP3Mods(N->getOperand(1), Ops[3], Ops[2]);
766   SelectVOP3Mods(N->getOperand(2), Ops[5], Ops[4]);
767   return CurDAG->SelectNodeTo(N, Opc, VT, MVT::i1, Ops);
768 }
769
770 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(const SDValue &Base, unsigned Offset,
771                                          unsigned OffsetBits) const {
772   if ((OffsetBits == 16 && !isUInt<16>(Offset)) ||
773       (OffsetBits == 8 && !isUInt<8>(Offset)))
774     return false;
775
776   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS ||
777       Subtarget->unsafeDSOffsetFoldingEnabled())
778     return true;
779
780   // On Southern Islands instruction with a negative base value and an offset
781   // don't seem to work.
782   return CurDAG->SignBitIsZero(Base);
783 }
784
785 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
786                                               SDValue &Offset) const {
787   if (CurDAG->isBaseWithConstantOffset(Addr)) {
788     SDValue N0 = Addr.getOperand(0);
789     SDValue N1 = Addr.getOperand(1);
790     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
791     if (isDSOffsetLegal(N0, C1->getSExtValue(), 16)) {
792       // (add n0, c0)
793       Base = N0;
794       Offset = N1;
795       return true;
796     }
797   } else if (Addr.getOpcode() == ISD::SUB) {
798     // sub C, x -> add (sub 0, x), C
799     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
800       int64_t ByteOffset = C->getSExtValue();
801       if (isUInt<16>(ByteOffset)) {
802         SDLoc DL(Addr);
803         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
804
805         // XXX - This is kind of hacky. Create a dummy sub node so we can check
806         // the known bits in isDSOffsetLegal. We need to emit the selected node
807         // here, so this is thrown away.
808         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
809                                       Zero, Addr.getOperand(1));
810
811         if (isDSOffsetLegal(Sub, ByteOffset, 16)) {
812           MachineSDNode *MachineSub
813             = CurDAG->getMachineNode(AMDGPU::V_SUB_I32_e32, DL, MVT::i32,
814                                      Zero, Addr.getOperand(1));
815
816           Base = SDValue(MachineSub, 0);
817           Offset = Addr.getOperand(0);
818           return true;
819         }
820       }
821     }
822   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
823     // If we have a constant address, prefer to put the constant into the
824     // offset. This can save moves to load the constant address since multiple
825     // operations can share the zero base address register, and enables merging
826     // into read2 / write2 instructions.
827
828     SDLoc DL(Addr);
829
830     if (isUInt<16>(CAddr->getZExtValue())) {
831       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
832       MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
833                                  DL, MVT::i32, Zero);
834       Base = SDValue(MovZero, 0);
835       Offset = Addr;
836       return true;
837     }
838   }
839
840   // default case
841   Base = Addr;
842   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i16);
843   return true;
844 }
845
846 // TODO: If offset is too big, put low 16-bit into offset.
847 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
848                                                    SDValue &Offset0,
849                                                    SDValue &Offset1) const {
850   SDLoc DL(Addr);
851
852   if (CurDAG->isBaseWithConstantOffset(Addr)) {
853     SDValue N0 = Addr.getOperand(0);
854     SDValue N1 = Addr.getOperand(1);
855     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
856     unsigned DWordOffset0 = C1->getZExtValue() / 4;
857     unsigned DWordOffset1 = DWordOffset0 + 1;
858     // (add n0, c0)
859     if (isDSOffsetLegal(N0, DWordOffset1, 8)) {
860       Base = N0;
861       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
862       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
863       return true;
864     }
865   } else if (Addr.getOpcode() == ISD::SUB) {
866     // sub C, x -> add (sub 0, x), C
867     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
868       unsigned DWordOffset0 = C->getZExtValue() / 4;
869       unsigned DWordOffset1 = DWordOffset0 + 1;
870
871       if (isUInt<8>(DWordOffset0)) {
872         SDLoc DL(Addr);
873         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
874
875         // XXX - This is kind of hacky. Create a dummy sub node so we can check
876         // the known bits in isDSOffsetLegal. We need to emit the selected node
877         // here, so this is thrown away.
878         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
879                                       Zero, Addr.getOperand(1));
880
881         if (isDSOffsetLegal(Sub, DWordOffset1, 8)) {
882           MachineSDNode *MachineSub
883             = CurDAG->getMachineNode(AMDGPU::V_SUB_I32_e32, DL, MVT::i32,
884                                      Zero, Addr.getOperand(1));
885
886           Base = SDValue(MachineSub, 0);
887           Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
888           Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
889           return true;
890         }
891       }
892     }
893   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
894     unsigned DWordOffset0 = CAddr->getZExtValue() / 4;
895     unsigned DWordOffset1 = DWordOffset0 + 1;
896     assert(4 * DWordOffset0 == CAddr->getZExtValue());
897
898     if (isUInt<8>(DWordOffset0) && isUInt<8>(DWordOffset1)) {
899       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
900       MachineSDNode *MovZero
901         = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
902                                  DL, MVT::i32, Zero);
903       Base = SDValue(MovZero, 0);
904       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
905       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
906       return true;
907     }
908   }
909
910   // default case
911   Base = Addr;
912   Offset0 = CurDAG->getTargetConstant(0, DL, MVT::i8);
913   Offset1 = CurDAG->getTargetConstant(1, DL, MVT::i8);
914   return true;
915 }
916
917 static bool isLegalMUBUFImmOffset(const ConstantSDNode *Imm) {
918   return isUInt<12>(Imm->getZExtValue());
919 }
920
921 void AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr,
922                                      SDValue &VAddr, SDValue &SOffset,
923                                      SDValue &Offset, SDValue &Offen,
924                                      SDValue &Idxen, SDValue &Addr64,
925                                      SDValue &GLC, SDValue &SLC,
926                                      SDValue &TFE) const {
927   SDLoc DL(Addr);
928
929   GLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
930   SLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
931   TFE = CurDAG->getTargetConstant(0, DL, MVT::i1);
932
933   Idxen = CurDAG->getTargetConstant(0, DL, MVT::i1);
934   Offen = CurDAG->getTargetConstant(0, DL, MVT::i1);
935   Addr64 = CurDAG->getTargetConstant(0, DL, MVT::i1);
936   SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
937
938   if (CurDAG->isBaseWithConstantOffset(Addr)) {
939     SDValue N0 = Addr.getOperand(0);
940     SDValue N1 = Addr.getOperand(1);
941     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
942
943     if (N0.getOpcode() == ISD::ADD) {
944       // (add (add N2, N3), C1) -> addr64
945       SDValue N2 = N0.getOperand(0);
946       SDValue N3 = N0.getOperand(1);
947       Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
948       Ptr = N2;
949       VAddr = N3;
950     } else {
951
952       // (add N0, C1) -> offset
953       VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
954       Ptr = N0;
955     }
956
957     if (isLegalMUBUFImmOffset(C1)) {
958         Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
959         return;
960     } else if (isUInt<32>(C1->getZExtValue())) {
961       // Illegal offset, store it in soffset.
962       Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
963       SOffset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
964                    CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32)),
965                         0);
966       return;
967     }
968   }
969
970   if (Addr.getOpcode() == ISD::ADD) {
971     // (add N0, N1) -> addr64
972     SDValue N0 = Addr.getOperand(0);
973     SDValue N1 = Addr.getOperand(1);
974     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
975     Ptr = N0;
976     VAddr = N1;
977     Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
978     return;
979   }
980
981   // default case -> offset
982   VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
983   Ptr = Addr;
984   Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
985 }
986
987 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
988                                            SDValue &VAddr, SDValue &SOffset,
989                                            SDValue &Offset, SDValue &GLC,
990                                            SDValue &SLC, SDValue &TFE) const {
991   SDValue Ptr, Offen, Idxen, Addr64;
992
993   // addr64 bit was removed for volcanic islands.
994   if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
995     return false;
996
997   SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
998               GLC, SLC, TFE);
999
1000   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
1001   if (C->getSExtValue()) {
1002     SDLoc DL(Addr);
1003
1004     const SITargetLowering& Lowering =
1005       *static_cast<const SITargetLowering*>(getTargetLowering());
1006
1007     SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
1008     return true;
1009   }
1010
1011   return false;
1012 }
1013
1014 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1015                                            SDValue &VAddr, SDValue &SOffset,
1016                                            SDValue &Offset,
1017                                            SDValue &SLC) const {
1018   SLC = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i1);
1019   SDValue GLC, TFE;
1020
1021   return SelectMUBUFAddr64(Addr, SRsrc, VAddr, SOffset, Offset, GLC, SLC, TFE);
1022 }
1023
1024 bool AMDGPUDAGToDAGISel::SelectMUBUFScratch(SDValue Addr, SDValue &Rsrc,
1025                                             SDValue &VAddr, SDValue &SOffset,
1026                                             SDValue &ImmOffset) const {
1027
1028   SDLoc DL(Addr);
1029   MachineFunction &MF = CurDAG->getMachineFunction();
1030   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1031
1032   Rsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1033   SOffset = CurDAG->getRegister(Info->getScratchWaveOffsetReg(), MVT::i32);
1034
1035   // (add n0, c1)
1036   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1037     SDValue N0 = Addr.getOperand(0);
1038     SDValue N1 = Addr.getOperand(1);
1039     // Offsets in vaddr must be positive.
1040     if (CurDAG->SignBitIsZero(N0)) {
1041       ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1042       if (isLegalMUBUFImmOffset(C1)) {
1043         VAddr = N0;
1044         ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1045         return true;
1046       }
1047     }
1048   }
1049
1050   // (node)
1051   VAddr = Addr;
1052   ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1053   return true;
1054 }
1055
1056 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1057                                            SDValue &SOffset, SDValue &Offset,
1058                                            SDValue &GLC, SDValue &SLC,
1059                                            SDValue &TFE) const {
1060   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1061   const SIInstrInfo *TII =
1062     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1063
1064   SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1065               GLC, SLC, TFE);
1066
1067   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1068       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1069       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1070     uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1071                     APInt::getAllOnesValue(32).getZExtValue(); // Size
1072     SDLoc DL(Addr);
1073
1074     const SITargetLowering& Lowering =
1075       *static_cast<const SITargetLowering*>(getTargetLowering());
1076
1077     SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1078     return true;
1079   }
1080   return false;
1081 }
1082
1083 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1084                                            SDValue &Soffset, SDValue &Offset,
1085                                            SDValue &GLC) const {
1086   SDValue SLC, TFE;
1087
1088   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE);
1089 }
1090
1091 ///
1092 /// \param EncodedOffset This is the immediate value that will be encoded
1093 ///        directly into the instruction.  On SI/CI the \p EncodedOffset
1094 ///        will be in units of dwords and on VI+ it will be units of bytes.
1095 static bool isLegalSMRDImmOffset(const AMDGPUSubtarget *ST,
1096                                  int64_t EncodedOffset) {
1097   return ST->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ?
1098      isUInt<8>(EncodedOffset) : isUInt<20>(EncodedOffset);
1099 }
1100
1101 bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDValue ByteOffsetNode,
1102                                           SDValue &Offset, bool &Imm) const {
1103
1104   // FIXME: Handle non-constant offsets.
1105   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ByteOffsetNode);
1106   if (!C)
1107     return false;
1108
1109   SDLoc SL(ByteOffsetNode);
1110   AMDGPUSubtarget::Generation Gen = Subtarget->getGeneration();
1111   int64_t ByteOffset = C->getSExtValue();
1112   int64_t EncodedOffset = Gen < AMDGPUSubtarget::VOLCANIC_ISLANDS ?
1113       ByteOffset >> 2 : ByteOffset;
1114
1115   if (isLegalSMRDImmOffset(Subtarget, EncodedOffset)) {
1116     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1117     Imm = true;
1118     return true;
1119   }
1120
1121   if (!isUInt<32>(EncodedOffset) || !isUInt<32>(ByteOffset))
1122     return false;
1123
1124   if (Gen == AMDGPUSubtarget::SEA_ISLANDS && isUInt<32>(EncodedOffset)) {
1125     // 32-bit Immediates are supported on Sea Islands.
1126     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1127   } else {
1128     SDValue C32Bit = CurDAG->getTargetConstant(ByteOffset, SL, MVT::i32);
1129     Offset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32,
1130                                             C32Bit), 0);
1131   }
1132   Imm = false;
1133   return true;
1134 }
1135
1136 bool AMDGPUDAGToDAGISel::SelectSMRD(SDValue Addr, SDValue &SBase,
1137                                      SDValue &Offset, bool &Imm) const {
1138
1139   SDLoc SL(Addr);
1140   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1141     SDValue N0 = Addr.getOperand(0);
1142     SDValue N1 = Addr.getOperand(1);
1143
1144     if (SelectSMRDOffset(N1, Offset, Imm)) {
1145       SBase = N0;
1146       return true;
1147     }
1148   }
1149   SBase = Addr;
1150   Offset = CurDAG->getTargetConstant(0, SL, MVT::i32);
1151   Imm = true;
1152   return true;
1153 }
1154
1155 bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
1156                                        SDValue &Offset) const {
1157   bool Imm;
1158   return SelectSMRD(Addr, SBase, Offset, Imm) && Imm;
1159 }
1160
1161 bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
1162                                          SDValue &Offset) const {
1163
1164   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1165     return false;
1166
1167   bool Imm;
1168   if (!SelectSMRD(Addr, SBase, Offset, Imm))
1169     return false;
1170
1171   return !Imm && isa<ConstantSDNode>(Offset);
1172 }
1173
1174 bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDValue Addr, SDValue &SBase,
1175                                         SDValue &Offset) const {
1176   bool Imm;
1177   return SelectSMRD(Addr, SBase, Offset, Imm) && !Imm &&
1178          !isa<ConstantSDNode>(Offset);
1179 }
1180
1181 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue Addr,
1182                                              SDValue &Offset) const {
1183   bool Imm;
1184   return SelectSMRDOffset(Addr, Offset, Imm) && Imm;
1185 }
1186
1187 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue Addr,
1188                                                SDValue &Offset) const {
1189   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1190     return false;
1191
1192   bool Imm;
1193   if (!SelectSMRDOffset(Addr, Offset, Imm))
1194     return false;
1195
1196   return !Imm && isa<ConstantSDNode>(Offset);
1197 }
1198
1199 bool AMDGPUDAGToDAGISel::SelectSMRDBufferSgpr(SDValue Addr,
1200                                               SDValue &Offset) const {
1201   bool Imm;
1202   return SelectSMRDOffset(Addr, Offset, Imm) && !Imm &&
1203          !isa<ConstantSDNode>(Offset);
1204 }
1205
1206 // FIXME: This is incorrect and only enough to be able to compile.
1207 SDNode *AMDGPUDAGToDAGISel::SelectAddrSpaceCast(SDNode *N) {
1208   AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(N);
1209   SDLoc DL(N);
1210
1211   assert(Subtarget->hasFlatAddressSpace() &&
1212          "addrspacecast only supported with flat address space!");
1213
1214   assert((ASC->getSrcAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
1215           ASC->getDestAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) &&
1216          "Cannot cast address space to / from constant address!");
1217
1218   assert((ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS ||
1219           ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) &&
1220          "Can only cast to / from flat address space!");
1221
1222   // The flat instructions read the address as the index of the VGPR holding the
1223   // address, so casting should just be reinterpreting the base VGPR, so just
1224   // insert trunc / bitcast / zext.
1225
1226   SDValue Src = ASC->getOperand(0);
1227   EVT DestVT = ASC->getValueType(0);
1228   EVT SrcVT = Src.getValueType();
1229
1230   unsigned SrcSize = SrcVT.getSizeInBits();
1231   unsigned DestSize = DestVT.getSizeInBits();
1232
1233   if (SrcSize > DestSize) {
1234     assert(SrcSize == 64 && DestSize == 32);
1235     return CurDAG->getMachineNode(
1236       TargetOpcode::EXTRACT_SUBREG,
1237       DL,
1238       DestVT,
1239       Src,
1240       CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32));
1241   }
1242
1243   if (DestSize > SrcSize) {
1244     assert(SrcSize == 32 && DestSize == 64);
1245
1246     // FIXME: This is probably wrong, we should never be defining
1247     // a register class with both VGPRs and SGPRs
1248     SDValue RC = CurDAG->getTargetConstant(AMDGPU::VS_64RegClassID, DL,
1249                                            MVT::i32);
1250
1251     const SDValue Ops[] = {
1252       RC,
1253       Src,
1254       CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
1255       SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
1256                                      CurDAG->getConstant(0, DL, MVT::i32)), 0),
1257       CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
1258     };
1259
1260     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1261                                   DL, N->getValueType(0), Ops);
1262   }
1263
1264   assert(SrcSize == 64 && DestSize == 64);
1265   return CurDAG->getNode(ISD::BITCAST, DL, DestVT, Src).getNode();
1266 }
1267
1268 SDNode *AMDGPUDAGToDAGISel::getS_BFE(unsigned Opcode, SDLoc DL, SDValue Val,
1269                                      uint32_t Offset, uint32_t Width) {
1270   // Transformation function, pack the offset and width of a BFE into
1271   // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
1272   // source, bits [5:0] contain the offset and bits [22:16] the width.
1273   uint32_t PackedVal = Offset | (Width << 16);
1274   SDValue PackedConst = CurDAG->getTargetConstant(PackedVal, DL, MVT::i32);
1275
1276   return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, PackedConst);
1277 }
1278
1279 SDNode *AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
1280   // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
1281   // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
1282   // Predicate: 0 < b <= c < 32
1283
1284   const SDValue &Shl = N->getOperand(0);
1285   ConstantSDNode *B = dyn_cast<ConstantSDNode>(Shl->getOperand(1));
1286   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1287
1288   if (B && C) {
1289     uint32_t BVal = B->getZExtValue();
1290     uint32_t CVal = C->getZExtValue();
1291
1292     if (0 < BVal && BVal <= CVal && CVal < 32) {
1293       bool Signed = N->getOpcode() == ISD::SRA;
1294       unsigned Opcode = Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
1295
1296       return getS_BFE(Opcode, SDLoc(N), Shl.getOperand(0),
1297                       CVal - BVal, 32 - CVal);
1298     }
1299   }
1300   return SelectCode(N);
1301 }
1302
1303 SDNode *AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
1304   switch (N->getOpcode()) {
1305   case ISD::AND:
1306     if (N->getOperand(0).getOpcode() == ISD::SRL) {
1307       // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
1308       // Predicate: isMask(mask)
1309       const SDValue &Srl = N->getOperand(0);
1310       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Srl.getOperand(1));
1311       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
1312
1313       if (Shift && Mask) {
1314         uint32_t ShiftVal = Shift->getZExtValue();
1315         uint32_t MaskVal = Mask->getZExtValue();
1316
1317         if (isMask_32(MaskVal)) {
1318           uint32_t WidthVal = countPopulation(MaskVal);
1319
1320           return getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N), Srl.getOperand(0),
1321                           ShiftVal, WidthVal);
1322         }
1323       }
1324     }
1325     break;
1326   case ISD::SRL:
1327     if (N->getOperand(0).getOpcode() == ISD::AND) {
1328       // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
1329       // Predicate: isMask(mask >> b)
1330       const SDValue &And = N->getOperand(0);
1331       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N->getOperand(1));
1332       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(And->getOperand(1));
1333
1334       if (Shift && Mask) {
1335         uint32_t ShiftVal = Shift->getZExtValue();
1336         uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
1337
1338         if (isMask_32(MaskVal)) {
1339           uint32_t WidthVal = countPopulation(MaskVal);
1340
1341           return getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N), And.getOperand(0),
1342                           ShiftVal, WidthVal);
1343         }
1344       }
1345     } else if (N->getOperand(0).getOpcode() == ISD::SHL)
1346       return SelectS_BFEFromShifts(N);
1347     break;
1348   case ISD::SRA:
1349     if (N->getOperand(0).getOpcode() == ISD::SHL)
1350       return SelectS_BFEFromShifts(N);
1351     break;
1352   }
1353
1354   return SelectCode(N);
1355 }
1356
1357 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
1358                                         SDValue &SrcMods) const {
1359
1360   unsigned Mods = 0;
1361
1362   Src = In;
1363
1364   if (Src.getOpcode() == ISD::FNEG) {
1365     Mods |= SISrcMods::NEG;
1366     Src = Src.getOperand(0);
1367   }
1368
1369   if (Src.getOpcode() == ISD::FABS) {
1370     Mods |= SISrcMods::ABS;
1371     Src = Src.getOperand(0);
1372   }
1373
1374   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
1375
1376   return true;
1377 }
1378
1379 bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src,
1380                                          SDValue &SrcMods) const {
1381   bool Res = SelectVOP3Mods(In, Src, SrcMods);
1382   return Res && cast<ConstantSDNode>(SrcMods)->isNullValue();
1383 }
1384
1385 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
1386                                          SDValue &SrcMods, SDValue &Clamp,
1387                                          SDValue &Omod) const {
1388   SDLoc DL(In);
1389   // FIXME: Handle Clamp and Omod
1390   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1391   Omod = CurDAG->getTargetConstant(0, DL, MVT::i32);
1392
1393   return SelectVOP3Mods(In, Src, SrcMods);
1394 }
1395
1396 bool AMDGPUDAGToDAGISel::SelectVOP3NoMods0(SDValue In, SDValue &Src,
1397                                            SDValue &SrcMods, SDValue &Clamp,
1398                                            SDValue &Omod) const {
1399   bool Res = SelectVOP3Mods0(In, Src, SrcMods, Clamp, Omod);
1400
1401   return Res && cast<ConstantSDNode>(SrcMods)->isNullValue() &&
1402                 cast<ConstantSDNode>(Clamp)->isNullValue() &&
1403                 cast<ConstantSDNode>(Omod)->isNullValue();
1404 }
1405
1406 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp(SDValue In, SDValue &Src,
1407                                               SDValue &SrcMods,
1408                                               SDValue &Omod) const {
1409   // FIXME: Handle Omod
1410   Omod = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
1411
1412   return SelectVOP3Mods(In, Src, SrcMods);
1413 }
1414
1415 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src,
1416                                                    SDValue &SrcMods,
1417                                                    SDValue &Clamp,
1418                                                    SDValue &Omod) const {
1419   Clamp = Omod = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
1420   return SelectVOP3Mods(In, Src, SrcMods);
1421 }
1422
1423 void AMDGPUDAGToDAGISel::PreprocessISelDAG() {
1424   bool Modified = false;
1425
1426   // XXX - Other targets seem to be able to do this without a worklist.
1427   SmallVector<LoadSDNode *, 8> LoadsToReplace;
1428   SmallVector<StoreSDNode *, 8> StoresToReplace;
1429
1430   for (SDNode &Node : CurDAG->allnodes()) {
1431     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(&Node)) {
1432       EVT VT = LD->getValueType(0);
1433       if (VT != MVT::i64 || LD->getExtensionType() != ISD::NON_EXTLOAD)
1434         continue;
1435
1436       // To simplify the TableGen patters, we replace all i64 loads with v2i32
1437       // loads.  Alternatively, we could promote i64 loads to v2i32 during DAG
1438       // legalization, however, so places (ExpandUnalignedLoad) in the DAG
1439       // legalizer assume that if i64 is legal, so doing this promotion early
1440       // can cause problems.
1441       LoadsToReplace.push_back(LD);
1442     } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(&Node)) {
1443       // Handle i64 stores here for the same reason mentioned above for loads.
1444       SDValue Value = ST->getValue();
1445       if (Value.getValueType() != MVT::i64 || ST->isTruncatingStore())
1446         continue;
1447       StoresToReplace.push_back(ST);
1448     }
1449   }
1450
1451   for (LoadSDNode *LD : LoadsToReplace) {
1452     SDLoc SL(LD);
1453
1454     SDValue NewLoad = CurDAG->getLoad(MVT::v2i32, SL, LD->getChain(),
1455                                       LD->getBasePtr(), LD->getMemOperand());
1456     SDValue BitCast = CurDAG->getNode(ISD::BITCAST, SL,
1457                                       MVT::i64, NewLoad);
1458     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLoad.getValue(1));
1459     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LD, 0), BitCast);
1460     Modified = true;
1461   }
1462
1463   for (StoreSDNode *ST : StoresToReplace) {
1464     SDValue NewValue = CurDAG->getNode(ISD::BITCAST, SDLoc(ST),
1465                                        MVT::v2i32, ST->getValue());
1466     const SDValue StoreOps[] = {
1467       ST->getChain(),
1468       NewValue,
1469       ST->getBasePtr(),
1470       ST->getOffset()
1471     };
1472
1473     CurDAG->UpdateNodeOperands(ST, StoreOps);
1474     Modified = true;
1475   }
1476
1477   // XXX - Is this necessary?
1478   if (Modified)
1479     CurDAG->RemoveDeadNodes();
1480 }
1481
1482 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
1483   const AMDGPUTargetLowering& Lowering =
1484     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
1485   bool IsModified = false;
1486   do {
1487     IsModified = false;
1488     // Go over all selected nodes and try to fold them a bit more
1489     for (SDNode &Node : CurDAG->allnodes()) {
1490       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
1491       if (!MachineNode)
1492         continue;
1493
1494       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
1495       if (ResNode != &Node) {
1496         ReplaceUses(&Node, ResNode);
1497         IsModified = true;
1498       }
1499     }
1500     CurDAG->RemoveDeadNodes();
1501   } while (IsModified);
1502 }