1 //===-- AMDGPUISelDAGToDAG.cpp - A dag to dag inst selector for AMDGPU ----===//
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 
15 #include "AMDGPU.h"
16 #include "AMDGPUArgumentUsageInfo.h"
17 #include "AMDGPUISelLowering.h" // For AMDGPUISD
18 #include "AMDGPUInstrInfo.h"
19 #include "AMDGPURegisterInfo.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
22 #include "SIDefines.h"
23 #include "SIISelLowering.h"
24 #include "SIInstrInfo.h"
25 #include "SIMachineFunctionInfo.h"
26 #include "SIRegisterInfo.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/SelectionDAGISel.h"
38 #include "llvm/CodeGen/SelectionDAGNodes.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/MC/MCInstrDesc.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CodeGen.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include <cassert>
48 #include <cstdint>
49 #include <new>
50 #include <vector>
51 
52 using namespace llvm;
53 
54 namespace llvm {
55 
56 class R600InstrInfo;
57 
58 } // end namespace llvm
59 
60 //===----------------------------------------------------------------------===//
61 // Instruction Selector Implementation
62 //===----------------------------------------------------------------------===//
63 
64 namespace {
65 
66 /// AMDGPU specific code to select AMDGPU machine instructions for
67 /// SelectionDAG operations.
68 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
69   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
70   // make the right decision when generating code for different targets.
71   const AMDGPUSubtarget *Subtarget;
72   AMDGPUAS AMDGPUASI;
73   bool EnableLateStructurizeCFG;
74 
75 public:
76   explicit AMDGPUDAGToDAGISel(TargetMachine *TM = nullptr,
77                               CodeGenOpt::Level OptLevel = CodeGenOpt::Default)
78     : SelectionDAGISel(*TM, OptLevel) {
79     AMDGPUASI = AMDGPU::getAMDGPUAS(*TM);
80     EnableLateStructurizeCFG = AMDGPUTargetMachine::EnableLateStructurizeCFG;
81   }
82   ~AMDGPUDAGToDAGISel() override = default;
83 
84   void getAnalysisUsage(AnalysisUsage &AU) const override {
85     AU.addRequired<AMDGPUArgumentUsageInfo>();
86     SelectionDAGISel::getAnalysisUsage(AU);
87   }
88 
89   bool runOnMachineFunction(MachineFunction &MF) override;
90   void Select(SDNode *N) override;
91   StringRef getPassName() const override;
92   void PostprocessISelDAG() override;
93 
94 protected:
95   void SelectBuildVector(SDNode *N, unsigned RegClassID);
96 
97 private:
98   std::pair<SDValue, SDValue> foldFrameIndex(SDValue N) const;
99   bool isNoNanSrc(SDValue N) const;
100   bool isInlineImmediate(const SDNode *N) const;
101   bool FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg, SDValue &Abs,
102                    const R600InstrInfo *TII);
103   bool FoldOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
104   bool FoldDotOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
105 
106   bool isConstantLoad(const MemSDNode *N, int cbID) const;
107   bool isUniformBr(const SDNode *N) const;
108 
109   SDNode *glueCopyToM0(SDNode *N) const;
110 
111   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
112   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
113   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
114                                        SDValue& Offset);
115   virtual bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
116   virtual bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
117   bool isDSOffsetLegal(const SDValue &Base, unsigned Offset,
118                        unsigned OffsetBits) const;
119   bool SelectDS1Addr1Offset(SDValue Ptr, SDValue &Base, SDValue &Offset) const;
120   bool SelectDS64Bit4ByteAligned(SDValue Ptr, SDValue &Base, SDValue &Offset0,
121                                  SDValue &Offset1) const;
122   bool SelectMUBUF(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
123                    SDValue &SOffset, SDValue &Offset, SDValue &Offen,
124                    SDValue &Idxen, SDValue &Addr64, SDValue &GLC, SDValue &SLC,
125                    SDValue &TFE) const;
126   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
127                          SDValue &SOffset, SDValue &Offset, SDValue &GLC,
128                          SDValue &SLC, SDValue &TFE) const;
129   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
130                          SDValue &VAddr, SDValue &SOffset, SDValue &Offset,
131                          SDValue &SLC) const;
132   bool SelectMUBUFScratchOffen(SDNode *Parent,
133                                SDValue Addr, SDValue &RSrc, SDValue &VAddr,
134                                SDValue &SOffset, SDValue &ImmOffset) const;
135   bool SelectMUBUFScratchOffset(SDNode *Parent,
136                                 SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
137                                 SDValue &Offset) const;
138 
139   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &SOffset,
140                          SDValue &Offset, SDValue &GLC, SDValue &SLC,
141                          SDValue &TFE) const;
142   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
143                          SDValue &Offset, SDValue &SLC) const;
144   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
145                          SDValue &Offset) const;
146   bool SelectMUBUFConstant(SDValue Constant,
147                            SDValue &SOffset,
148                            SDValue &ImmOffset) const;
149   bool SelectMUBUFIntrinsicOffset(SDValue Offset, SDValue &SOffset,
150                                   SDValue &ImmOffset) const;
151   bool SelectMUBUFIntrinsicVOffset(SDValue Offset, SDValue &SOffset,
152                                    SDValue &ImmOffset, SDValue &VOffset) const;
153 
154   bool SelectFlatAtomic(SDValue Addr, SDValue &VAddr,
155                         SDValue &Offset, SDValue &SLC) const;
156   bool SelectFlatAtomicSigned(SDValue Addr, SDValue &VAddr,
157                               SDValue &Offset, SDValue &SLC) const;
158 
159   template <bool IsSigned>
160   bool SelectFlatOffset(SDValue Addr, SDValue &VAddr,
161                         SDValue &Offset, SDValue &SLC) const;
162 
163   bool SelectSMRDOffset(SDValue ByteOffsetNode, SDValue &Offset,
164                         bool &Imm) const;
165   bool SelectSMRD(SDValue Addr, SDValue &SBase, SDValue &Offset,
166                   bool &Imm) const;
167   bool SelectSMRDImm(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
168   bool SelectSMRDImm32(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
169   bool SelectSMRDSgpr(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
170   bool SelectSMRDBufferImm(SDValue Addr, SDValue &Offset) const;
171   bool SelectSMRDBufferImm32(SDValue Addr, SDValue &Offset) const;
172   bool SelectSMRDBufferSgpr(SDValue Addr, SDValue &Offset) const;
173   bool SelectMOVRELOffset(SDValue Index, SDValue &Base, SDValue &Offset) const;
174 
175   bool SelectVOP3Mods_NNaN(SDValue In, SDValue &Src, SDValue &SrcMods) const;
176   bool SelectVOP3ModsImpl(SDValue In, SDValue &Src, unsigned &SrcMods) const;
177   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
178   bool SelectVOP3NoMods(SDValue In, SDValue &Src) const;
179   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
180                        SDValue &Clamp, SDValue &Omod) const;
181   bool SelectVOP3NoMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
182                          SDValue &Clamp, SDValue &Omod) const;
183 
184   bool SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src, SDValue &SrcMods,
185                                  SDValue &Clamp,
186                                  SDValue &Omod) const;
187 
188   bool SelectVOP3OMods(SDValue In, SDValue &Src,
189                        SDValue &Clamp, SDValue &Omod) const;
190 
191   bool SelectVOP3PMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
192   bool SelectVOP3PMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
193                         SDValue &Clamp) const;
194 
195   bool SelectVOP3OpSel(SDValue In, SDValue &Src, SDValue &SrcMods) const;
196   bool SelectVOP3OpSel0(SDValue In, SDValue &Src, SDValue &SrcMods,
197                         SDValue &Clamp) const;
198 
199   bool SelectVOP3OpSelMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
200   bool SelectVOP3OpSelMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
201                             SDValue &Clamp) const;
202   bool SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src, unsigned &Mods) const;
203   bool SelectVOP3PMadMixMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
204 
205   void SelectADD_SUB_I64(SDNode *N);
206   void SelectUADDO_USUBO(SDNode *N);
207   void SelectDIV_SCALE(SDNode *N);
208   void SelectFMA_W_CHAIN(SDNode *N);
209   void SelectFMUL_W_CHAIN(SDNode *N);
210 
211   SDNode *getS_BFE(unsigned Opcode, const SDLoc &DL, SDValue Val,
212                    uint32_t Offset, uint32_t Width);
213   void SelectS_BFEFromShifts(SDNode *N);
214   void SelectS_BFE(SDNode *N);
215   bool isCBranchSCC(const SDNode *N) const;
216   void SelectBRCOND(SDNode *N);
217   void SelectFMAD(SDNode *N);
218   void SelectATOMIC_CMP_SWAP(SDNode *N);
219 
220 protected:
221   // Include the pieces autogenerated from the target description.
222 #include "AMDGPUGenDAGISel.inc"
223 };
224 
225 class R600DAGToDAGISel : public AMDGPUDAGToDAGISel {
226 public:
227   explicit R600DAGToDAGISel(TargetMachine *TM, CodeGenOpt::Level OptLevel) :
228       AMDGPUDAGToDAGISel(TM, OptLevel) {}
229 
230   void Select(SDNode *N) override;
231 
232   bool SelectADDRIndirect(SDValue Addr, SDValue &Base,
233                           SDValue &Offset) override;
234   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
235                           SDValue &Offset) override;
236 };
237 
238 }  // end anonymous namespace
239 
240 INITIALIZE_PASS_BEGIN(AMDGPUDAGToDAGISel, "isel",
241                       "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
242 INITIALIZE_PASS_DEPENDENCY(AMDGPUArgumentUsageInfo)
243 INITIALIZE_PASS_END(AMDGPUDAGToDAGISel, "isel",
244                     "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
245 
246 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
247 // DAG, ready for instruction scheduling.
248 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine *TM,
249                                         CodeGenOpt::Level OptLevel) {
250   return new AMDGPUDAGToDAGISel(TM, OptLevel);
251 }
252 
253 /// \brief This pass converts a legalized DAG into a R600-specific
254 // DAG, ready for instruction scheduling.
255 FunctionPass *llvm::createR600ISelDag(TargetMachine *TM,
256                                       CodeGenOpt::Level OptLevel) {
257   return new R600DAGToDAGISel(TM, OptLevel);
258 }
259 
260 bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
261   Subtarget = &MF.getSubtarget<AMDGPUSubtarget>();
262   return SelectionDAGISel::runOnMachineFunction(MF);
263 }
264 
265 bool AMDGPUDAGToDAGISel::isNoNanSrc(SDValue N) const {
266   if (TM.Options.NoNaNsFPMath)
267     return true;
268 
269   // TODO: Move into isKnownNeverNaN
270   if (N->getFlags().isDefined())
271     return N->getFlags().hasNoNaNs();
272 
273   return CurDAG->isKnownNeverNaN(N);
274 }
275 
276 bool AMDGPUDAGToDAGISel::isInlineImmediate(const SDNode *N) const {
277   const SIInstrInfo *TII
278     = static_cast<const SISubtarget *>(Subtarget)->getInstrInfo();
279 
280   if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N))
281     return TII->isInlineConstant(C->getAPIntValue());
282 
283   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N))
284     return TII->isInlineConstant(C->getValueAPF().bitcastToAPInt());
285 
286   return false;
287 }
288 
289 /// \brief Determine the register class for \p OpNo
290 /// \returns The register class of the virtual register that will be used for
291 /// the given operand number \OpNo or NULL if the register class cannot be
292 /// determined.
293 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
294                                                           unsigned OpNo) const {
295   if (!N->isMachineOpcode()) {
296     if (N->getOpcode() == ISD::CopyToReg) {
297       unsigned Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
298       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
299         MachineRegisterInfo &MRI = CurDAG->getMachineFunction().getRegInfo();
300         return MRI.getRegClass(Reg);
301       }
302 
303       const SIRegisterInfo *TRI
304         = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
305       return TRI->getPhysRegClass(Reg);
306     }
307 
308     return nullptr;
309   }
310 
311   switch (N->getMachineOpcode()) {
312   default: {
313     const MCInstrDesc &Desc =
314         Subtarget->getInstrInfo()->get(N->getMachineOpcode());
315     unsigned OpIdx = Desc.getNumDefs() + OpNo;
316     if (OpIdx >= Desc.getNumOperands())
317       return nullptr;
318     int RegClass = Desc.OpInfo[OpIdx].RegClass;
319     if (RegClass == -1)
320       return nullptr;
321 
322     return Subtarget->getRegisterInfo()->getRegClass(RegClass);
323   }
324   case AMDGPU::REG_SEQUENCE: {
325     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
326     const TargetRegisterClass *SuperRC =
327         Subtarget->getRegisterInfo()->getRegClass(RCID);
328 
329     SDValue SubRegOp = N->getOperand(OpNo + 1);
330     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
331     return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
332                                                               SubRegIdx);
333   }
334   }
335 }
336 
337 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N) const {
338   if (cast<MemSDNode>(N)->getAddressSpace() != AMDGPUASI.LOCAL_ADDRESS)
339     return N;
340 
341   const SITargetLowering& Lowering =
342       *static_cast<const SITargetLowering*>(getTargetLowering());
343 
344   // Write max value to m0 before each load operation
345 
346   SDValue M0 = Lowering.copyToM0(*CurDAG, CurDAG->getEntryNode(), SDLoc(N),
347                                  CurDAG->getTargetConstant(-1, SDLoc(N), MVT::i32));
348 
349   SDValue Glue = M0.getValue(1);
350 
351   SmallVector <SDValue, 8> Ops;
352   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
353      Ops.push_back(N->getOperand(i));
354   }
355   Ops.push_back(Glue);
356   CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), Ops);
357 
358   return N;
359 }
360 
361 static unsigned selectSGPRVectorRegClassID(unsigned NumVectorElts) {
362   switch (NumVectorElts) {
363   case 1:
364     return AMDGPU::SReg_32_XM0RegClassID;
365   case 2:
366     return AMDGPU::SReg_64RegClassID;
367   case 4:
368     return AMDGPU::SReg_128RegClassID;
369   case 8:
370     return AMDGPU::SReg_256RegClassID;
371   case 16:
372     return AMDGPU::SReg_512RegClassID;
373   }
374 
375   llvm_unreachable("invalid vector size");
376 }
377 
378 static bool getConstantValue(SDValue N, uint32_t &Out) {
379   if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N)) {
380     Out = C->getAPIntValue().getZExtValue();
381     return true;
382   }
383 
384   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N)) {
385     Out = C->getValueAPF().bitcastToAPInt().getZExtValue();
386     return true;
387   }
388 
389   return false;
390 }
391 
392 void AMDGPUDAGToDAGISel::SelectBuildVector(SDNode *N, unsigned RegClassID) {
393   EVT VT = N->getValueType(0);
394   unsigned NumVectorElts = VT.getVectorNumElements();
395   EVT EltVT = VT.getVectorElementType();
396   const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
397   SDLoc DL(N);
398   SDValue RegClass = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
399 
400   if (NumVectorElts == 1) {
401     CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT, N->getOperand(0),
402                          RegClass);
403     return;
404   }
405 
406   assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
407                                   "supported yet");
408   // 16 = Max Num Vector Elements
409   // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
410   // 1 = Vector Register Class
411   SmallVector<SDValue, 16 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
412 
413   RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
414   bool IsRegSeq = true;
415   unsigned NOps = N->getNumOperands();
416   for (unsigned i = 0; i < NOps; i++) {
417     // XXX: Why is this here?
418     if (isa<RegisterSDNode>(N->getOperand(i))) {
419       IsRegSeq = false;
420       break;
421     }
422     RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
423     RegSeqArgs[1 + (2 * i) + 1] =
424             CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), DL,
425                                       MVT::i32);
426   }
427   if (NOps != NumVectorElts) {
428     // Fill in the missing undef elements if this was a scalar_to_vector.
429     assert(N->getOpcode() == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
430     MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
431                                                    DL, EltVT);
432     for (unsigned i = NOps; i < NumVectorElts; ++i) {
433       RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
434       RegSeqArgs[1 + (2 * i) + 1] =
435         CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), DL, MVT::i32);
436     }
437   }
438 
439   if (!IsRegSeq)
440     SelectCode(N);
441   CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(), RegSeqArgs);
442 }
443 
444 void AMDGPUDAGToDAGISel::Select(SDNode *N) {
445   unsigned int Opc = N->getOpcode();
446   if (N->isMachineOpcode()) {
447     N->setNodeId(-1);
448     return;   // Already selected.
449   }
450 
451   if (isa<AtomicSDNode>(N) ||
452       (Opc == AMDGPUISD::ATOMIC_INC || Opc == AMDGPUISD::ATOMIC_DEC))
453     N = glueCopyToM0(N);
454 
455   switch (Opc) {
456   default: break;
457   // We are selecting i64 ADD here instead of custom lower it during
458   // DAG legalization, so we can fold some i64 ADDs used for address
459   // calculation into the LOAD and STORE instructions.
460   case ISD::ADD:
461   case ISD::ADDC:
462   case ISD::ADDE:
463   case ISD::SUB:
464   case ISD::SUBC:
465   case ISD::SUBE: {
466     if (N->getValueType(0) != MVT::i64)
467       break;
468 
469     SelectADD_SUB_I64(N);
470     return;
471   }
472   case ISD::UADDO:
473   case ISD::USUBO: {
474     SelectUADDO_USUBO(N);
475     return;
476   }
477   case AMDGPUISD::FMUL_W_CHAIN: {
478     SelectFMUL_W_CHAIN(N);
479     return;
480   }
481   case AMDGPUISD::FMA_W_CHAIN: {
482     SelectFMA_W_CHAIN(N);
483     return;
484   }
485 
486   case ISD::SCALAR_TO_VECTOR:
487   case ISD::BUILD_VECTOR: {
488     EVT VT = N->getValueType(0);
489     unsigned NumVectorElts = VT.getVectorNumElements();
490 
491     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
492       if (Opc == ISD::BUILD_VECTOR) {
493         uint32_t LHSVal, RHSVal;
494         if (getConstantValue(N->getOperand(0), LHSVal) &&
495             getConstantValue(N->getOperand(1), RHSVal)) {
496           uint32_t K = LHSVal | (RHSVal << 16);
497           CurDAG->SelectNodeTo(N, AMDGPU::S_MOV_B32, VT,
498                                CurDAG->getTargetConstant(K, SDLoc(N), MVT::i32));
499           return;
500         }
501       }
502 
503       break;
504     }
505 
506     assert(VT.getVectorElementType().bitsEq(MVT::i32));
507     unsigned RegClassID = selectSGPRVectorRegClassID(NumVectorElts);
508     SelectBuildVector(N, RegClassID);
509     return;
510   }
511   case ISD::BUILD_PAIR: {
512     SDValue RC, SubReg0, SubReg1;
513     SDLoc DL(N);
514     if (N->getValueType(0) == MVT::i128) {
515       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32);
516       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32);
517       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32);
518     } else if (N->getValueType(0) == MVT::i64) {
519       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32);
520       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
521       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
522     } else {
523       llvm_unreachable("Unhandled value type for BUILD_PAIR");
524     }
525     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
526                             N->getOperand(1), SubReg1 };
527     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
528                                           N->getValueType(0), Ops));
529     return;
530   }
531 
532   case ISD::Constant:
533   case ISD::ConstantFP: {
534     if (N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
535       break;
536 
537     uint64_t Imm;
538     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
539       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
540     else {
541       ConstantSDNode *C = cast<ConstantSDNode>(N);
542       Imm = C->getZExtValue();
543     }
544 
545     SDLoc DL(N);
546     SDNode *Lo = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
547                                 CurDAG->getConstant(Imm & 0xFFFFFFFF, DL,
548                                                     MVT::i32));
549     SDNode *Hi = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
550                                 CurDAG->getConstant(Imm >> 32, DL, MVT::i32));
551     const SDValue Ops[] = {
552       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
553       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
554       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
555     };
556 
557     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
558                                           N->getValueType(0), Ops));
559     return;
560   }
561   case ISD::LOAD:
562   case ISD::STORE: {
563     N = glueCopyToM0(N);
564     break;
565   }
566 
567   case AMDGPUISD::BFE_I32:
568   case AMDGPUISD::BFE_U32: {
569     // There is a scalar version available, but unlike the vector version which
570     // has a separate operand for the offset and width, the scalar version packs
571     // the width and offset into a single operand. Try to move to the scalar
572     // version if the offsets are constant, so that we can try to keep extended
573     // loads of kernel arguments in SGPRs.
574 
575     // TODO: Technically we could try to pattern match scalar bitshifts of
576     // dynamic values, but it's probably not useful.
577     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
578     if (!Offset)
579       break;
580 
581     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
582     if (!Width)
583       break;
584 
585     bool Signed = Opc == AMDGPUISD::BFE_I32;
586 
587     uint32_t OffsetVal = Offset->getZExtValue();
588     uint32_t WidthVal = Width->getZExtValue();
589 
590     ReplaceNode(N, getS_BFE(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32,
591                             SDLoc(N), N->getOperand(0), OffsetVal, WidthVal));
592     return;
593   }
594   case AMDGPUISD::DIV_SCALE: {
595     SelectDIV_SCALE(N);
596     return;
597   }
598   case ISD::CopyToReg: {
599     const SITargetLowering& Lowering =
600       *static_cast<const SITargetLowering*>(getTargetLowering());
601     N = Lowering.legalizeTargetIndependentNode(N, *CurDAG);
602     break;
603   }
604   case ISD::AND:
605   case ISD::SRL:
606   case ISD::SRA:
607   case ISD::SIGN_EXTEND_INREG:
608     if (N->getValueType(0) != MVT::i32)
609       break;
610 
611     SelectS_BFE(N);
612     return;
613   case ISD::BRCOND:
614     SelectBRCOND(N);
615     return;
616   case ISD::FMAD:
617     SelectFMAD(N);
618     return;
619   case AMDGPUISD::ATOMIC_CMP_SWAP:
620     SelectATOMIC_CMP_SWAP(N);
621     return;
622   }
623 
624   SelectCode(N);
625 }
626 
627 bool AMDGPUDAGToDAGISel::isConstantLoad(const MemSDNode *N, int CbId) const {
628   if (!N->readMem())
629     return false;
630   if (CbId == -1)
631     return N->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS;
632 
633   return N->getAddressSpace() == AMDGPUASI.CONSTANT_BUFFER_0 + CbId;
634 }
635 
636 bool AMDGPUDAGToDAGISel::isUniformBr(const SDNode *N) const {
637   const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
638   const Instruction *Term = BB->getTerminator();
639   return Term->getMetadata("amdgpu.uniform") ||
640          Term->getMetadata("structurizecfg.uniform");
641 }
642 
643 StringRef AMDGPUDAGToDAGISel::getPassName() const {
644   return "AMDGPU DAG->DAG Pattern Instruction Selection";
645 }
646 
647 //===----------------------------------------------------------------------===//
648 // Complex Patterns
649 //===----------------------------------------------------------------------===//
650 
651 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
652                                                          SDValue& IntPtr) {
653   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
654     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, SDLoc(Addr),
655                                        true);
656     return true;
657   }
658   return false;
659 }
660 
661 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
662     SDValue& BaseReg, SDValue &Offset) {
663   if (!isa<ConstantSDNode>(Addr)) {
664     BaseReg = Addr;
665     Offset = CurDAG->getIntPtrConstant(0, SDLoc(Addr), true);
666     return true;
667   }
668   return false;
669 }
670 
671 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
672                                             SDValue &Offset) {
673   return false;
674 }
675 
676 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
677                                             SDValue &Offset) {
678   ConstantSDNode *C;
679   SDLoc DL(Addr);
680 
681   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
682     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
683     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
684   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
685              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
686     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
687     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
688   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
689             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
690     Base = Addr.getOperand(0);
691     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
692   } else {
693     Base = Addr;
694     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
695   }
696 
697   return true;
698 }
699 
700 void AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
701   SDLoc DL(N);
702   SDValue LHS = N->getOperand(0);
703   SDValue RHS = N->getOperand(1);
704 
705   unsigned Opcode = N->getOpcode();
706   bool ConsumeCarry = (Opcode == ISD::ADDE || Opcode == ISD::SUBE);
707   bool ProduceCarry =
708       ConsumeCarry || Opcode == ISD::ADDC || Opcode == ISD::SUBC;
709   bool IsAdd =
710       (Opcode == ISD::ADD || Opcode == ISD::ADDC || Opcode == ISD::ADDE);
711 
712   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
713   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
714 
715   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
716                                        DL, MVT::i32, LHS, Sub0);
717   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
718                                        DL, MVT::i32, LHS, Sub1);
719 
720   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
721                                        DL, MVT::i32, RHS, Sub0);
722   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
723                                        DL, MVT::i32, RHS, Sub1);
724 
725   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
726 
727   unsigned Opc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
728   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
729 
730   SDNode *AddLo;
731   if (!ConsumeCarry) {
732     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
733     AddLo = CurDAG->getMachineNode(Opc, DL, VTList, Args);
734   } else {
735     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(2) };
736     AddLo = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
737   }
738   SDValue AddHiArgs[] = {
739     SDValue(Hi0, 0),
740     SDValue(Hi1, 0),
741     SDValue(AddLo, 1)
742   };
743   SDNode *AddHi = CurDAG->getMachineNode(CarryOpc, DL, VTList, AddHiArgs);
744 
745   SDValue RegSequenceArgs[] = {
746     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
747     SDValue(AddLo,0),
748     Sub0,
749     SDValue(AddHi,0),
750     Sub1,
751   };
752   SDNode *RegSequence = CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
753                                                MVT::i64, RegSequenceArgs);
754 
755   if (ProduceCarry) {
756     // Replace the carry-use
757     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(AddHi, 1));
758   }
759 
760   // Replace the remaining uses.
761   CurDAG->ReplaceAllUsesWith(N, RegSequence);
762   CurDAG->RemoveDeadNode(N);
763 }
764 
765 void AMDGPUDAGToDAGISel::SelectUADDO_USUBO(SDNode *N) {
766   // The name of the opcodes are misleading. v_add_i32/v_sub_i32 have unsigned
767   // carry out despite the _i32 name. These were renamed in VI to _U32.
768   // FIXME: We should probably rename the opcodes here.
769   unsigned Opc = N->getOpcode() == ISD::UADDO ?
770     AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
771 
772   CurDAG->SelectNodeTo(N, Opc, N->getVTList(),
773                        { N->getOperand(0), N->getOperand(1) });
774 }
775 
776 void AMDGPUDAGToDAGISel::SelectFMA_W_CHAIN(SDNode *N) {
777   SDLoc SL(N);
778   //  src0_modifiers, src0,  src1_modifiers, src1, src2_modifiers, src2, clamp, omod
779   SDValue Ops[10];
780 
781   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[6], Ops[7]);
782   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
783   SelectVOP3Mods(N->getOperand(3), Ops[5], Ops[4]);
784   Ops[8] = N->getOperand(0);
785   Ops[9] = N->getOperand(4);
786 
787   CurDAG->SelectNodeTo(N, AMDGPU::V_FMA_F32, N->getVTList(), Ops);
788 }
789 
790 void AMDGPUDAGToDAGISel::SelectFMUL_W_CHAIN(SDNode *N) {
791   SDLoc SL(N);
792   //	src0_modifiers, src0,  src1_modifiers, src1, clamp, omod
793   SDValue Ops[8];
794 
795   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[4], Ops[5]);
796   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
797   Ops[6] = N->getOperand(0);
798   Ops[7] = N->getOperand(3);
799 
800   CurDAG->SelectNodeTo(N, AMDGPU::V_MUL_F32_e64, N->getVTList(), Ops);
801 }
802 
803 // We need to handle this here because tablegen doesn't support matching
804 // instructions with multiple outputs.
805 void AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
806   SDLoc SL(N);
807   EVT VT = N->getValueType(0);
808 
809   assert(VT == MVT::f32 || VT == MVT::f64);
810 
811   unsigned Opc
812     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
813 
814   SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) };
815   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
816 }
817 
818 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(const SDValue &Base, unsigned Offset,
819                                          unsigned OffsetBits) const {
820   if ((OffsetBits == 16 && !isUInt<16>(Offset)) ||
821       (OffsetBits == 8 && !isUInt<8>(Offset)))
822     return false;
823 
824   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS ||
825       Subtarget->unsafeDSOffsetFoldingEnabled())
826     return true;
827 
828   // On Southern Islands instruction with a negative base value and an offset
829   // don't seem to work.
830   return CurDAG->SignBitIsZero(Base);
831 }
832 
833 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
834                                               SDValue &Offset) const {
835   SDLoc DL(Addr);
836   if (CurDAG->isBaseWithConstantOffset(Addr)) {
837     SDValue N0 = Addr.getOperand(0);
838     SDValue N1 = Addr.getOperand(1);
839     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
840     if (isDSOffsetLegal(N0, C1->getSExtValue(), 16)) {
841       // (add n0, c0)
842       Base = N0;
843       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
844       return true;
845     }
846   } else if (Addr.getOpcode() == ISD::SUB) {
847     // sub C, x -> add (sub 0, x), C
848     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
849       int64_t ByteOffset = C->getSExtValue();
850       if (isUInt<16>(ByteOffset)) {
851         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
852 
853         // XXX - This is kind of hacky. Create a dummy sub node so we can check
854         // the known bits in isDSOffsetLegal. We need to emit the selected node
855         // here, so this is thrown away.
856         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
857                                       Zero, Addr.getOperand(1));
858 
859         if (isDSOffsetLegal(Sub, ByteOffset, 16)) {
860           MachineSDNode *MachineSub
861             = CurDAG->getMachineNode(AMDGPU::V_SUB_I32_e32, DL, MVT::i32,
862                                      Zero, Addr.getOperand(1));
863 
864           Base = SDValue(MachineSub, 0);
865           Offset = CurDAG->getTargetConstant(ByteOffset, DL, MVT::i16);
866           return true;
867         }
868       }
869     }
870   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
871     // If we have a constant address, prefer to put the constant into the
872     // offset. This can save moves to load the constant address since multiple
873     // operations can share the zero base address register, and enables merging
874     // into read2 / write2 instructions.
875 
876     SDLoc DL(Addr);
877 
878     if (isUInt<16>(CAddr->getZExtValue())) {
879       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
880       MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
881                                  DL, MVT::i32, Zero);
882       Base = SDValue(MovZero, 0);
883       Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
884       return true;
885     }
886   }
887 
888   // default case
889   Base = Addr;
890   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i16);
891   return true;
892 }
893 
894 // TODO: If offset is too big, put low 16-bit into offset.
895 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
896                                                    SDValue &Offset0,
897                                                    SDValue &Offset1) const {
898   SDLoc DL(Addr);
899 
900   if (CurDAG->isBaseWithConstantOffset(Addr)) {
901     SDValue N0 = Addr.getOperand(0);
902     SDValue N1 = Addr.getOperand(1);
903     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
904     unsigned DWordOffset0 = C1->getZExtValue() / 4;
905     unsigned DWordOffset1 = DWordOffset0 + 1;
906     // (add n0, c0)
907     if (isDSOffsetLegal(N0, DWordOffset1, 8)) {
908       Base = N0;
909       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
910       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
911       return true;
912     }
913   } else if (Addr.getOpcode() == ISD::SUB) {
914     // sub C, x -> add (sub 0, x), C
915     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
916       unsigned DWordOffset0 = C->getZExtValue() / 4;
917       unsigned DWordOffset1 = DWordOffset0 + 1;
918 
919       if (isUInt<8>(DWordOffset0)) {
920         SDLoc DL(Addr);
921         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
922 
923         // XXX - This is kind of hacky. Create a dummy sub node so we can check
924         // the known bits in isDSOffsetLegal. We need to emit the selected node
925         // here, so this is thrown away.
926         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
927                                       Zero, Addr.getOperand(1));
928 
929         if (isDSOffsetLegal(Sub, DWordOffset1, 8)) {
930           MachineSDNode *MachineSub
931             = CurDAG->getMachineNode(AMDGPU::V_SUB_I32_e32, DL, MVT::i32,
932                                      Zero, Addr.getOperand(1));
933 
934           Base = SDValue(MachineSub, 0);
935           Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
936           Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
937           return true;
938         }
939       }
940     }
941   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
942     unsigned DWordOffset0 = CAddr->getZExtValue() / 4;
943     unsigned DWordOffset1 = DWordOffset0 + 1;
944     assert(4 * DWordOffset0 == CAddr->getZExtValue());
945 
946     if (isUInt<8>(DWordOffset0) && isUInt<8>(DWordOffset1)) {
947       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
948       MachineSDNode *MovZero
949         = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
950                                  DL, MVT::i32, Zero);
951       Base = SDValue(MovZero, 0);
952       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
953       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
954       return true;
955     }
956   }
957 
958   // default case
959 
960   // FIXME: This is broken on SI where we still need to check if the base
961   // pointer is positive here.
962   Base = Addr;
963   Offset0 = CurDAG->getTargetConstant(0, DL, MVT::i8);
964   Offset1 = CurDAG->getTargetConstant(1, DL, MVT::i8);
965   return true;
966 }
967 
968 static bool isLegalMUBUFImmOffset(unsigned Imm) {
969   return isUInt<12>(Imm);
970 }
971 
972 static bool isLegalMUBUFImmOffset(const ConstantSDNode *Imm) {
973   return isLegalMUBUFImmOffset(Imm->getZExtValue());
974 }
975 
976 bool AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr,
977                                      SDValue &VAddr, SDValue &SOffset,
978                                      SDValue &Offset, SDValue &Offen,
979                                      SDValue &Idxen, SDValue &Addr64,
980                                      SDValue &GLC, SDValue &SLC,
981                                      SDValue &TFE) const {
982   // Subtarget prefers to use flat instruction
983   if (Subtarget->useFlatForGlobal())
984     return false;
985 
986   SDLoc DL(Addr);
987 
988   if (!GLC.getNode())
989     GLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
990   if (!SLC.getNode())
991     SLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
992   TFE = CurDAG->getTargetConstant(0, DL, MVT::i1);
993 
994   Idxen = CurDAG->getTargetConstant(0, DL, MVT::i1);
995   Offen = CurDAG->getTargetConstant(0, DL, MVT::i1);
996   Addr64 = CurDAG->getTargetConstant(0, DL, MVT::i1);
997   SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
998 
999   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1000     SDValue N0 = Addr.getOperand(0);
1001     SDValue N1 = Addr.getOperand(1);
1002     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1003 
1004     if (N0.getOpcode() == ISD::ADD) {
1005       // (add (add N2, N3), C1) -> addr64
1006       SDValue N2 = N0.getOperand(0);
1007       SDValue N3 = N0.getOperand(1);
1008       Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1009       Ptr = N2;
1010       VAddr = N3;
1011     } else {
1012       // (add N0, C1) -> offset
1013       VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
1014       Ptr = N0;
1015     }
1016 
1017     if (isLegalMUBUFImmOffset(C1)) {
1018       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1019       return true;
1020     }
1021 
1022     if (isUInt<32>(C1->getZExtValue())) {
1023       // Illegal offset, store it in soffset.
1024       Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1025       SOffset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
1026                    CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32)),
1027                         0);
1028       return true;
1029     }
1030   }
1031 
1032   if (Addr.getOpcode() == ISD::ADD) {
1033     // (add N0, N1) -> addr64
1034     SDValue N0 = Addr.getOperand(0);
1035     SDValue N1 = Addr.getOperand(1);
1036     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1037     Ptr = N0;
1038     VAddr = N1;
1039     Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1040     return true;
1041   }
1042 
1043   // default case -> offset
1044   VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
1045   Ptr = Addr;
1046   Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1047 
1048   return true;
1049 }
1050 
1051 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1052                                            SDValue &VAddr, SDValue &SOffset,
1053                                            SDValue &Offset, SDValue &GLC,
1054                                            SDValue &SLC, SDValue &TFE) const {
1055   SDValue Ptr, Offen, Idxen, Addr64;
1056 
1057   // addr64 bit was removed for volcanic islands.
1058   if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1059     return false;
1060 
1061   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1062               GLC, SLC, TFE))
1063     return false;
1064 
1065   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
1066   if (C->getSExtValue()) {
1067     SDLoc DL(Addr);
1068 
1069     const SITargetLowering& Lowering =
1070       *static_cast<const SITargetLowering*>(getTargetLowering());
1071 
1072     SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
1073     return true;
1074   }
1075 
1076   return false;
1077 }
1078 
1079 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1080                                            SDValue &VAddr, SDValue &SOffset,
1081                                            SDValue &Offset,
1082                                            SDValue &SLC) const {
1083   SLC = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i1);
1084   SDValue GLC, TFE;
1085 
1086   return SelectMUBUFAddr64(Addr, SRsrc, VAddr, SOffset, Offset, GLC, SLC, TFE);
1087 }
1088 
1089 static bool isStackPtrRelative(const MachinePointerInfo &PtrInfo) {
1090   auto PSV = PtrInfo.V.dyn_cast<const PseudoSourceValue *>();
1091   return PSV && PSV->isStack();
1092 }
1093 
1094 std::pair<SDValue, SDValue> AMDGPUDAGToDAGISel::foldFrameIndex(SDValue N) const {
1095   const MachineFunction &MF = CurDAG->getMachineFunction();
1096   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1097 
1098   if (auto FI = dyn_cast<FrameIndexSDNode>(N)) {
1099     SDValue TFI = CurDAG->getTargetFrameIndex(FI->getIndex(),
1100                                               FI->getValueType(0));
1101 
1102     // If we can resolve this to a frame index access, this is relative to the
1103     // frame pointer SGPR.
1104     return std::make_pair(TFI, CurDAG->getRegister(Info->getFrameOffsetReg(),
1105                                                    MVT::i32));
1106   }
1107 
1108   // If we don't know this private access is a local stack object, it needs to
1109   // be relative to the entry point's scratch wave offset register.
1110   return std::make_pair(N, CurDAG->getRegister(Info->getScratchWaveOffsetReg(),
1111                                                MVT::i32));
1112 }
1113 
1114 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(SDNode *Parent,
1115                                                  SDValue Addr, SDValue &Rsrc,
1116                                                  SDValue &VAddr, SDValue &SOffset,
1117                                                  SDValue &ImmOffset) const {
1118 
1119   SDLoc DL(Addr);
1120   MachineFunction &MF = CurDAG->getMachineFunction();
1121   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1122 
1123   Rsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1124 
1125   if (ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1126     unsigned Imm = CAddr->getZExtValue();
1127     assert(!isLegalMUBUFImmOffset(Imm) &&
1128            "should have been selected by other pattern");
1129 
1130     SDValue HighBits = CurDAG->getTargetConstant(Imm & ~4095, DL, MVT::i32);
1131     MachineSDNode *MovHighBits = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1132                                                         DL, MVT::i32, HighBits);
1133     VAddr = SDValue(MovHighBits, 0);
1134 
1135     // In a call sequence, stores to the argument stack area are relative to the
1136     // stack pointer.
1137     const MachinePointerInfo &PtrInfo = cast<MemSDNode>(Parent)->getPointerInfo();
1138     unsigned SOffsetReg = isStackPtrRelative(PtrInfo) ?
1139       Info->getStackPtrOffsetReg() : Info->getScratchWaveOffsetReg();
1140 
1141     SOffset = CurDAG->getRegister(SOffsetReg, MVT::i32);
1142     ImmOffset = CurDAG->getTargetConstant(Imm & 4095, DL, MVT::i16);
1143     return true;
1144   }
1145 
1146   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1147     // (add n0, c1)
1148 
1149     SDValue N0 = Addr.getOperand(0);
1150     SDValue N1 = Addr.getOperand(1);
1151 
1152     // Offsets in vaddr must be positive.
1153     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1154     if (isLegalMUBUFImmOffset(C1)) {
1155       std::tie(VAddr, SOffset) = foldFrameIndex(N0);
1156       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1157       return true;
1158     }
1159   }
1160 
1161   // (node)
1162   std::tie(VAddr, SOffset) = foldFrameIndex(Addr);
1163   ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1164   return true;
1165 }
1166 
1167 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffset(SDNode *Parent,
1168                                                   SDValue Addr,
1169                                                   SDValue &SRsrc,
1170                                                   SDValue &SOffset,
1171                                                   SDValue &Offset) const {
1172   ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr);
1173   if (!CAddr || !isLegalMUBUFImmOffset(CAddr))
1174     return false;
1175 
1176   SDLoc DL(Addr);
1177   MachineFunction &MF = CurDAG->getMachineFunction();
1178   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1179 
1180   SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1181 
1182   const MachinePointerInfo &PtrInfo = cast<MemSDNode>(Parent)->getPointerInfo();
1183   unsigned SOffsetReg = isStackPtrRelative(PtrInfo) ?
1184     Info->getStackPtrOffsetReg() : Info->getScratchWaveOffsetReg();
1185 
1186   // FIXME: Get from MachinePointerInfo? We should only be using the frame
1187   // offset if we know this is in a call sequence.
1188   SOffset = CurDAG->getRegister(SOffsetReg, MVT::i32);
1189 
1190   Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1191   return true;
1192 }
1193 
1194 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1195                                            SDValue &SOffset, SDValue &Offset,
1196                                            SDValue &GLC, SDValue &SLC,
1197                                            SDValue &TFE) const {
1198   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1199   const SIInstrInfo *TII =
1200     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1201 
1202   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1203               GLC, SLC, TFE))
1204     return false;
1205 
1206   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1207       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1208       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1209     uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1210                     APInt::getAllOnesValue(32).getZExtValue(); // Size
1211     SDLoc DL(Addr);
1212 
1213     const SITargetLowering& Lowering =
1214       *static_cast<const SITargetLowering*>(getTargetLowering());
1215 
1216     SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1217     return true;
1218   }
1219   return false;
1220 }
1221 
1222 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1223                                            SDValue &Soffset, SDValue &Offset
1224                                            ) const {
1225   SDValue GLC, SLC, TFE;
1226 
1227   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE);
1228 }
1229 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1230                                            SDValue &Soffset, SDValue &Offset,
1231                                            SDValue &SLC) const {
1232   SDValue GLC, TFE;
1233 
1234   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE);
1235 }
1236 
1237 bool AMDGPUDAGToDAGISel::SelectMUBUFConstant(SDValue Constant,
1238                                              SDValue &SOffset,
1239                                              SDValue &ImmOffset) const {
1240   SDLoc DL(Constant);
1241   const uint32_t Align = 4;
1242   const uint32_t MaxImm = alignDown(4095, Align);
1243   uint32_t Imm = cast<ConstantSDNode>(Constant)->getZExtValue();
1244   uint32_t Overflow = 0;
1245 
1246   if (Imm > MaxImm) {
1247     if (Imm <= MaxImm + 64) {
1248       // Use an SOffset inline constant for 4..64
1249       Overflow = Imm - MaxImm;
1250       Imm = MaxImm;
1251     } else {
1252       // Try to keep the same value in SOffset for adjacent loads, so that
1253       // the corresponding register contents can be re-used.
1254       //
1255       // Load values with all low-bits (except for alignment bits) set into
1256       // SOffset, so that a larger range of values can be covered using
1257       // s_movk_i32.
1258       //
1259       // Atomic operations fail to work correctly when individual address
1260       // components are unaligned, even if their sum is aligned.
1261       uint32_t High = (Imm + Align) & ~4095;
1262       uint32_t Low = (Imm + Align) & 4095;
1263       Imm = Low;
1264       Overflow = High - Align;
1265     }
1266   }
1267 
1268   // There is a hardware bug in SI and CI which prevents address clamping in
1269   // MUBUF instructions from working correctly with SOffsets. The immediate
1270   // offset is unaffected.
1271   if (Overflow > 0 &&
1272       Subtarget->getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
1273     return false;
1274 
1275   ImmOffset = CurDAG->getTargetConstant(Imm, DL, MVT::i16);
1276 
1277   if (Overflow <= 64)
1278     SOffset = CurDAG->getTargetConstant(Overflow, DL, MVT::i32);
1279   else
1280     SOffset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
1281                       CurDAG->getTargetConstant(Overflow, DL, MVT::i32)),
1282                       0);
1283 
1284   return true;
1285 }
1286 
1287 bool AMDGPUDAGToDAGISel::SelectMUBUFIntrinsicOffset(SDValue Offset,
1288                                                     SDValue &SOffset,
1289                                                     SDValue &ImmOffset) const {
1290   SDLoc DL(Offset);
1291 
1292   if (!isa<ConstantSDNode>(Offset))
1293     return false;
1294 
1295   return SelectMUBUFConstant(Offset, SOffset, ImmOffset);
1296 }
1297 
1298 bool AMDGPUDAGToDAGISel::SelectMUBUFIntrinsicVOffset(SDValue Offset,
1299                                                      SDValue &SOffset,
1300                                                      SDValue &ImmOffset,
1301                                                      SDValue &VOffset) const {
1302   SDLoc DL(Offset);
1303 
1304   // Don't generate an unnecessary voffset for constant offsets.
1305   if (isa<ConstantSDNode>(Offset)) {
1306     SDValue Tmp1, Tmp2;
1307 
1308     // When necessary, use a voffset in <= CI anyway to work around a hardware
1309     // bug.
1310     if (Subtarget->getGeneration() > AMDGPUSubtarget::SEA_ISLANDS ||
1311         SelectMUBUFConstant(Offset, Tmp1, Tmp2))
1312       return false;
1313   }
1314 
1315   if (CurDAG->isBaseWithConstantOffset(Offset)) {
1316     SDValue N0 = Offset.getOperand(0);
1317     SDValue N1 = Offset.getOperand(1);
1318     if (cast<ConstantSDNode>(N1)->getSExtValue() >= 0 &&
1319         SelectMUBUFConstant(N1, SOffset, ImmOffset)) {
1320       VOffset = N0;
1321       return true;
1322     }
1323   }
1324 
1325   SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1326   ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1327   VOffset = Offset;
1328 
1329   return true;
1330 }
1331 
1332 template <bool IsSigned>
1333 bool AMDGPUDAGToDAGISel::SelectFlatOffset(SDValue Addr,
1334                                           SDValue &VAddr,
1335                                           SDValue &Offset,
1336                                           SDValue &SLC) const {
1337   int64_t OffsetVal = 0;
1338 
1339   if (Subtarget->hasFlatInstOffsets() &&
1340       CurDAG->isBaseWithConstantOffset(Addr)) {
1341     SDValue N0 = Addr.getOperand(0);
1342     SDValue N1 = Addr.getOperand(1);
1343     int64_t COffsetVal = cast<ConstantSDNode>(N1)->getSExtValue();
1344 
1345     if ((IsSigned && isInt<13>(COffsetVal)) ||
1346         (!IsSigned && isUInt<12>(COffsetVal))) {
1347       Addr = N0;
1348       OffsetVal = COffsetVal;
1349     }
1350   }
1351 
1352   VAddr = Addr;
1353   Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i16);
1354   SLC = CurDAG->getTargetConstant(0, SDLoc(), MVT::i1);
1355 
1356   return true;
1357 }
1358 
1359 bool AMDGPUDAGToDAGISel::SelectFlatAtomic(SDValue Addr,
1360                                           SDValue &VAddr,
1361                                           SDValue &Offset,
1362                                           SDValue &SLC) const {
1363   return SelectFlatOffset<false>(Addr, VAddr, Offset, SLC);
1364 }
1365 
1366 bool AMDGPUDAGToDAGISel::SelectFlatAtomicSigned(SDValue Addr,
1367                                           SDValue &VAddr,
1368                                           SDValue &Offset,
1369                                           SDValue &SLC) const {
1370   return SelectFlatOffset<true>(Addr, VAddr, Offset, SLC);
1371 }
1372 
1373 bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDValue ByteOffsetNode,
1374                                           SDValue &Offset, bool &Imm) const {
1375 
1376   // FIXME: Handle non-constant offsets.
1377   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ByteOffsetNode);
1378   if (!C)
1379     return false;
1380 
1381   SDLoc SL(ByteOffsetNode);
1382   AMDGPUSubtarget::Generation Gen = Subtarget->getGeneration();
1383   int64_t ByteOffset = C->getSExtValue();
1384   int64_t EncodedOffset = AMDGPU::getSMRDEncodedOffset(*Subtarget, ByteOffset);
1385 
1386   if (AMDGPU::isLegalSMRDImmOffset(*Subtarget, ByteOffset)) {
1387     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1388     Imm = true;
1389     return true;
1390   }
1391 
1392   if (!isUInt<32>(EncodedOffset) || !isUInt<32>(ByteOffset))
1393     return false;
1394 
1395   if (Gen == AMDGPUSubtarget::SEA_ISLANDS && isUInt<32>(EncodedOffset)) {
1396     // 32-bit Immediates are supported on Sea Islands.
1397     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1398   } else {
1399     SDValue C32Bit = CurDAG->getTargetConstant(ByteOffset, SL, MVT::i32);
1400     Offset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32,
1401                                             C32Bit), 0);
1402   }
1403   Imm = false;
1404   return true;
1405 }
1406 
1407 bool AMDGPUDAGToDAGISel::SelectSMRD(SDValue Addr, SDValue &SBase,
1408                                      SDValue &Offset, bool &Imm) const {
1409   SDLoc SL(Addr);
1410   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1411     SDValue N0 = Addr.getOperand(0);
1412     SDValue N1 = Addr.getOperand(1);
1413 
1414     if (SelectSMRDOffset(N1, Offset, Imm)) {
1415       SBase = N0;
1416       return true;
1417     }
1418   }
1419   SBase = Addr;
1420   Offset = CurDAG->getTargetConstant(0, SL, MVT::i32);
1421   Imm = true;
1422   return true;
1423 }
1424 
1425 bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
1426                                        SDValue &Offset) const {
1427   bool Imm;
1428   return SelectSMRD(Addr, SBase, Offset, Imm) && Imm;
1429 }
1430 
1431 bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
1432                                          SDValue &Offset) const {
1433 
1434   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1435     return false;
1436 
1437   bool Imm;
1438   if (!SelectSMRD(Addr, SBase, Offset, Imm))
1439     return false;
1440 
1441   return !Imm && isa<ConstantSDNode>(Offset);
1442 }
1443 
1444 bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDValue Addr, SDValue &SBase,
1445                                         SDValue &Offset) const {
1446   bool Imm;
1447   return SelectSMRD(Addr, SBase, Offset, Imm) && !Imm &&
1448          !isa<ConstantSDNode>(Offset);
1449 }
1450 
1451 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue Addr,
1452                                              SDValue &Offset) const {
1453   bool Imm;
1454   return SelectSMRDOffset(Addr, Offset, Imm) && Imm;
1455 }
1456 
1457 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue Addr,
1458                                                SDValue &Offset) const {
1459   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1460     return false;
1461 
1462   bool Imm;
1463   if (!SelectSMRDOffset(Addr, Offset, Imm))
1464     return false;
1465 
1466   return !Imm && isa<ConstantSDNode>(Offset);
1467 }
1468 
1469 bool AMDGPUDAGToDAGISel::SelectSMRDBufferSgpr(SDValue Addr,
1470                                               SDValue &Offset) const {
1471   bool Imm;
1472   return SelectSMRDOffset(Addr, Offset, Imm) && !Imm &&
1473          !isa<ConstantSDNode>(Offset);
1474 }
1475 
1476 bool AMDGPUDAGToDAGISel::SelectMOVRELOffset(SDValue Index,
1477                                             SDValue &Base,
1478                                             SDValue &Offset) const {
1479   SDLoc DL(Index);
1480 
1481   if (CurDAG->isBaseWithConstantOffset(Index)) {
1482     SDValue N0 = Index.getOperand(0);
1483     SDValue N1 = Index.getOperand(1);
1484     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1485 
1486     // (add n0, c0)
1487     Base = N0;
1488     Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
1489     return true;
1490   }
1491 
1492   if (isa<ConstantSDNode>(Index))
1493     return false;
1494 
1495   Base = Index;
1496   Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1497   return true;
1498 }
1499 
1500 SDNode *AMDGPUDAGToDAGISel::getS_BFE(unsigned Opcode, const SDLoc &DL,
1501                                      SDValue Val, uint32_t Offset,
1502                                      uint32_t Width) {
1503   // Transformation function, pack the offset and width of a BFE into
1504   // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
1505   // source, bits [5:0] contain the offset and bits [22:16] the width.
1506   uint32_t PackedVal = Offset | (Width << 16);
1507   SDValue PackedConst = CurDAG->getTargetConstant(PackedVal, DL, MVT::i32);
1508 
1509   return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, PackedConst);
1510 }
1511 
1512 void AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
1513   // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
1514   // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
1515   // Predicate: 0 < b <= c < 32
1516 
1517   const SDValue &Shl = N->getOperand(0);
1518   ConstantSDNode *B = dyn_cast<ConstantSDNode>(Shl->getOperand(1));
1519   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1520 
1521   if (B && C) {
1522     uint32_t BVal = B->getZExtValue();
1523     uint32_t CVal = C->getZExtValue();
1524 
1525     if (0 < BVal && BVal <= CVal && CVal < 32) {
1526       bool Signed = N->getOpcode() == ISD::SRA;
1527       unsigned Opcode = Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
1528 
1529       ReplaceNode(N, getS_BFE(Opcode, SDLoc(N), Shl.getOperand(0), CVal - BVal,
1530                               32 - CVal));
1531       return;
1532     }
1533   }
1534   SelectCode(N);
1535 }
1536 
1537 void AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
1538   switch (N->getOpcode()) {
1539   case ISD::AND:
1540     if (N->getOperand(0).getOpcode() == ISD::SRL) {
1541       // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
1542       // Predicate: isMask(mask)
1543       const SDValue &Srl = N->getOperand(0);
1544       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Srl.getOperand(1));
1545       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
1546 
1547       if (Shift && Mask) {
1548         uint32_t ShiftVal = Shift->getZExtValue();
1549         uint32_t MaskVal = Mask->getZExtValue();
1550 
1551         if (isMask_32(MaskVal)) {
1552           uint32_t WidthVal = countPopulation(MaskVal);
1553 
1554           ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N),
1555                                   Srl.getOperand(0), ShiftVal, WidthVal));
1556           return;
1557         }
1558       }
1559     }
1560     break;
1561   case ISD::SRL:
1562     if (N->getOperand(0).getOpcode() == ISD::AND) {
1563       // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
1564       // Predicate: isMask(mask >> b)
1565       const SDValue &And = N->getOperand(0);
1566       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N->getOperand(1));
1567       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(And->getOperand(1));
1568 
1569       if (Shift && Mask) {
1570         uint32_t ShiftVal = Shift->getZExtValue();
1571         uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
1572 
1573         if (isMask_32(MaskVal)) {
1574           uint32_t WidthVal = countPopulation(MaskVal);
1575 
1576           ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N),
1577                                   And.getOperand(0), ShiftVal, WidthVal));
1578           return;
1579         }
1580       }
1581     } else if (N->getOperand(0).getOpcode() == ISD::SHL) {
1582       SelectS_BFEFromShifts(N);
1583       return;
1584     }
1585     break;
1586   case ISD::SRA:
1587     if (N->getOperand(0).getOpcode() == ISD::SHL) {
1588       SelectS_BFEFromShifts(N);
1589       return;
1590     }
1591     break;
1592 
1593   case ISD::SIGN_EXTEND_INREG: {
1594     // sext_inreg (srl x, 16), i8 -> bfe_i32 x, 16, 8
1595     SDValue Src = N->getOperand(0);
1596     if (Src.getOpcode() != ISD::SRL)
1597       break;
1598 
1599     const ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
1600     if (!Amt)
1601       break;
1602 
1603     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
1604     ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_I32, SDLoc(N), Src.getOperand(0),
1605                             Amt->getZExtValue(), Width));
1606     return;
1607   }
1608   }
1609 
1610   SelectCode(N);
1611 }
1612 
1613 bool AMDGPUDAGToDAGISel::isCBranchSCC(const SDNode *N) const {
1614   assert(N->getOpcode() == ISD::BRCOND);
1615   if (!N->hasOneUse())
1616     return false;
1617 
1618   SDValue Cond = N->getOperand(1);
1619   if (Cond.getOpcode() == ISD::CopyToReg)
1620     Cond = Cond.getOperand(2);
1621 
1622   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
1623     return false;
1624 
1625   MVT VT = Cond.getOperand(0).getSimpleValueType();
1626   if (VT == MVT::i32)
1627     return true;
1628 
1629   if (VT == MVT::i64) {
1630     auto ST = static_cast<const SISubtarget *>(Subtarget);
1631 
1632     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
1633     return (CC == ISD::SETEQ || CC == ISD::SETNE) && ST->hasScalarCompareEq64();
1634   }
1635 
1636   return false;
1637 }
1638 
1639 void AMDGPUDAGToDAGISel::SelectBRCOND(SDNode *N) {
1640   SDValue Cond = N->getOperand(1);
1641 
1642   if (Cond.isUndef()) {
1643     CurDAG->SelectNodeTo(N, AMDGPU::SI_BR_UNDEF, MVT::Other,
1644                          N->getOperand(2), N->getOperand(0));
1645     return;
1646   }
1647 
1648   bool UseSCCBr = isCBranchSCC(N) && isUniformBr(N);
1649   unsigned BrOp = UseSCCBr ? AMDGPU::S_CBRANCH_SCC1 : AMDGPU::S_CBRANCH_VCCNZ;
1650   unsigned CondReg = UseSCCBr ? AMDGPU::SCC : AMDGPU::VCC;
1651   SDLoc SL(N);
1652 
1653   SDValue VCC = CurDAG->getCopyToReg(N->getOperand(0), SL, CondReg, Cond);
1654   CurDAG->SelectNodeTo(N, BrOp, MVT::Other,
1655                        N->getOperand(2), // Basic Block
1656                        VCC.getValue(0));
1657 }
1658 
1659 void AMDGPUDAGToDAGISel::SelectFMAD(SDNode *N) {
1660   MVT VT = N->getSimpleValueType(0);
1661   if (VT != MVT::f32 || !Subtarget->hasMadMixInsts()) {
1662     SelectCode(N);
1663     return;
1664   }
1665 
1666   SDValue Src0 = N->getOperand(0);
1667   SDValue Src1 = N->getOperand(1);
1668   SDValue Src2 = N->getOperand(2);
1669   unsigned Src0Mods, Src1Mods, Src2Mods;
1670 
1671   // Avoid using v_mad_mix_f32 unless there is actually an operand using the
1672   // conversion from f16.
1673   bool Sel0 = SelectVOP3PMadMixModsImpl(Src0, Src0, Src0Mods);
1674   bool Sel1 = SelectVOP3PMadMixModsImpl(Src1, Src1, Src1Mods);
1675   bool Sel2 = SelectVOP3PMadMixModsImpl(Src2, Src2, Src2Mods);
1676 
1677   assert(!Subtarget->hasFP32Denormals() &&
1678          "fmad selected with denormals enabled");
1679   // TODO: We can select this with f32 denormals enabled if all the sources are
1680   // converted from f16 (in which case fmad isn't legal).
1681 
1682   if (Sel0 || Sel1 || Sel2) {
1683     // For dummy operands.
1684     SDValue Zero = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
1685     SDValue Ops[] = {
1686       CurDAG->getTargetConstant(Src0Mods, SDLoc(), MVT::i32), Src0,
1687       CurDAG->getTargetConstant(Src1Mods, SDLoc(), MVT::i32), Src1,
1688       CurDAG->getTargetConstant(Src2Mods, SDLoc(), MVT::i32), Src2,
1689       CurDAG->getTargetConstant(0, SDLoc(), MVT::i1),
1690       Zero, Zero
1691     };
1692 
1693     CurDAG->SelectNodeTo(N, AMDGPU::V_MAD_MIX_F32, MVT::f32, Ops);
1694   } else {
1695     SelectCode(N);
1696   }
1697 }
1698 
1699 // This is here because there isn't a way to use the generated sub0_sub1 as the
1700 // subreg index to EXTRACT_SUBREG in tablegen.
1701 void AMDGPUDAGToDAGISel::SelectATOMIC_CMP_SWAP(SDNode *N) {
1702   MemSDNode *Mem = cast<MemSDNode>(N);
1703   unsigned AS = Mem->getAddressSpace();
1704   if (AS == AMDGPUASI.FLAT_ADDRESS) {
1705     SelectCode(N);
1706     return;
1707   }
1708 
1709   MVT VT = N->getSimpleValueType(0);
1710   bool Is32 = (VT == MVT::i32);
1711   SDLoc SL(N);
1712 
1713   MachineSDNode *CmpSwap = nullptr;
1714   if (Subtarget->hasAddr64()) {
1715     SDValue SRsrc, VAddr, SOffset, Offset, GLC, SLC;
1716 
1717     if (SelectMUBUFAddr64(Mem->getBasePtr(), SRsrc, VAddr, SOffset, Offset, SLC)) {
1718       unsigned Opcode = Is32 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_ADDR64_RTN :
1719         AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_ADDR64_RTN;
1720       SDValue CmpVal = Mem->getOperand(2);
1721 
1722       // XXX - Do we care about glue operands?
1723 
1724       SDValue Ops[] = {
1725         CmpVal, VAddr, SRsrc, SOffset, Offset, SLC, Mem->getChain()
1726       };
1727 
1728       CmpSwap = CurDAG->getMachineNode(Opcode, SL, Mem->getVTList(), Ops);
1729     }
1730   }
1731 
1732   if (!CmpSwap) {
1733     SDValue SRsrc, SOffset, Offset, SLC;
1734     if (SelectMUBUFOffset(Mem->getBasePtr(), SRsrc, SOffset, Offset, SLC)) {
1735       unsigned Opcode = Is32 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_OFFSET_RTN :
1736         AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_OFFSET_RTN;
1737 
1738       SDValue CmpVal = Mem->getOperand(2);
1739       SDValue Ops[] = {
1740         CmpVal, SRsrc, SOffset, Offset, SLC, Mem->getChain()
1741       };
1742 
1743       CmpSwap = CurDAG->getMachineNode(Opcode, SL, Mem->getVTList(), Ops);
1744     }
1745   }
1746 
1747   if (!CmpSwap) {
1748     SelectCode(N);
1749     return;
1750   }
1751 
1752   MachineSDNode::mmo_iterator MMOs = MF->allocateMemRefsArray(1);
1753   *MMOs = Mem->getMemOperand();
1754   CmpSwap->setMemRefs(MMOs, MMOs + 1);
1755 
1756   unsigned SubReg = Is32 ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
1757   SDValue Extract
1758     = CurDAG->getTargetExtractSubreg(SubReg, SL, VT, SDValue(CmpSwap, 0));
1759 
1760   ReplaceUses(SDValue(N, 0), Extract);
1761   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 1));
1762   CurDAG->RemoveDeadNode(N);
1763 }
1764 
1765 bool AMDGPUDAGToDAGISel::SelectVOP3ModsImpl(SDValue In, SDValue &Src,
1766                                             unsigned &Mods) const {
1767   Mods = 0;
1768   Src = In;
1769 
1770   if (Src.getOpcode() == ISD::FNEG) {
1771     Mods |= SISrcMods::NEG;
1772     Src = Src.getOperand(0);
1773   }
1774 
1775   if (Src.getOpcode() == ISD::FABS) {
1776     Mods |= SISrcMods::ABS;
1777     Src = Src.getOperand(0);
1778   }
1779 
1780   return true;
1781 }
1782 
1783 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
1784                                         SDValue &SrcMods) const {
1785   unsigned Mods;
1786   if (SelectVOP3ModsImpl(In, Src, Mods)) {
1787     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
1788     return true;
1789   }
1790 
1791   return false;
1792 }
1793 
1794 bool AMDGPUDAGToDAGISel::SelectVOP3Mods_NNaN(SDValue In, SDValue &Src,
1795                                              SDValue &SrcMods) const {
1796   SelectVOP3Mods(In, Src, SrcMods);
1797   return isNoNanSrc(Src);
1798 }
1799 
1800 bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src) const {
1801   if (In.getOpcode() == ISD::FABS || In.getOpcode() == ISD::FNEG)
1802     return false;
1803 
1804   Src = In;
1805   return true;
1806 }
1807 
1808 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
1809                                          SDValue &SrcMods, SDValue &Clamp,
1810                                          SDValue &Omod) const {
1811   SDLoc DL(In);
1812   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
1813   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
1814 
1815   return SelectVOP3Mods(In, Src, SrcMods);
1816 }
1817 
1818 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src,
1819                                                    SDValue &SrcMods,
1820                                                    SDValue &Clamp,
1821                                                    SDValue &Omod) const {
1822   Clamp = Omod = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
1823   return SelectVOP3Mods(In, Src, SrcMods);
1824 }
1825 
1826 bool AMDGPUDAGToDAGISel::SelectVOP3OMods(SDValue In, SDValue &Src,
1827                                          SDValue &Clamp, SDValue &Omod) const {
1828   Src = In;
1829 
1830   SDLoc DL(In);
1831   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
1832   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
1833 
1834   return true;
1835 }
1836 
1837 static SDValue stripBitcast(SDValue Val) {
1838   return Val.getOpcode() == ISD::BITCAST ? Val.getOperand(0) : Val;
1839 }
1840 
1841 // Figure out if this is really an extract of the high 16-bits of a dword.
1842 static bool isExtractHiElt(SDValue In, SDValue &Out) {
1843   In = stripBitcast(In);
1844   if (In.getOpcode() != ISD::TRUNCATE)
1845     return false;
1846 
1847   SDValue Srl = In.getOperand(0);
1848   if (Srl.getOpcode() == ISD::SRL) {
1849     if (ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
1850       if (ShiftAmt->getZExtValue() == 16) {
1851         Out = stripBitcast(Srl.getOperand(0));
1852         return true;
1853       }
1854     }
1855   }
1856 
1857   return false;
1858 }
1859 
1860 // Look through operations that obscure just looking at the low 16-bits of the
1861 // same register.
1862 static SDValue stripExtractLoElt(SDValue In) {
1863   if (In.getOpcode() == ISD::TRUNCATE) {
1864     SDValue Src = In.getOperand(0);
1865     if (Src.getValueType().getSizeInBits() == 32)
1866       return stripBitcast(Src);
1867   }
1868 
1869   return In;
1870 }
1871 
1872 bool AMDGPUDAGToDAGISel::SelectVOP3PMods(SDValue In, SDValue &Src,
1873                                          SDValue &SrcMods) const {
1874   unsigned Mods = 0;
1875   Src = In;
1876 
1877   if (Src.getOpcode() == ISD::FNEG) {
1878     Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
1879     Src = Src.getOperand(0);
1880   }
1881 
1882   if (Src.getOpcode() == ISD::BUILD_VECTOR) {
1883     unsigned VecMods = Mods;
1884 
1885     SDValue Lo = stripBitcast(Src.getOperand(0));
1886     SDValue Hi = stripBitcast(Src.getOperand(1));
1887 
1888     if (Lo.getOpcode() == ISD::FNEG) {
1889       Lo = stripBitcast(Lo.getOperand(0));
1890       Mods ^= SISrcMods::NEG;
1891     }
1892 
1893     if (Hi.getOpcode() == ISD::FNEG) {
1894       Hi = stripBitcast(Hi.getOperand(0));
1895       Mods ^= SISrcMods::NEG_HI;
1896     }
1897 
1898     if (isExtractHiElt(Lo, Lo))
1899       Mods |= SISrcMods::OP_SEL_0;
1900 
1901     if (isExtractHiElt(Hi, Hi))
1902       Mods |= SISrcMods::OP_SEL_1;
1903 
1904     Lo = stripExtractLoElt(Lo);
1905     Hi = stripExtractLoElt(Hi);
1906 
1907     if (Lo == Hi && !isInlineImmediate(Lo.getNode())) {
1908       // Really a scalar input. Just select from the low half of the register to
1909       // avoid packing.
1910 
1911       Src = Lo;
1912       SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
1913       return true;
1914     }
1915 
1916     Mods = VecMods;
1917   }
1918 
1919   // Packed instructions do not have abs modifiers.
1920   Mods |= SISrcMods::OP_SEL_1;
1921 
1922   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
1923   return true;
1924 }
1925 
1926 bool AMDGPUDAGToDAGISel::SelectVOP3PMods0(SDValue In, SDValue &Src,
1927                                           SDValue &SrcMods,
1928                                           SDValue &Clamp) const {
1929   SDLoc SL(In);
1930 
1931   // FIXME: Handle clamp and op_sel
1932   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
1933 
1934   return SelectVOP3PMods(In, Src, SrcMods);
1935 }
1936 
1937 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel(SDValue In, SDValue &Src,
1938                                          SDValue &SrcMods) const {
1939   Src = In;
1940   // FIXME: Handle op_sel
1941   SrcMods = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
1942   return true;
1943 }
1944 
1945 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel0(SDValue In, SDValue &Src,
1946                                           SDValue &SrcMods,
1947                                           SDValue &Clamp) const {
1948   SDLoc SL(In);
1949 
1950   // FIXME: Handle clamp
1951   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
1952 
1953   return SelectVOP3OpSel(In, Src, SrcMods);
1954 }
1955 
1956 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods(SDValue In, SDValue &Src,
1957                                              SDValue &SrcMods) const {
1958   // FIXME: Handle op_sel
1959   return SelectVOP3Mods(In, Src, SrcMods);
1960 }
1961 
1962 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods0(SDValue In, SDValue &Src,
1963                                               SDValue &SrcMods,
1964                                               SDValue &Clamp) const {
1965   SDLoc SL(In);
1966 
1967   // FIXME: Handle clamp
1968   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
1969 
1970   return SelectVOP3OpSelMods(In, Src, SrcMods);
1971 }
1972 
1973 // The return value is not whether the match is possible (which it always is),
1974 // but whether or not it a conversion is really used.
1975 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src,
1976                                                    unsigned &Mods) const {
1977   Mods = 0;
1978   SelectVOP3ModsImpl(In, Src, Mods);
1979 
1980   if (Src.getOpcode() == ISD::FP_EXTEND) {
1981     Src = Src.getOperand(0);
1982     assert(Src.getValueType() == MVT::f16);
1983     Src = stripBitcast(Src);
1984 
1985     // Be careful about folding modifiers if we already have an abs. fneg is
1986     // applied last, so we don't want to apply an earlier fneg.
1987     if ((Mods & SISrcMods::ABS) == 0) {
1988       unsigned ModsTmp;
1989       SelectVOP3ModsImpl(Src, Src, ModsTmp);
1990 
1991       if ((ModsTmp & SISrcMods::NEG) != 0)
1992         Mods ^= SISrcMods::NEG;
1993 
1994       if ((ModsTmp & SISrcMods::ABS) != 0)
1995         Mods |= SISrcMods::ABS;
1996     }
1997 
1998     // op_sel/op_sel_hi decide the source type and source.
1999     // If the source's op_sel_hi is set, it indicates to do a conversion from fp16.
2000     // If the sources's op_sel is set, it picks the high half of the source
2001     // register.
2002 
2003     Mods |= SISrcMods::OP_SEL_1;
2004     if (isExtractHiElt(Src, Src)) {
2005       Mods |= SISrcMods::OP_SEL_0;
2006 
2007       // TODO: Should we try to look for neg/abs here?
2008     }
2009 
2010     return true;
2011   }
2012 
2013   return false;
2014 }
2015 
2016 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixMods(SDValue In, SDValue &Src,
2017                                                SDValue &SrcMods) const {
2018   unsigned Mods = 0;
2019   SelectVOP3PMadMixModsImpl(In, Src, Mods);
2020   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2021   return true;
2022 }
2023 
2024 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
2025   const AMDGPUTargetLowering& Lowering =
2026     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
2027   bool IsModified = false;
2028   do {
2029     IsModified = false;
2030     // Go over all selected nodes and try to fold them a bit more
2031     for (SDNode &Node : CurDAG->allnodes()) {
2032       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
2033       if (!MachineNode)
2034         continue;
2035 
2036       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
2037       if (ResNode != &Node) {
2038         ReplaceUses(&Node, ResNode);
2039         IsModified = true;
2040       }
2041     }
2042     CurDAG->RemoveDeadNodes();
2043   } while (IsModified);
2044 }
2045 
2046 void R600DAGToDAGISel::Select(SDNode *N) {
2047   unsigned int Opc = N->getOpcode();
2048   if (N->isMachineOpcode()) {
2049     N->setNodeId(-1);
2050     return;   // Already selected.
2051   }
2052 
2053   switch (Opc) {
2054   default: break;
2055   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
2056   case ISD::SCALAR_TO_VECTOR:
2057   case ISD::BUILD_VECTOR: {
2058     EVT VT = N->getValueType(0);
2059     unsigned NumVectorElts = VT.getVectorNumElements();
2060     unsigned RegClassID;
2061     // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
2062     // that adds a 128 bits reg copy when going through TwoAddressInstructions
2063     // pass. We want to avoid 128 bits copies as much as possible because they
2064     // can't be bundled by our scheduler.
2065     switch(NumVectorElts) {
2066     case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
2067     case 4:
2068       if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
2069         RegClassID = AMDGPU::R600_Reg128VerticalRegClassID;
2070       else
2071         RegClassID = AMDGPU::R600_Reg128RegClassID;
2072       break;
2073     default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
2074     }
2075     SelectBuildVector(N, RegClassID);
2076     return;
2077   }
2078   }
2079 
2080   SelectCode(N);
2081 }
2082 
2083 bool R600DAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
2084                                           SDValue &Offset) {
2085   ConstantSDNode *C;
2086   SDLoc DL(Addr);
2087 
2088   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
2089     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
2090     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2091   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
2092              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
2093     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
2094     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2095   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
2096             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
2097     Base = Addr.getOperand(0);
2098     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2099   } else {
2100     Base = Addr;
2101     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
2102   }
2103 
2104   return true;
2105 }
2106 
2107 bool R600DAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
2108                                           SDValue &Offset) {
2109   ConstantSDNode *IMMOffset;
2110 
2111   if (Addr.getOpcode() == ISD::ADD
2112       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
2113       && isInt<16>(IMMOffset->getZExtValue())) {
2114 
2115       Base = Addr.getOperand(0);
2116       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
2117                                          MVT::i32);
2118       return true;
2119   // If the pointer address is constant, we can move it to the offset field.
2120   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
2121              && isInt<16>(IMMOffset->getZExtValue())) {
2122     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
2123                                   SDLoc(CurDAG->getEntryNode()),
2124                                   AMDGPU::ZERO, MVT::i32);
2125     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
2126                                        MVT::i32);
2127     return true;
2128   }
2129 
2130   // Default case, no offset
2131   Base = Addr;
2132   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
2133   return true;
2134 }
2135