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