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