1 //===-- AMDGPUISelDAGToDAG.cpp - A dag to dag inst selector for AMDGPU ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //==-----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Defines an instruction selector for the AMDGPU target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPU.h"
15 #include "AMDGPUArgumentUsageInfo.h"
16 #include "AMDGPUISelLowering.h" // For AMDGPUISD
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPUPerfHintAnalysis.h"
19 #include "AMDGPURegisterInfo.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
22 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
23 #include "SIDefines.h"
24 #include "SIISelLowering.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Analysis/LegacyDivergenceAnalysis.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/InitializePasses.h"
43 #ifdef EXPENSIVE_CHECKS
44 #include "llvm/IR/Dominators.h"
45 #endif
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/MC/MCInstrDesc.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CodeGen.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MachineValueType.h"
52 #include "llvm/Support/MathExtras.h"
53 #include <cassert>
54 #include <cstdint>
55 #include <new>
56 #include <vector>
57 
58 #define DEBUG_TYPE "isel"
59 
60 using namespace llvm;
61 
62 namespace llvm {
63 
64 class R600InstrInfo;
65 
66 } // end namespace llvm
67 
68 //===----------------------------------------------------------------------===//
69 // Instruction Selector Implementation
70 //===----------------------------------------------------------------------===//
71 
72 namespace {
73 
74 static bool isNullConstantOrUndef(SDValue V) {
75   if (V.isUndef())
76     return true;
77 
78   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
79   return Const != nullptr && Const->isNullValue();
80 }
81 
82 static bool getConstantValue(SDValue N, uint32_t &Out) {
83   // This is only used for packed vectors, where ussing 0 for undef should
84   // always be good.
85   if (N.isUndef()) {
86     Out = 0;
87     return true;
88   }
89 
90   if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N)) {
91     Out = C->getAPIntValue().getSExtValue();
92     return true;
93   }
94 
95   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N)) {
96     Out = C->getValueAPF().bitcastToAPInt().getSExtValue();
97     return true;
98   }
99 
100   return false;
101 }
102 
103 // TODO: Handle undef as zero
104 static SDNode *packConstantV2I16(const SDNode *N, SelectionDAG &DAG,
105                                  bool Negate = false) {
106   assert(N->getOpcode() == ISD::BUILD_VECTOR && N->getNumOperands() == 2);
107   uint32_t LHSVal, RHSVal;
108   if (getConstantValue(N->getOperand(0), LHSVal) &&
109       getConstantValue(N->getOperand(1), RHSVal)) {
110     SDLoc SL(N);
111     uint32_t K = Negate ?
112       (-LHSVal & 0xffff) | (-RHSVal << 16) :
113       (LHSVal & 0xffff) | (RHSVal << 16);
114     return DAG.getMachineNode(AMDGPU::S_MOV_B32, SL, N->getValueType(0),
115                               DAG.getTargetConstant(K, SL, MVT::i32));
116   }
117 
118   return nullptr;
119 }
120 
121 static SDNode *packNegConstantV2I16(const SDNode *N, SelectionDAG &DAG) {
122   return packConstantV2I16(N, DAG, true);
123 }
124 
125 /// AMDGPU specific code to select AMDGPU machine instructions for
126 /// SelectionDAG operations.
127 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
128   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
129   // make the right decision when generating code for different targets.
130   const GCNSubtarget *Subtarget;
131 
132   // Default FP mode for the current function.
133   AMDGPU::SIModeRegisterDefaults Mode;
134 
135   bool EnableLateStructurizeCFG;
136 
137 public:
138   explicit AMDGPUDAGToDAGISel(TargetMachine *TM = nullptr,
139                               CodeGenOpt::Level OptLevel = CodeGenOpt::Default)
140     : SelectionDAGISel(*TM, OptLevel) {
141     EnableLateStructurizeCFG = AMDGPUTargetMachine::EnableLateStructurizeCFG;
142   }
143   ~AMDGPUDAGToDAGISel() override = default;
144 
145   void getAnalysisUsage(AnalysisUsage &AU) const override {
146     AU.addRequired<AMDGPUArgumentUsageInfo>();
147     AU.addRequired<LegacyDivergenceAnalysis>();
148 #ifdef EXPENSIVE_CHECKS
149     AU.addRequired<DominatorTreeWrapperPass>();
150     AU.addRequired<LoopInfoWrapperPass>();
151 #endif
152     SelectionDAGISel::getAnalysisUsage(AU);
153   }
154 
155   bool matchLoadD16FromBuildVector(SDNode *N) const;
156 
157   bool runOnMachineFunction(MachineFunction &MF) override;
158   void PreprocessISelDAG() override;
159   void Select(SDNode *N) override;
160   StringRef getPassName() const override;
161   void PostprocessISelDAG() override;
162 
163 protected:
164   void SelectBuildVector(SDNode *N, unsigned RegClassID);
165 
166 private:
167   std::pair<SDValue, SDValue> foldFrameIndex(SDValue N) const;
168   bool isNoNanSrc(SDValue N) const;
169   bool isInlineImmediate(const SDNode *N, bool Negated = false) const;
170   bool isNegInlineImmediate(const SDNode *N) const {
171     return isInlineImmediate(N, true);
172   }
173 
174   bool isVGPRImm(const SDNode *N) const;
175   bool isUniformLoad(const SDNode *N) const;
176   bool isUniformBr(const SDNode *N) const;
177 
178   MachineSDNode *buildSMovImm64(SDLoc &DL, uint64_t Val, EVT VT) const;
179 
180   SDNode *glueCopyToOp(SDNode *N, SDValue NewChain, SDValue Glue) const;
181   SDNode *glueCopyToM0(SDNode *N, SDValue Val) const;
182   SDNode *glueCopyToM0LDSInit(SDNode *N) const;
183 
184   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
185   virtual bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
186   virtual bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
187   bool isDSOffsetLegal(SDValue Base, unsigned Offset,
188                        unsigned OffsetBits) const;
189   bool SelectDS1Addr1Offset(SDValue Ptr, SDValue &Base, SDValue &Offset) const;
190   bool SelectDS64Bit4ByteAligned(SDValue Ptr, SDValue &Base, SDValue &Offset0,
191                                  SDValue &Offset1) const;
192   bool SelectMUBUF(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
193                    SDValue &SOffset, SDValue &Offset, SDValue &Offen,
194                    SDValue &Idxen, SDValue &Addr64, SDValue &GLC, SDValue &SLC,
195                    SDValue &TFE, SDValue &DLC, SDValue &SWZ) const;
196   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
197                          SDValue &SOffset, SDValue &Offset, SDValue &GLC,
198                          SDValue &SLC, SDValue &TFE, SDValue &DLC,
199                          SDValue &SWZ) const;
200   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
201                          SDValue &VAddr, SDValue &SOffset, SDValue &Offset,
202                          SDValue &SLC) const;
203   bool SelectMUBUFScratchOffen(SDNode *Parent,
204                                SDValue Addr, SDValue &RSrc, SDValue &VAddr,
205                                SDValue &SOffset, SDValue &ImmOffset) const;
206   bool SelectMUBUFScratchOffset(SDNode *Parent,
207                                 SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
208                                 SDValue &Offset) const;
209 
210   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &SOffset,
211                          SDValue &Offset, SDValue &GLC, SDValue &SLC,
212                          SDValue &TFE, SDValue &DLC, SDValue &SWZ) const;
213   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
214                          SDValue &Offset, SDValue &SLC) const;
215   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
216                          SDValue &Offset) const;
217 
218   template <bool IsSigned>
219   bool SelectFlatOffset(SDNode *N, SDValue Addr, SDValue &VAddr,
220                         SDValue &Offset, SDValue &SLC) const;
221   bool SelectFlatAtomic(SDNode *N, SDValue Addr, SDValue &VAddr,
222                         SDValue &Offset, SDValue &SLC) const;
223   bool SelectFlatAtomicSigned(SDNode *N, SDValue Addr, SDValue &VAddr,
224                               SDValue &Offset, SDValue &SLC) const;
225 
226   bool SelectSMRDOffset(SDValue ByteOffsetNode, SDValue &Offset,
227                         bool &Imm) const;
228   SDValue Expand32BitAddress(SDValue Addr) const;
229   bool SelectSMRD(SDValue Addr, SDValue &SBase, SDValue &Offset,
230                   bool &Imm) const;
231   bool SelectSMRDImm(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
232   bool SelectSMRDImm32(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
233   bool SelectSMRDSgpr(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
234   bool SelectSMRDBufferImm(SDValue Addr, SDValue &Offset) const;
235   bool SelectSMRDBufferImm32(SDValue Addr, SDValue &Offset) const;
236   bool SelectMOVRELOffset(SDValue Index, SDValue &Base, SDValue &Offset) const;
237 
238   bool SelectVOP3Mods_NNaN(SDValue In, SDValue &Src, SDValue &SrcMods) const;
239   bool SelectVOP3Mods_f32(SDValue In, SDValue &Src, SDValue &SrcMods) const;
240   bool SelectVOP3ModsImpl(SDValue In, SDValue &Src, unsigned &SrcMods) const;
241   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
242   bool SelectVOP3NoMods(SDValue In, SDValue &Src) const;
243   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
244                        SDValue &Clamp, SDValue &Omod) const;
245   bool SelectVOP3NoMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
246                          SDValue &Clamp, SDValue &Omod) const;
247 
248   bool SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src, SDValue &SrcMods,
249                                  SDValue &Clamp,
250                                  SDValue &Omod) const;
251 
252   bool SelectVOP3OMods(SDValue In, SDValue &Src,
253                        SDValue &Clamp, SDValue &Omod) const;
254 
255   bool SelectVOP3PMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
256   bool SelectVOP3PMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
257                         SDValue &Clamp) const;
258 
259   bool SelectVOP3OpSel(SDValue In, SDValue &Src, SDValue &SrcMods) const;
260   bool SelectVOP3OpSel0(SDValue In, SDValue &Src, SDValue &SrcMods,
261                         SDValue &Clamp) const;
262 
263   bool SelectVOP3OpSelMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
264   bool SelectVOP3OpSelMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
265                             SDValue &Clamp) const;
266   bool SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src, unsigned &Mods) const;
267   bool SelectVOP3PMadMixMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
268 
269   SDValue getHi16Elt(SDValue In) const;
270 
271   SDValue getMaterializedScalarImm32(int64_t Val, const SDLoc &DL) const;
272 
273   void SelectADD_SUB_I64(SDNode *N);
274   void SelectAddcSubb(SDNode *N);
275   void SelectUADDO_USUBO(SDNode *N);
276   void SelectDIV_SCALE(SDNode *N);
277   void SelectDIV_FMAS(SDNode *N);
278   void SelectMAD_64_32(SDNode *N);
279   void SelectFMA_W_CHAIN(SDNode *N);
280   void SelectFMUL_W_CHAIN(SDNode *N);
281 
282   SDNode *getS_BFE(unsigned Opcode, const SDLoc &DL, SDValue Val,
283                    uint32_t Offset, uint32_t Width);
284   void SelectS_BFEFromShifts(SDNode *N);
285   void SelectS_BFE(SDNode *N);
286   bool isCBranchSCC(const SDNode *N) const;
287   void SelectBRCOND(SDNode *N);
288   void SelectFMAD_FMA(SDNode *N);
289   void SelectATOMIC_CMP_SWAP(SDNode *N);
290   void SelectDSAppendConsume(SDNode *N, unsigned IntrID);
291   void SelectDS_GWS(SDNode *N, unsigned IntrID);
292   void SelectINTRINSIC_W_CHAIN(SDNode *N);
293   void SelectINTRINSIC_WO_CHAIN(SDNode *N);
294   void SelectINTRINSIC_VOID(SDNode *N);
295 
296 protected:
297   // Include the pieces autogenerated from the target description.
298 #include "AMDGPUGenDAGISel.inc"
299 };
300 
301 class R600DAGToDAGISel : public AMDGPUDAGToDAGISel {
302   const R600Subtarget *Subtarget;
303 
304   bool isConstantLoad(const MemSDNode *N, int cbID) const;
305   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
306   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
307                                        SDValue& Offset);
308 public:
309   explicit R600DAGToDAGISel(TargetMachine *TM, CodeGenOpt::Level OptLevel) :
310       AMDGPUDAGToDAGISel(TM, OptLevel) {}
311 
312   void Select(SDNode *N) override;
313 
314   bool SelectADDRIndirect(SDValue Addr, SDValue &Base,
315                           SDValue &Offset) override;
316   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
317                           SDValue &Offset) override;
318 
319   bool runOnMachineFunction(MachineFunction &MF) override;
320 
321   void PreprocessISelDAG() override {}
322 
323 protected:
324   // Include the pieces autogenerated from the target description.
325 #include "R600GenDAGISel.inc"
326 };
327 
328 static SDValue stripBitcast(SDValue Val) {
329   return Val.getOpcode() == ISD::BITCAST ? Val.getOperand(0) : Val;
330 }
331 
332 // Figure out if this is really an extract of the high 16-bits of a dword.
333 static bool isExtractHiElt(SDValue In, SDValue &Out) {
334   In = stripBitcast(In);
335   if (In.getOpcode() != ISD::TRUNCATE)
336     return false;
337 
338   SDValue Srl = In.getOperand(0);
339   if (Srl.getOpcode() == ISD::SRL) {
340     if (ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
341       if (ShiftAmt->getZExtValue() == 16) {
342         Out = stripBitcast(Srl.getOperand(0));
343         return true;
344       }
345     }
346   }
347 
348   return false;
349 }
350 
351 // Look through operations that obscure just looking at the low 16-bits of the
352 // same register.
353 static SDValue stripExtractLoElt(SDValue In) {
354   if (In.getOpcode() == ISD::TRUNCATE) {
355     SDValue Src = In.getOperand(0);
356     if (Src.getValueType().getSizeInBits() == 32)
357       return stripBitcast(Src);
358   }
359 
360   return In;
361 }
362 
363 }  // end anonymous namespace
364 
365 INITIALIZE_PASS_BEGIN(AMDGPUDAGToDAGISel, "amdgpu-isel",
366                       "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
367 INITIALIZE_PASS_DEPENDENCY(AMDGPUArgumentUsageInfo)
368 INITIALIZE_PASS_DEPENDENCY(AMDGPUPerfHintAnalysis)
369 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
370 #ifdef EXPENSIVE_CHECKS
371 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
372 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
373 #endif
374 INITIALIZE_PASS_END(AMDGPUDAGToDAGISel, "amdgpu-isel",
375                     "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
376 
377 /// This pass converts a legalized DAG into a AMDGPU-specific
378 // DAG, ready for instruction scheduling.
379 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine *TM,
380                                         CodeGenOpt::Level OptLevel) {
381   return new AMDGPUDAGToDAGISel(TM, OptLevel);
382 }
383 
384 /// This pass converts a legalized DAG into a R600-specific
385 // DAG, ready for instruction scheduling.
386 FunctionPass *llvm::createR600ISelDag(TargetMachine *TM,
387                                       CodeGenOpt::Level OptLevel) {
388   return new R600DAGToDAGISel(TM, OptLevel);
389 }
390 
391 bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
392 #ifdef EXPENSIVE_CHECKS
393   DominatorTree & DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
394   LoopInfo * LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
395   for (auto &L : LI->getLoopsInPreorder()) {
396     assert(L->isLCSSAForm(DT));
397   }
398 #endif
399   Subtarget = &MF.getSubtarget<GCNSubtarget>();
400   Mode = AMDGPU::SIModeRegisterDefaults(MF.getFunction(), *Subtarget);
401   return SelectionDAGISel::runOnMachineFunction(MF);
402 }
403 
404 bool AMDGPUDAGToDAGISel::matchLoadD16FromBuildVector(SDNode *N) const {
405   assert(Subtarget->d16PreservesUnusedBits());
406   MVT VT = N->getValueType(0).getSimpleVT();
407   if (VT != MVT::v2i16 && VT != MVT::v2f16)
408     return false;
409 
410   SDValue Lo = N->getOperand(0);
411   SDValue Hi = N->getOperand(1);
412 
413   LoadSDNode *LdHi = dyn_cast<LoadSDNode>(stripBitcast(Hi));
414 
415   // build_vector lo, (load ptr) -> load_d16_hi ptr, lo
416   // build_vector lo, (zextload ptr from i8) -> load_d16_hi_u8 ptr, lo
417   // build_vector lo, (sextload ptr from i8) -> load_d16_hi_i8 ptr, lo
418 
419   // Need to check for possible indirect dependencies on the other half of the
420   // vector to avoid introducing a cycle.
421   if (LdHi && Hi.hasOneUse() && !LdHi->isPredecessorOf(Lo.getNode())) {
422     SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
423 
424     SDValue TiedIn = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Lo);
425     SDValue Ops[] = {
426       LdHi->getChain(), LdHi->getBasePtr(), TiedIn
427     };
428 
429     unsigned LoadOp = AMDGPUISD::LOAD_D16_HI;
430     if (LdHi->getMemoryVT() == MVT::i8) {
431       LoadOp = LdHi->getExtensionType() == ISD::SEXTLOAD ?
432         AMDGPUISD::LOAD_D16_HI_I8 : AMDGPUISD::LOAD_D16_HI_U8;
433     } else {
434       assert(LdHi->getMemoryVT() == MVT::i16);
435     }
436 
437     SDValue NewLoadHi =
438       CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdHi), VTList,
439                                   Ops, LdHi->getMemoryVT(),
440                                   LdHi->getMemOperand());
441 
442     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadHi);
443     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdHi, 1), NewLoadHi.getValue(1));
444     return true;
445   }
446 
447   // build_vector (load ptr), hi -> load_d16_lo ptr, hi
448   // build_vector (zextload ptr from i8), hi -> load_d16_lo_u8 ptr, hi
449   // build_vector (sextload ptr from i8), hi -> load_d16_lo_i8 ptr, hi
450   LoadSDNode *LdLo = dyn_cast<LoadSDNode>(stripBitcast(Lo));
451   if (LdLo && Lo.hasOneUse()) {
452     SDValue TiedIn = getHi16Elt(Hi);
453     if (!TiedIn || LdLo->isPredecessorOf(TiedIn.getNode()))
454       return false;
455 
456     SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
457     unsigned LoadOp = AMDGPUISD::LOAD_D16_LO;
458     if (LdLo->getMemoryVT() == MVT::i8) {
459       LoadOp = LdLo->getExtensionType() == ISD::SEXTLOAD ?
460         AMDGPUISD::LOAD_D16_LO_I8 : AMDGPUISD::LOAD_D16_LO_U8;
461     } else {
462       assert(LdLo->getMemoryVT() == MVT::i16);
463     }
464 
465     TiedIn = CurDAG->getNode(ISD::BITCAST, SDLoc(N), VT, TiedIn);
466 
467     SDValue Ops[] = {
468       LdLo->getChain(), LdLo->getBasePtr(), TiedIn
469     };
470 
471     SDValue NewLoadLo =
472       CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdLo), VTList,
473                                   Ops, LdLo->getMemoryVT(),
474                                   LdLo->getMemOperand());
475 
476     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadLo);
477     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdLo, 1), NewLoadLo.getValue(1));
478     return true;
479   }
480 
481   return false;
482 }
483 
484 void AMDGPUDAGToDAGISel::PreprocessISelDAG() {
485   if (!Subtarget->d16PreservesUnusedBits())
486     return;
487 
488   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
489 
490   bool MadeChange = false;
491   while (Position != CurDAG->allnodes_begin()) {
492     SDNode *N = &*--Position;
493     if (N->use_empty())
494       continue;
495 
496     switch (N->getOpcode()) {
497     case ISD::BUILD_VECTOR:
498       MadeChange |= matchLoadD16FromBuildVector(N);
499       break;
500     default:
501       break;
502     }
503   }
504 
505   if (MadeChange) {
506     CurDAG->RemoveDeadNodes();
507     LLVM_DEBUG(dbgs() << "After PreProcess:\n";
508                CurDAG->dump(););
509   }
510 }
511 
512 bool AMDGPUDAGToDAGISel::isNoNanSrc(SDValue N) const {
513   if (TM.Options.NoNaNsFPMath)
514     return true;
515 
516   // TODO: Move into isKnownNeverNaN
517   if (N->getFlags().isDefined())
518     return N->getFlags().hasNoNaNs();
519 
520   return CurDAG->isKnownNeverNaN(N);
521 }
522 
523 bool AMDGPUDAGToDAGISel::isInlineImmediate(const SDNode *N,
524                                            bool Negated) const {
525   if (N->isUndef())
526     return true;
527 
528   const SIInstrInfo *TII = Subtarget->getInstrInfo();
529   if (Negated) {
530     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N))
531       return TII->isInlineConstant(-C->getAPIntValue());
532 
533     if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N))
534       return TII->isInlineConstant(-C->getValueAPF().bitcastToAPInt());
535 
536   } else {
537     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N))
538       return TII->isInlineConstant(C->getAPIntValue());
539 
540     if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N))
541       return TII->isInlineConstant(C->getValueAPF().bitcastToAPInt());
542   }
543 
544   return false;
545 }
546 
547 /// Determine the register class for \p OpNo
548 /// \returns The register class of the virtual register that will be used for
549 /// the given operand number \OpNo or NULL if the register class cannot be
550 /// determined.
551 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
552                                                           unsigned OpNo) const {
553   if (!N->isMachineOpcode()) {
554     if (N->getOpcode() == ISD::CopyToReg) {
555       unsigned Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
556       if (Register::isVirtualRegister(Reg)) {
557         MachineRegisterInfo &MRI = CurDAG->getMachineFunction().getRegInfo();
558         return MRI.getRegClass(Reg);
559       }
560 
561       const SIRegisterInfo *TRI
562         = static_cast<const GCNSubtarget *>(Subtarget)->getRegisterInfo();
563       return TRI->getPhysRegClass(Reg);
564     }
565 
566     return nullptr;
567   }
568 
569   switch (N->getMachineOpcode()) {
570   default: {
571     const MCInstrDesc &Desc =
572         Subtarget->getInstrInfo()->get(N->getMachineOpcode());
573     unsigned OpIdx = Desc.getNumDefs() + OpNo;
574     if (OpIdx >= Desc.getNumOperands())
575       return nullptr;
576     int RegClass = Desc.OpInfo[OpIdx].RegClass;
577     if (RegClass == -1)
578       return nullptr;
579 
580     return Subtarget->getRegisterInfo()->getRegClass(RegClass);
581   }
582   case AMDGPU::REG_SEQUENCE: {
583     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
584     const TargetRegisterClass *SuperRC =
585         Subtarget->getRegisterInfo()->getRegClass(RCID);
586 
587     SDValue SubRegOp = N->getOperand(OpNo + 1);
588     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
589     return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
590                                                               SubRegIdx);
591   }
592   }
593 }
594 
595 SDNode *AMDGPUDAGToDAGISel::glueCopyToOp(SDNode *N, SDValue NewChain,
596                                          SDValue Glue) const {
597   SmallVector <SDValue, 8> Ops;
598   Ops.push_back(NewChain); // Replace the chain.
599   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
600     Ops.push_back(N->getOperand(i));
601 
602   Ops.push_back(Glue);
603   return CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), Ops);
604 }
605 
606 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N, SDValue Val) const {
607   const SITargetLowering& Lowering =
608     *static_cast<const SITargetLowering*>(getTargetLowering());
609 
610   assert(N->getOperand(0).getValueType() == MVT::Other && "Expected chain");
611 
612   SDValue M0 = Lowering.copyToM0(*CurDAG, N->getOperand(0), SDLoc(N), Val);
613   return glueCopyToOp(N, M0, M0.getValue(1));
614 }
615 
616 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0LDSInit(SDNode *N) const {
617   unsigned AS = cast<MemSDNode>(N)->getAddressSpace();
618   if (AS == AMDGPUAS::LOCAL_ADDRESS) {
619     if (Subtarget->ldsRequiresM0Init())
620       return glueCopyToM0(N, CurDAG->getTargetConstant(-1, SDLoc(N), MVT::i32));
621   } else if (AS == AMDGPUAS::REGION_ADDRESS) {
622     MachineFunction &MF = CurDAG->getMachineFunction();
623     unsigned Value = MF.getInfo<SIMachineFunctionInfo>()->getGDSSize();
624     return
625         glueCopyToM0(N, CurDAG->getTargetConstant(Value, SDLoc(N), MVT::i32));
626   }
627   return N;
628 }
629 
630 MachineSDNode *AMDGPUDAGToDAGISel::buildSMovImm64(SDLoc &DL, uint64_t Imm,
631                                                   EVT VT) const {
632   SDNode *Lo = CurDAG->getMachineNode(
633       AMDGPU::S_MOV_B32, DL, MVT::i32,
634       CurDAG->getTargetConstant(Imm & 0xFFFFFFFF, DL, MVT::i32));
635   SDNode *Hi =
636       CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
637                              CurDAG->getTargetConstant(Imm >> 32, DL, MVT::i32));
638   const SDValue Ops[] = {
639       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
640       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
641       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
642 
643   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, VT, Ops);
644 }
645 
646 static unsigned selectSGPRVectorRegClassID(unsigned NumVectorElts) {
647   switch (NumVectorElts) {
648   case 1:
649     return AMDGPU::SReg_32RegClassID;
650   case 2:
651     return AMDGPU::SReg_64RegClassID;
652   case 3:
653     return AMDGPU::SGPR_96RegClassID;
654   case 4:
655     return AMDGPU::SGPR_128RegClassID;
656   case 5:
657     return AMDGPU::SGPR_160RegClassID;
658   case 8:
659     return AMDGPU::SReg_256RegClassID;
660   case 16:
661     return AMDGPU::SReg_512RegClassID;
662   case 32:
663     return AMDGPU::SReg_1024RegClassID;
664   }
665 
666   llvm_unreachable("invalid vector size");
667 }
668 
669 void AMDGPUDAGToDAGISel::SelectBuildVector(SDNode *N, unsigned RegClassID) {
670   EVT VT = N->getValueType(0);
671   unsigned NumVectorElts = VT.getVectorNumElements();
672   EVT EltVT = VT.getVectorElementType();
673   SDLoc DL(N);
674   SDValue RegClass = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
675 
676   if (NumVectorElts == 1) {
677     CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT, N->getOperand(0),
678                          RegClass);
679     return;
680   }
681 
682   assert(NumVectorElts <= 32 && "Vectors with more than 32 elements not "
683                                   "supported yet");
684   // 32 = Max Num Vector Elements
685   // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
686   // 1 = Vector Register Class
687   SmallVector<SDValue, 32 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
688 
689   RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
690   bool IsRegSeq = true;
691   unsigned NOps = N->getNumOperands();
692   for (unsigned i = 0; i < NOps; i++) {
693     // XXX: Why is this here?
694     if (isa<RegisterSDNode>(N->getOperand(i))) {
695       IsRegSeq = false;
696       break;
697     }
698     unsigned Sub = AMDGPURegisterInfo::getSubRegFromChannel(i);
699     RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
700     RegSeqArgs[1 + (2 * i) + 1] = CurDAG->getTargetConstant(Sub, DL, MVT::i32);
701   }
702   if (NOps != NumVectorElts) {
703     // Fill in the missing undef elements if this was a scalar_to_vector.
704     assert(N->getOpcode() == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
705     MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
706                                                    DL, EltVT);
707     for (unsigned i = NOps; i < NumVectorElts; ++i) {
708       unsigned Sub = AMDGPURegisterInfo::getSubRegFromChannel(i);
709       RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
710       RegSeqArgs[1 + (2 * i) + 1] =
711           CurDAG->getTargetConstant(Sub, DL, MVT::i32);
712     }
713   }
714 
715   if (!IsRegSeq)
716     SelectCode(N);
717   CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(), RegSeqArgs);
718 }
719 
720 void AMDGPUDAGToDAGISel::Select(SDNode *N) {
721   unsigned int Opc = N->getOpcode();
722   if (N->isMachineOpcode()) {
723     N->setNodeId(-1);
724     return;   // Already selected.
725   }
726 
727   // isa<MemSDNode> almost works but is slightly too permissive for some DS
728   // intrinsics.
729   if (Opc == ISD::LOAD || Opc == ISD::STORE || isa<AtomicSDNode>(N) ||
730       (Opc == AMDGPUISD::ATOMIC_INC || Opc == AMDGPUISD::ATOMIC_DEC ||
731        Opc == ISD::ATOMIC_LOAD_FADD ||
732        Opc == AMDGPUISD::ATOMIC_LOAD_FMIN ||
733        Opc == AMDGPUISD::ATOMIC_LOAD_FMAX)) {
734     N = glueCopyToM0LDSInit(N);
735     SelectCode(N);
736     return;
737   }
738 
739   switch (Opc) {
740   default:
741     break;
742   // We are selecting i64 ADD here instead of custom lower it during
743   // DAG legalization, so we can fold some i64 ADDs used for address
744   // calculation into the LOAD and STORE instructions.
745   case ISD::ADDC:
746   case ISD::ADDE:
747   case ISD::SUBC:
748   case ISD::SUBE: {
749     if (N->getValueType(0) != MVT::i64)
750       break;
751 
752     SelectADD_SUB_I64(N);
753     return;
754   }
755   case ISD::ADDCARRY:
756   case ISD::SUBCARRY:
757     if (N->getValueType(0) != MVT::i32)
758       break;
759 
760     SelectAddcSubb(N);
761     return;
762   case ISD::UADDO:
763   case ISD::USUBO: {
764     SelectUADDO_USUBO(N);
765     return;
766   }
767   case AMDGPUISD::FMUL_W_CHAIN: {
768     SelectFMUL_W_CHAIN(N);
769     return;
770   }
771   case AMDGPUISD::FMA_W_CHAIN: {
772     SelectFMA_W_CHAIN(N);
773     return;
774   }
775 
776   case ISD::SCALAR_TO_VECTOR:
777   case ISD::BUILD_VECTOR: {
778     EVT VT = N->getValueType(0);
779     unsigned NumVectorElts = VT.getVectorNumElements();
780     if (VT.getScalarSizeInBits() == 16) {
781       if (Opc == ISD::BUILD_VECTOR && NumVectorElts == 2) {
782         if (SDNode *Packed = packConstantV2I16(N, *CurDAG)) {
783           ReplaceNode(N, Packed);
784           return;
785         }
786       }
787 
788       break;
789     }
790 
791     assert(VT.getVectorElementType().bitsEq(MVT::i32));
792     unsigned RegClassID = selectSGPRVectorRegClassID(NumVectorElts);
793     SelectBuildVector(N, RegClassID);
794     return;
795   }
796   case ISD::BUILD_PAIR: {
797     SDValue RC, SubReg0, SubReg1;
798     SDLoc DL(N);
799     if (N->getValueType(0) == MVT::i128) {
800       RC = CurDAG->getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32);
801       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32);
802       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32);
803     } else if (N->getValueType(0) == MVT::i64) {
804       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32);
805       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
806       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
807     } else {
808       llvm_unreachable("Unhandled value type for BUILD_PAIR");
809     }
810     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
811                             N->getOperand(1), SubReg1 };
812     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
813                                           N->getValueType(0), Ops));
814     return;
815   }
816 
817   case ISD::Constant:
818   case ISD::ConstantFP: {
819     if (N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
820       break;
821 
822     uint64_t Imm;
823     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
824       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
825     else {
826       ConstantSDNode *C = cast<ConstantSDNode>(N);
827       Imm = C->getZExtValue();
828     }
829 
830     SDLoc DL(N);
831     ReplaceNode(N, buildSMovImm64(DL, Imm, N->getValueType(0)));
832     return;
833   }
834   case AMDGPUISD::BFE_I32:
835   case AMDGPUISD::BFE_U32: {
836     // There is a scalar version available, but unlike the vector version which
837     // has a separate operand for the offset and width, the scalar version packs
838     // the width and offset into a single operand. Try to move to the scalar
839     // version if the offsets are constant, so that we can try to keep extended
840     // loads of kernel arguments in SGPRs.
841 
842     // TODO: Technically we could try to pattern match scalar bitshifts of
843     // dynamic values, but it's probably not useful.
844     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
845     if (!Offset)
846       break;
847 
848     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
849     if (!Width)
850       break;
851 
852     bool Signed = Opc == AMDGPUISD::BFE_I32;
853 
854     uint32_t OffsetVal = Offset->getZExtValue();
855     uint32_t WidthVal = Width->getZExtValue();
856 
857     ReplaceNode(N, getS_BFE(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32,
858                             SDLoc(N), N->getOperand(0), OffsetVal, WidthVal));
859     return;
860   }
861   case AMDGPUISD::DIV_SCALE: {
862     SelectDIV_SCALE(N);
863     return;
864   }
865   case AMDGPUISD::DIV_FMAS: {
866     SelectDIV_FMAS(N);
867     return;
868   }
869   case AMDGPUISD::MAD_I64_I32:
870   case AMDGPUISD::MAD_U64_U32: {
871     SelectMAD_64_32(N);
872     return;
873   }
874   case ISD::CopyToReg: {
875     const SITargetLowering& Lowering =
876       *static_cast<const SITargetLowering*>(getTargetLowering());
877     N = Lowering.legalizeTargetIndependentNode(N, *CurDAG);
878     break;
879   }
880   case ISD::AND:
881   case ISD::SRL:
882   case ISD::SRA:
883   case ISD::SIGN_EXTEND_INREG:
884     if (N->getValueType(0) != MVT::i32)
885       break;
886 
887     SelectS_BFE(N);
888     return;
889   case ISD::BRCOND:
890     SelectBRCOND(N);
891     return;
892   case ISD::FMAD:
893   case ISD::FMA:
894     SelectFMAD_FMA(N);
895     return;
896   case AMDGPUISD::ATOMIC_CMP_SWAP:
897     SelectATOMIC_CMP_SWAP(N);
898     return;
899   case AMDGPUISD::CVT_PKRTZ_F16_F32:
900   case AMDGPUISD::CVT_PKNORM_I16_F32:
901   case AMDGPUISD::CVT_PKNORM_U16_F32:
902   case AMDGPUISD::CVT_PK_U16_U32:
903   case AMDGPUISD::CVT_PK_I16_I32: {
904     // Hack around using a legal type if f16 is illegal.
905     if (N->getValueType(0) == MVT::i32) {
906       MVT NewVT = Opc == AMDGPUISD::CVT_PKRTZ_F16_F32 ? MVT::v2f16 : MVT::v2i16;
907       N = CurDAG->MorphNodeTo(N, N->getOpcode(), CurDAG->getVTList(NewVT),
908                               { N->getOperand(0), N->getOperand(1) });
909       SelectCode(N);
910       return;
911     }
912 
913     break;
914   }
915   case ISD::INTRINSIC_W_CHAIN: {
916     SelectINTRINSIC_W_CHAIN(N);
917     return;
918   }
919   case ISD::INTRINSIC_WO_CHAIN: {
920     SelectINTRINSIC_WO_CHAIN(N);
921     return;
922   }
923   case ISD::INTRINSIC_VOID: {
924     SelectINTRINSIC_VOID(N);
925     return;
926   }
927   }
928 
929   SelectCode(N);
930 }
931 
932 bool AMDGPUDAGToDAGISel::isUniformBr(const SDNode *N) const {
933   const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
934   const Instruction *Term = BB->getTerminator();
935   return Term->getMetadata("amdgpu.uniform") ||
936          Term->getMetadata("structurizecfg.uniform");
937 }
938 
939 StringRef AMDGPUDAGToDAGISel::getPassName() const {
940   return "AMDGPU DAG->DAG Pattern Instruction Selection";
941 }
942 
943 //===----------------------------------------------------------------------===//
944 // Complex Patterns
945 //===----------------------------------------------------------------------===//
946 
947 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
948                                             SDValue &Offset) {
949   return false;
950 }
951 
952 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
953                                             SDValue &Offset) {
954   ConstantSDNode *C;
955   SDLoc DL(Addr);
956 
957   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
958     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
959     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
960   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
961              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
962     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
963     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
964   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
965             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
966     Base = Addr.getOperand(0);
967     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
968   } else {
969     Base = Addr;
970     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
971   }
972 
973   return true;
974 }
975 
976 SDValue AMDGPUDAGToDAGISel::getMaterializedScalarImm32(int64_t Val,
977                                                        const SDLoc &DL) const {
978   SDNode *Mov = CurDAG->getMachineNode(
979     AMDGPU::S_MOV_B32, DL, MVT::i32,
980     CurDAG->getTargetConstant(Val, DL, MVT::i32));
981   return SDValue(Mov, 0);
982 }
983 
984 // FIXME: Should only handle addcarry/subcarry
985 void AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
986   SDLoc DL(N);
987   SDValue LHS = N->getOperand(0);
988   SDValue RHS = N->getOperand(1);
989 
990   unsigned Opcode = N->getOpcode();
991   bool ConsumeCarry = (Opcode == ISD::ADDE || Opcode == ISD::SUBE);
992   bool ProduceCarry =
993       ConsumeCarry || Opcode == ISD::ADDC || Opcode == ISD::SUBC;
994   bool IsAdd = Opcode == ISD::ADD || Opcode == ISD::ADDC || Opcode == ISD::ADDE;
995 
996   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
997   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
998 
999   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1000                                        DL, MVT::i32, LHS, Sub0);
1001   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1002                                        DL, MVT::i32, LHS, Sub1);
1003 
1004   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1005                                        DL, MVT::i32, RHS, Sub0);
1006   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1007                                        DL, MVT::i32, RHS, Sub1);
1008 
1009   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
1010 
1011   unsigned Opc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
1012   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
1013 
1014   SDNode *AddLo;
1015   if (!ConsumeCarry) {
1016     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
1017     AddLo = CurDAG->getMachineNode(Opc, DL, VTList, Args);
1018   } else {
1019     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(2) };
1020     AddLo = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
1021   }
1022   SDValue AddHiArgs[] = {
1023     SDValue(Hi0, 0),
1024     SDValue(Hi1, 0),
1025     SDValue(AddLo, 1)
1026   };
1027   SDNode *AddHi = CurDAG->getMachineNode(CarryOpc, DL, VTList, AddHiArgs);
1028 
1029   SDValue RegSequenceArgs[] = {
1030     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
1031     SDValue(AddLo,0),
1032     Sub0,
1033     SDValue(AddHi,0),
1034     Sub1,
1035   };
1036   SDNode *RegSequence = CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1037                                                MVT::i64, RegSequenceArgs);
1038 
1039   if (ProduceCarry) {
1040     // Replace the carry-use
1041     ReplaceUses(SDValue(N, 1), SDValue(AddHi, 1));
1042   }
1043 
1044   // Replace the remaining uses.
1045   ReplaceNode(N, RegSequence);
1046 }
1047 
1048 void AMDGPUDAGToDAGISel::SelectAddcSubb(SDNode *N) {
1049   SDLoc DL(N);
1050   SDValue LHS = N->getOperand(0);
1051   SDValue RHS = N->getOperand(1);
1052   SDValue CI = N->getOperand(2);
1053 
1054   unsigned Opc = N->getOpcode() == ISD::ADDCARRY ? AMDGPU::V_ADDC_U32_e64
1055                                                  : AMDGPU::V_SUBB_U32_e64;
1056   CurDAG->SelectNodeTo(
1057       N, Opc, N->getVTList(),
1058       {LHS, RHS, CI, CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
1059 }
1060 
1061 void AMDGPUDAGToDAGISel::SelectUADDO_USUBO(SDNode *N) {
1062   // The name of the opcodes are misleading. v_add_i32/v_sub_i32 have unsigned
1063   // carry out despite the _i32 name. These were renamed in VI to _U32.
1064   // FIXME: We should probably rename the opcodes here.
1065   unsigned Opc = N->getOpcode() == ISD::UADDO ?
1066     AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
1067 
1068   CurDAG->SelectNodeTo(
1069       N, Opc, N->getVTList(),
1070       {N->getOperand(0), N->getOperand(1),
1071        CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
1072 }
1073 
1074 void AMDGPUDAGToDAGISel::SelectFMA_W_CHAIN(SDNode *N) {
1075   SDLoc SL(N);
1076   //  src0_modifiers, src0,  src1_modifiers, src1, src2_modifiers, src2, clamp, omod
1077   SDValue Ops[10];
1078 
1079   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[6], Ops[7]);
1080   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
1081   SelectVOP3Mods(N->getOperand(3), Ops[5], Ops[4]);
1082   Ops[8] = N->getOperand(0);
1083   Ops[9] = N->getOperand(4);
1084 
1085   CurDAG->SelectNodeTo(N, AMDGPU::V_FMA_F32, N->getVTList(), Ops);
1086 }
1087 
1088 void AMDGPUDAGToDAGISel::SelectFMUL_W_CHAIN(SDNode *N) {
1089   SDLoc SL(N);
1090   //    src0_modifiers, src0,  src1_modifiers, src1, clamp, omod
1091   SDValue Ops[8];
1092 
1093   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[4], Ops[5]);
1094   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
1095   Ops[6] = N->getOperand(0);
1096   Ops[7] = N->getOperand(3);
1097 
1098   CurDAG->SelectNodeTo(N, AMDGPU::V_MUL_F32_e64, N->getVTList(), Ops);
1099 }
1100 
1101 // We need to handle this here because tablegen doesn't support matching
1102 // instructions with multiple outputs.
1103 void AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
1104   SDLoc SL(N);
1105   EVT VT = N->getValueType(0);
1106 
1107   assert(VT == MVT::f32 || VT == MVT::f64);
1108 
1109   unsigned Opc
1110     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
1111 
1112   SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) };
1113   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1114 }
1115 
1116 void AMDGPUDAGToDAGISel::SelectDIV_FMAS(SDNode *N) {
1117   const GCNSubtarget *ST = static_cast<const GCNSubtarget *>(Subtarget);
1118   const SIRegisterInfo *TRI = ST->getRegisterInfo();
1119 
1120   SDLoc SL(N);
1121   EVT VT = N->getValueType(0);
1122 
1123   assert(VT == MVT::f32 || VT == MVT::f64);
1124 
1125   unsigned Opc
1126     = (VT == MVT::f64) ? AMDGPU::V_DIV_FMAS_F64 : AMDGPU::V_DIV_FMAS_F32;
1127 
1128   SDValue CarryIn = N->getOperand(3);
1129   // V_DIV_FMAS implicitly reads VCC.
1130   SDValue VCC = CurDAG->getCopyToReg(CurDAG->getEntryNode(), SL,
1131                                      TRI->getVCC(), CarryIn, SDValue());
1132 
1133   SDValue Ops[10];
1134 
1135   SelectVOP3Mods0(N->getOperand(0), Ops[1], Ops[0], Ops[6], Ops[7]);
1136   SelectVOP3Mods(N->getOperand(1), Ops[3], Ops[2]);
1137   SelectVOP3Mods(N->getOperand(2), Ops[5], Ops[4]);
1138 
1139   Ops[8] = VCC;
1140   Ops[9] = VCC.getValue(1);
1141 
1142   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1143 }
1144 
1145 // We need to handle this here because tablegen doesn't support matching
1146 // instructions with multiple outputs.
1147 void AMDGPUDAGToDAGISel::SelectMAD_64_32(SDNode *N) {
1148   SDLoc SL(N);
1149   bool Signed = N->getOpcode() == AMDGPUISD::MAD_I64_I32;
1150   unsigned Opc = Signed ? AMDGPU::V_MAD_I64_I32 : AMDGPU::V_MAD_U64_U32;
1151 
1152   SDValue Clamp = CurDAG->getTargetConstant(0, SL, MVT::i1);
1153   SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
1154                     Clamp };
1155   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1156 }
1157 
1158 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(SDValue Base, unsigned Offset,
1159                                          unsigned OffsetBits) const {
1160   if ((OffsetBits == 16 && !isUInt<16>(Offset)) ||
1161       (OffsetBits == 8 && !isUInt<8>(Offset)))
1162     return false;
1163 
1164   if (Subtarget->hasUsableDSOffset() ||
1165       Subtarget->unsafeDSOffsetFoldingEnabled())
1166     return true;
1167 
1168   // On Southern Islands instruction with a negative base value and an offset
1169   // don't seem to work.
1170   return CurDAG->SignBitIsZero(Base);
1171 }
1172 
1173 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
1174                                               SDValue &Offset) const {
1175   SDLoc DL(Addr);
1176   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1177     SDValue N0 = Addr.getOperand(0);
1178     SDValue N1 = Addr.getOperand(1);
1179     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1180     if (isDSOffsetLegal(N0, C1->getSExtValue(), 16)) {
1181       // (add n0, c0)
1182       Base = N0;
1183       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1184       return true;
1185     }
1186   } else if (Addr.getOpcode() == ISD::SUB) {
1187     // sub C, x -> add (sub 0, x), C
1188     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1189       int64_t ByteOffset = C->getSExtValue();
1190       if (isUInt<16>(ByteOffset)) {
1191         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1192 
1193         // XXX - This is kind of hacky. Create a dummy sub node so we can check
1194         // the known bits in isDSOffsetLegal. We need to emit the selected node
1195         // here, so this is thrown away.
1196         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
1197                                       Zero, Addr.getOperand(1));
1198 
1199         if (isDSOffsetLegal(Sub, ByteOffset, 16)) {
1200           SmallVector<SDValue, 3> Opnds;
1201           Opnds.push_back(Zero);
1202           Opnds.push_back(Addr.getOperand(1));
1203 
1204           // FIXME: Select to VOP3 version for with-carry.
1205           unsigned SubOp = AMDGPU::V_SUB_I32_e32;
1206           if (Subtarget->hasAddNoCarry()) {
1207             SubOp = AMDGPU::V_SUB_U32_e64;
1208             Opnds.push_back(
1209                 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1210           }
1211 
1212           MachineSDNode *MachineSub =
1213               CurDAG->getMachineNode(SubOp, DL, MVT::i32, Opnds);
1214 
1215           Base = SDValue(MachineSub, 0);
1216           Offset = CurDAG->getTargetConstant(ByteOffset, DL, MVT::i16);
1217           return true;
1218         }
1219       }
1220     }
1221   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1222     // If we have a constant address, prefer to put the constant into the
1223     // offset. This can save moves to load the constant address since multiple
1224     // operations can share the zero base address register, and enables merging
1225     // into read2 / write2 instructions.
1226 
1227     SDLoc DL(Addr);
1228 
1229     if (isUInt<16>(CAddr->getZExtValue())) {
1230       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1231       MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1232                                  DL, MVT::i32, Zero);
1233       Base = SDValue(MovZero, 0);
1234       Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1235       return true;
1236     }
1237   }
1238 
1239   // default case
1240   Base = Addr;
1241   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i16);
1242   return true;
1243 }
1244 
1245 // TODO: If offset is too big, put low 16-bit into offset.
1246 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
1247                                                    SDValue &Offset0,
1248                                                    SDValue &Offset1) const {
1249   SDLoc DL(Addr);
1250 
1251   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1252     SDValue N0 = Addr.getOperand(0);
1253     SDValue N1 = Addr.getOperand(1);
1254     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1255     unsigned DWordOffset0 = C1->getZExtValue() / 4;
1256     unsigned DWordOffset1 = DWordOffset0 + 1;
1257     // (add n0, c0)
1258     if (isDSOffsetLegal(N0, DWordOffset1, 8)) {
1259       Base = N0;
1260       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
1261       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
1262       return true;
1263     }
1264   } else if (Addr.getOpcode() == ISD::SUB) {
1265     // sub C, x -> add (sub 0, x), C
1266     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1267       unsigned DWordOffset0 = C->getZExtValue() / 4;
1268       unsigned DWordOffset1 = DWordOffset0 + 1;
1269 
1270       if (isUInt<8>(DWordOffset0)) {
1271         SDLoc DL(Addr);
1272         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1273 
1274         // XXX - This is kind of hacky. Create a dummy sub node so we can check
1275         // the known bits in isDSOffsetLegal. We need to emit the selected node
1276         // here, so this is thrown away.
1277         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
1278                                       Zero, Addr.getOperand(1));
1279 
1280         if (isDSOffsetLegal(Sub, DWordOffset1, 8)) {
1281           SmallVector<SDValue, 3> Opnds;
1282           Opnds.push_back(Zero);
1283           Opnds.push_back(Addr.getOperand(1));
1284           unsigned SubOp = AMDGPU::V_SUB_I32_e32;
1285           if (Subtarget->hasAddNoCarry()) {
1286             SubOp = AMDGPU::V_SUB_U32_e64;
1287             Opnds.push_back(
1288                 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1289           }
1290 
1291           MachineSDNode *MachineSub
1292             = CurDAG->getMachineNode(SubOp, DL, MVT::i32, Opnds);
1293 
1294           Base = SDValue(MachineSub, 0);
1295           Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
1296           Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
1297           return true;
1298         }
1299       }
1300     }
1301   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1302     unsigned DWordOffset0 = CAddr->getZExtValue() / 4;
1303     unsigned DWordOffset1 = DWordOffset0 + 1;
1304     assert(4 * DWordOffset0 == CAddr->getZExtValue());
1305 
1306     if (isUInt<8>(DWordOffset0) && isUInt<8>(DWordOffset1)) {
1307       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1308       MachineSDNode *MovZero
1309         = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1310                                  DL, MVT::i32, Zero);
1311       Base = SDValue(MovZero, 0);
1312       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
1313       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
1314       return true;
1315     }
1316   }
1317 
1318   // default case
1319 
1320   Base = Addr;
1321   Offset0 = CurDAG->getTargetConstant(0, DL, MVT::i8);
1322   Offset1 = CurDAG->getTargetConstant(1, DL, MVT::i8);
1323   return true;
1324 }
1325 
1326 bool AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr,
1327                                      SDValue &VAddr, SDValue &SOffset,
1328                                      SDValue &Offset, SDValue &Offen,
1329                                      SDValue &Idxen, SDValue &Addr64,
1330                                      SDValue &GLC, SDValue &SLC,
1331                                      SDValue &TFE, SDValue &DLC,
1332                                      SDValue &SWZ) const {
1333   // Subtarget prefers to use flat instruction
1334   if (Subtarget->useFlatForGlobal())
1335     return false;
1336 
1337   SDLoc DL(Addr);
1338 
1339   if (!GLC.getNode())
1340     GLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
1341   if (!SLC.getNode())
1342     SLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
1343   TFE = CurDAG->getTargetConstant(0, DL, MVT::i1);
1344   DLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
1345   SWZ = CurDAG->getTargetConstant(0, DL, MVT::i1);
1346 
1347   Idxen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1348   Offen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1349   Addr64 = CurDAG->getTargetConstant(0, DL, MVT::i1);
1350   SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1351 
1352   ConstantSDNode *C1 = nullptr;
1353   SDValue N0 = Addr;
1354   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1355     C1 = cast<ConstantSDNode>(Addr.getOperand(1));
1356     if (isUInt<32>(C1->getZExtValue()))
1357       N0 = Addr.getOperand(0);
1358     else
1359       C1 = nullptr;
1360   }
1361 
1362   if (N0.getOpcode() == ISD::ADD) {
1363     // (add N2, N3) -> addr64, or
1364     // (add (add N2, N3), C1) -> addr64
1365     SDValue N2 = N0.getOperand(0);
1366     SDValue N3 = N0.getOperand(1);
1367     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1368 
1369     if (N2->isDivergent()) {
1370       if (N3->isDivergent()) {
1371         // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
1372         // addr64, and construct the resource from a 0 address.
1373         Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1374         VAddr = N0;
1375       } else {
1376         // N2 is divergent, N3 is not.
1377         Ptr = N3;
1378         VAddr = N2;
1379       }
1380     } else {
1381       // N2 is not divergent.
1382       Ptr = N2;
1383       VAddr = N3;
1384     }
1385     Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1386   } else if (N0->isDivergent()) {
1387     // N0 is divergent. Use it as the addr64, and construct the resource from a
1388     // 0 address.
1389     Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1390     VAddr = N0;
1391     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1392   } else {
1393     // N0 -> offset, or
1394     // (N0 + C1) -> offset
1395     VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
1396     Ptr = N0;
1397   }
1398 
1399   if (!C1) {
1400     // No offset.
1401     Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1402     return true;
1403   }
1404 
1405   if (SIInstrInfo::isLegalMUBUFImmOffset(C1->getZExtValue())) {
1406     // Legal offset for instruction.
1407     Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1408     return true;
1409   }
1410 
1411   // Illegal offset, store it in soffset.
1412   Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1413   SOffset =
1414       SDValue(CurDAG->getMachineNode(
1415                   AMDGPU::S_MOV_B32, DL, MVT::i32,
1416                   CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32)),
1417               0);
1418   return true;
1419 }
1420 
1421 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1422                                            SDValue &VAddr, SDValue &SOffset,
1423                                            SDValue &Offset, SDValue &GLC,
1424                                            SDValue &SLC, SDValue &TFE,
1425                                            SDValue &DLC, SDValue &SWZ) const {
1426   SDValue Ptr, Offen, Idxen, Addr64;
1427 
1428   // addr64 bit was removed for volcanic islands.
1429   if (!Subtarget->hasAddr64())
1430     return false;
1431 
1432   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1433               GLC, SLC, TFE, DLC, SWZ))
1434     return false;
1435 
1436   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
1437   if (C->getSExtValue()) {
1438     SDLoc DL(Addr);
1439 
1440     const SITargetLowering& Lowering =
1441       *static_cast<const SITargetLowering*>(getTargetLowering());
1442 
1443     SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
1444     return true;
1445   }
1446 
1447   return false;
1448 }
1449 
1450 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1451                                            SDValue &VAddr, SDValue &SOffset,
1452                                            SDValue &Offset,
1453                                            SDValue &SLC) const {
1454   SLC = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i1);
1455   SDValue GLC, TFE, DLC, SWZ;
1456 
1457   return SelectMUBUFAddr64(Addr, SRsrc, VAddr, SOffset, Offset, GLC, SLC, TFE, DLC, SWZ);
1458 }
1459 
1460 static bool isStackPtrRelative(const MachinePointerInfo &PtrInfo) {
1461   auto PSV = PtrInfo.V.dyn_cast<const PseudoSourceValue *>();
1462   return PSV && PSV->isStack();
1463 }
1464 
1465 std::pair<SDValue, SDValue> AMDGPUDAGToDAGISel::foldFrameIndex(SDValue N) const {
1466   const MachineFunction &MF = CurDAG->getMachineFunction();
1467   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1468 
1469   if (auto FI = dyn_cast<FrameIndexSDNode>(N)) {
1470     SDValue TFI = CurDAG->getTargetFrameIndex(FI->getIndex(),
1471                                               FI->getValueType(0));
1472 
1473     // If we can resolve this to a frame index access, this will be relative to
1474     // either the stack or frame pointer SGPR.
1475     return std::make_pair(
1476         TFI, CurDAG->getRegister(Info->getStackPtrOffsetReg(), MVT::i32));
1477   }
1478 
1479   // If we don't know this private access is a local stack object, it needs to
1480   // be relative to the entry point's scratch wave offset register.
1481   return std::make_pair(N, CurDAG->getRegister(Info->getScratchWaveOffsetReg(),
1482                                                MVT::i32));
1483 }
1484 
1485 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(SDNode *Parent,
1486                                                  SDValue Addr, SDValue &Rsrc,
1487                                                  SDValue &VAddr, SDValue &SOffset,
1488                                                  SDValue &ImmOffset) const {
1489 
1490   SDLoc DL(Addr);
1491   MachineFunction &MF = CurDAG->getMachineFunction();
1492   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1493 
1494   Rsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1495 
1496   if (ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1497     unsigned Imm = CAddr->getZExtValue();
1498 
1499     SDValue HighBits = CurDAG->getTargetConstant(Imm & ~4095, DL, MVT::i32);
1500     MachineSDNode *MovHighBits = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1501                                                         DL, MVT::i32, HighBits);
1502     VAddr = SDValue(MovHighBits, 0);
1503 
1504     // In a call sequence, stores to the argument stack area are relative to the
1505     // stack pointer.
1506     const MachinePointerInfo &PtrInfo = cast<MemSDNode>(Parent)->getPointerInfo();
1507     unsigned SOffsetReg = isStackPtrRelative(PtrInfo) ?
1508       Info->getStackPtrOffsetReg() : Info->getScratchWaveOffsetReg();
1509 
1510     SOffset = CurDAG->getRegister(SOffsetReg, MVT::i32);
1511     ImmOffset = CurDAG->getTargetConstant(Imm & 4095, DL, MVT::i16);
1512     return true;
1513   }
1514 
1515   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1516     // (add n0, c1)
1517 
1518     SDValue N0 = Addr.getOperand(0);
1519     SDValue N1 = Addr.getOperand(1);
1520 
1521     // Offsets in vaddr must be positive if range checking is enabled.
1522     //
1523     // The total computation of vaddr + soffset + offset must not overflow.  If
1524     // vaddr is negative, even if offset is 0 the sgpr offset add will end up
1525     // overflowing.
1526     //
1527     // Prior to gfx9, MUBUF instructions with the vaddr offset enabled would
1528     // always perform a range check. If a negative vaddr base index was used,
1529     // this would fail the range check. The overall address computation would
1530     // compute a valid address, but this doesn't happen due to the range
1531     // check. For out-of-bounds MUBUF loads, a 0 is returned.
1532     //
1533     // Therefore it should be safe to fold any VGPR offset on gfx9 into the
1534     // MUBUF vaddr, but not on older subtargets which can only do this if the
1535     // sign bit is known 0.
1536     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1537     if (SIInstrInfo::isLegalMUBUFImmOffset(C1->getZExtValue()) &&
1538         (!Subtarget->privateMemoryResourceIsRangeChecked() ||
1539          CurDAG->SignBitIsZero(N0))) {
1540       std::tie(VAddr, SOffset) = foldFrameIndex(N0);
1541       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1542       return true;
1543     }
1544   }
1545 
1546   // (node)
1547   std::tie(VAddr, SOffset) = foldFrameIndex(Addr);
1548   ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1549   return true;
1550 }
1551 
1552 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffset(SDNode *Parent,
1553                                                   SDValue Addr,
1554                                                   SDValue &SRsrc,
1555                                                   SDValue &SOffset,
1556                                                   SDValue &Offset) const {
1557   ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr);
1558   if (!CAddr || !SIInstrInfo::isLegalMUBUFImmOffset(CAddr->getZExtValue()))
1559     return false;
1560 
1561   SDLoc DL(Addr);
1562   MachineFunction &MF = CurDAG->getMachineFunction();
1563   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1564 
1565   SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1566 
1567   const MachinePointerInfo &PtrInfo = cast<MemSDNode>(Parent)->getPointerInfo();
1568   unsigned SOffsetReg = isStackPtrRelative(PtrInfo) ?
1569     Info->getStackPtrOffsetReg() : Info->getScratchWaveOffsetReg();
1570 
1571   // FIXME: Get from MachinePointerInfo? We should only be using the frame
1572   // offset if we know this is in a call sequence.
1573   SOffset = CurDAG->getRegister(SOffsetReg, MVT::i32);
1574 
1575   Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1576   return true;
1577 }
1578 
1579 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1580                                            SDValue &SOffset, SDValue &Offset,
1581                                            SDValue &GLC, SDValue &SLC,
1582                                            SDValue &TFE, SDValue &DLC,
1583                                            SDValue &SWZ) const {
1584   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1585   const SIInstrInfo *TII =
1586     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1587 
1588   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1589               GLC, SLC, TFE, DLC, SWZ))
1590     return false;
1591 
1592   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1593       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1594       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1595     uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1596                     APInt::getAllOnesValue(32).getZExtValue(); // Size
1597     SDLoc DL(Addr);
1598 
1599     const SITargetLowering& Lowering =
1600       *static_cast<const SITargetLowering*>(getTargetLowering());
1601 
1602     SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1603     return true;
1604   }
1605   return false;
1606 }
1607 
1608 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1609                                            SDValue &Soffset, SDValue &Offset
1610                                            ) const {
1611   SDValue GLC, SLC, TFE, DLC, SWZ;
1612 
1613   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE, DLC, SWZ);
1614 }
1615 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1616                                            SDValue &Soffset, SDValue &Offset,
1617                                            SDValue &SLC) const {
1618   SDValue GLC, TFE, DLC, SWZ;
1619 
1620   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE, DLC, SWZ);
1621 }
1622 
1623 // Find a load or store from corresponding pattern root.
1624 // Roots may be build_vector, bitconvert or their combinations.
1625 static MemSDNode* findMemSDNode(SDNode *N) {
1626   N = AMDGPUTargetLowering::stripBitcast(SDValue(N,0)).getNode();
1627   if (MemSDNode *MN = dyn_cast<MemSDNode>(N))
1628     return MN;
1629   assert(isa<BuildVectorSDNode>(N));
1630   for (SDValue V : N->op_values())
1631     if (MemSDNode *MN =
1632           dyn_cast<MemSDNode>(AMDGPUTargetLowering::stripBitcast(V)))
1633       return MN;
1634   llvm_unreachable("cannot find MemSDNode in the pattern!");
1635 }
1636 
1637 template <bool IsSigned>
1638 bool AMDGPUDAGToDAGISel::SelectFlatOffset(SDNode *N,
1639                                           SDValue Addr,
1640                                           SDValue &VAddr,
1641                                           SDValue &Offset,
1642                                           SDValue &SLC) const {
1643   int64_t OffsetVal = 0;
1644 
1645   if (Subtarget->hasFlatInstOffsets() &&
1646       (!Subtarget->hasFlatSegmentOffsetBug() ||
1647        findMemSDNode(N)->getAddressSpace() != AMDGPUAS::FLAT_ADDRESS) &&
1648       CurDAG->isBaseWithConstantOffset(Addr)) {
1649     SDValue N0 = Addr.getOperand(0);
1650     SDValue N1 = Addr.getOperand(1);
1651     uint64_t COffsetVal = cast<ConstantSDNode>(N1)->getSExtValue();
1652 
1653     const SIInstrInfo *TII = Subtarget->getInstrInfo();
1654     unsigned AS = findMemSDNode(N)->getAddressSpace();
1655     if (TII->isLegalFLATOffset(COffsetVal, AS, IsSigned)) {
1656       Addr = N0;
1657       OffsetVal = COffsetVal;
1658     } else {
1659       // If the offset doesn't fit, put the low bits into the offset field and
1660       // add the rest.
1661 
1662       SDLoc DL(N);
1663       uint64_t ImmField;
1664       const unsigned NumBits = TII->getNumFlatOffsetBits(AS, IsSigned);
1665       if (IsSigned) {
1666         ImmField = SignExtend64(COffsetVal, NumBits);
1667 
1668         // Don't use a negative offset field if the base offset is positive.
1669         // Since the scheduler currently relies on the offset field, doing so
1670         // could result in strange scheduling decisions.
1671 
1672         // TODO: Should we not do this in the opposite direction as well?
1673         if (static_cast<int64_t>(COffsetVal) > 0) {
1674           if (static_cast<int64_t>(ImmField) < 0) {
1675             const uint64_t OffsetMask = maskTrailingOnes<uint64_t>(NumBits - 1);
1676             ImmField = COffsetVal & OffsetMask;
1677           }
1678         }
1679       } else {
1680         // TODO: Should we do this for a negative offset?
1681         const uint64_t OffsetMask = maskTrailingOnes<uint64_t>(NumBits);
1682         ImmField = COffsetVal & OffsetMask;
1683       }
1684 
1685       uint64_t RemainderOffset = COffsetVal - ImmField;
1686 
1687       assert(TII->isLegalFLATOffset(ImmField, AS, IsSigned));
1688       assert(RemainderOffset + ImmField == COffsetVal);
1689 
1690       OffsetVal = ImmField;
1691 
1692       // TODO: Should this try to use a scalar add pseudo if the base address is
1693       // uniform and saddr is usable?
1694       SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
1695       SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
1696 
1697       SDNode *N0Lo = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1698                                             DL, MVT::i32, N0, Sub0);
1699       SDNode *N0Hi = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1700                                             DL, MVT::i32, N0, Sub1);
1701 
1702       SDValue AddOffsetLo
1703         = getMaterializedScalarImm32(Lo_32(RemainderOffset), DL);
1704       SDValue AddOffsetHi
1705         = getMaterializedScalarImm32(Hi_32(RemainderOffset), DL);
1706 
1707       SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i1);
1708       SDValue Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
1709 
1710       SDNode *Add = CurDAG->getMachineNode(
1711         AMDGPU::V_ADD_I32_e64, DL, VTs,
1712         {AddOffsetLo, SDValue(N0Lo, 0), Clamp});
1713 
1714       SDNode *Addc = CurDAG->getMachineNode(
1715         AMDGPU::V_ADDC_U32_e64, DL, VTs,
1716         {AddOffsetHi, SDValue(N0Hi, 0), SDValue(Add, 1), Clamp});
1717 
1718       SDValue RegSequenceArgs[] = {
1719         CurDAG->getTargetConstant(AMDGPU::VReg_64RegClassID, DL, MVT::i32),
1720         SDValue(Add, 0), Sub0, SDValue(Addc, 0), Sub1
1721       };
1722 
1723       Addr = SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1724                                             MVT::i64, RegSequenceArgs), 0);
1725     }
1726   }
1727 
1728   VAddr = Addr;
1729   Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i16);
1730   SLC = CurDAG->getTargetConstant(0, SDLoc(), MVT::i1);
1731   return true;
1732 }
1733 
1734 bool AMDGPUDAGToDAGISel::SelectFlatAtomic(SDNode *N,
1735                                           SDValue Addr,
1736                                           SDValue &VAddr,
1737                                           SDValue &Offset,
1738                                           SDValue &SLC) const {
1739   return SelectFlatOffset<false>(N, Addr, VAddr, Offset, SLC);
1740 }
1741 
1742 bool AMDGPUDAGToDAGISel::SelectFlatAtomicSigned(SDNode *N,
1743                                                 SDValue Addr,
1744                                                 SDValue &VAddr,
1745                                                 SDValue &Offset,
1746                                                 SDValue &SLC) const {
1747   return SelectFlatOffset<true>(N, Addr, VAddr, Offset, SLC);
1748 }
1749 
1750 bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDValue ByteOffsetNode,
1751                                           SDValue &Offset, bool &Imm) const {
1752 
1753   // FIXME: Handle non-constant offsets.
1754   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ByteOffsetNode);
1755   if (!C)
1756     return false;
1757 
1758   SDLoc SL(ByteOffsetNode);
1759   GCNSubtarget::Generation Gen = Subtarget->getGeneration();
1760   int64_t ByteOffset = C->getSExtValue();
1761   int64_t EncodedOffset = AMDGPU::getSMRDEncodedOffset(*Subtarget, ByteOffset);
1762 
1763   if (AMDGPU::isLegalSMRDImmOffset(*Subtarget, ByteOffset)) {
1764     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1765     Imm = true;
1766     return true;
1767   }
1768 
1769   if (!isUInt<32>(EncodedOffset) || !isUInt<32>(ByteOffset))
1770     return false;
1771 
1772   if (Gen == AMDGPUSubtarget::SEA_ISLANDS && isUInt<32>(EncodedOffset)) {
1773     // 32-bit Immediates are supported on Sea Islands.
1774     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1775   } else {
1776     SDValue C32Bit = CurDAG->getTargetConstant(ByteOffset, SL, MVT::i32);
1777     Offset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32,
1778                                             C32Bit), 0);
1779   }
1780   Imm = false;
1781   return true;
1782 }
1783 
1784 SDValue AMDGPUDAGToDAGISel::Expand32BitAddress(SDValue Addr) const {
1785   if (Addr.getValueType() != MVT::i32)
1786     return Addr;
1787 
1788   // Zero-extend a 32-bit address.
1789   SDLoc SL(Addr);
1790 
1791   const MachineFunction &MF = CurDAG->getMachineFunction();
1792   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1793   unsigned AddrHiVal = Info->get32BitAddressHighBits();
1794   SDValue AddrHi = CurDAG->getTargetConstant(AddrHiVal, SL, MVT::i32);
1795 
1796   const SDValue Ops[] = {
1797     CurDAG->getTargetConstant(AMDGPU::SReg_64_XEXECRegClassID, SL, MVT::i32),
1798     Addr,
1799     CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32),
1800     SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32, AddrHi),
1801             0),
1802     CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32),
1803   };
1804 
1805   return SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, SL, MVT::i64,
1806                                         Ops), 0);
1807 }
1808 
1809 bool AMDGPUDAGToDAGISel::SelectSMRD(SDValue Addr, SDValue &SBase,
1810                                      SDValue &Offset, bool &Imm) const {
1811   SDLoc SL(Addr);
1812 
1813   // A 32-bit (address + offset) should not cause unsigned 32-bit integer
1814   // wraparound, because s_load instructions perform the addition in 64 bits.
1815   if ((Addr.getValueType() != MVT::i32 ||
1816        Addr->getFlags().hasNoUnsignedWrap()) &&
1817       CurDAG->isBaseWithConstantOffset(Addr)) {
1818     SDValue N0 = Addr.getOperand(0);
1819     SDValue N1 = Addr.getOperand(1);
1820 
1821     if (SelectSMRDOffset(N1, Offset, Imm)) {
1822       SBase = Expand32BitAddress(N0);
1823       return true;
1824     }
1825   }
1826   SBase = Expand32BitAddress(Addr);
1827   Offset = CurDAG->getTargetConstant(0, SL, MVT::i32);
1828   Imm = true;
1829   return true;
1830 }
1831 
1832 bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
1833                                        SDValue &Offset) const {
1834   bool Imm;
1835   return SelectSMRD(Addr, SBase, Offset, Imm) && Imm;
1836 }
1837 
1838 bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
1839                                          SDValue &Offset) const {
1840 
1841   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1842     return false;
1843 
1844   bool Imm;
1845   if (!SelectSMRD(Addr, SBase, Offset, Imm))
1846     return false;
1847 
1848   return !Imm && isa<ConstantSDNode>(Offset);
1849 }
1850 
1851 bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDValue Addr, SDValue &SBase,
1852                                         SDValue &Offset) const {
1853   bool Imm;
1854   return SelectSMRD(Addr, SBase, Offset, Imm) && !Imm &&
1855          !isa<ConstantSDNode>(Offset);
1856 }
1857 
1858 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue Addr,
1859                                              SDValue &Offset) const {
1860   bool Imm;
1861   return SelectSMRDOffset(Addr, Offset, Imm) && Imm;
1862 }
1863 
1864 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue Addr,
1865                                                SDValue &Offset) const {
1866   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1867     return false;
1868 
1869   bool Imm;
1870   if (!SelectSMRDOffset(Addr, Offset, Imm))
1871     return false;
1872 
1873   return !Imm && isa<ConstantSDNode>(Offset);
1874 }
1875 
1876 bool AMDGPUDAGToDAGISel::SelectMOVRELOffset(SDValue Index,
1877                                             SDValue &Base,
1878                                             SDValue &Offset) const {
1879   SDLoc DL(Index);
1880 
1881   if (CurDAG->isBaseWithConstantOffset(Index)) {
1882     SDValue N0 = Index.getOperand(0);
1883     SDValue N1 = Index.getOperand(1);
1884     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1885 
1886     // (add n0, c0)
1887     // Don't peel off the offset (c0) if doing so could possibly lead
1888     // the base (n0) to be negative.
1889     if (C1->getSExtValue() <= 0 || CurDAG->SignBitIsZero(N0)) {
1890       Base = N0;
1891       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
1892       return true;
1893     }
1894   }
1895 
1896   if (isa<ConstantSDNode>(Index))
1897     return false;
1898 
1899   Base = Index;
1900   Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1901   return true;
1902 }
1903 
1904 SDNode *AMDGPUDAGToDAGISel::getS_BFE(unsigned Opcode, const SDLoc &DL,
1905                                      SDValue Val, uint32_t Offset,
1906                                      uint32_t Width) {
1907   // Transformation function, pack the offset and width of a BFE into
1908   // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
1909   // source, bits [5:0] contain the offset and bits [22:16] the width.
1910   uint32_t PackedVal = Offset | (Width << 16);
1911   SDValue PackedConst = CurDAG->getTargetConstant(PackedVal, DL, MVT::i32);
1912 
1913   return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, PackedConst);
1914 }
1915 
1916 void AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
1917   // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
1918   // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
1919   // Predicate: 0 < b <= c < 32
1920 
1921   const SDValue &Shl = N->getOperand(0);
1922   ConstantSDNode *B = dyn_cast<ConstantSDNode>(Shl->getOperand(1));
1923   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1924 
1925   if (B && C) {
1926     uint32_t BVal = B->getZExtValue();
1927     uint32_t CVal = C->getZExtValue();
1928 
1929     if (0 < BVal && BVal <= CVal && CVal < 32) {
1930       bool Signed = N->getOpcode() == ISD::SRA;
1931       unsigned Opcode = Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
1932 
1933       ReplaceNode(N, getS_BFE(Opcode, SDLoc(N), Shl.getOperand(0), CVal - BVal,
1934                               32 - CVal));
1935       return;
1936     }
1937   }
1938   SelectCode(N);
1939 }
1940 
1941 void AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
1942   switch (N->getOpcode()) {
1943   case ISD::AND:
1944     if (N->getOperand(0).getOpcode() == ISD::SRL) {
1945       // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
1946       // Predicate: isMask(mask)
1947       const SDValue &Srl = N->getOperand(0);
1948       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Srl.getOperand(1));
1949       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
1950 
1951       if (Shift && Mask) {
1952         uint32_t ShiftVal = Shift->getZExtValue();
1953         uint32_t MaskVal = Mask->getZExtValue();
1954 
1955         if (isMask_32(MaskVal)) {
1956           uint32_t WidthVal = countPopulation(MaskVal);
1957 
1958           ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N),
1959                                   Srl.getOperand(0), ShiftVal, WidthVal));
1960           return;
1961         }
1962       }
1963     }
1964     break;
1965   case ISD::SRL:
1966     if (N->getOperand(0).getOpcode() == ISD::AND) {
1967       // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
1968       // Predicate: isMask(mask >> b)
1969       const SDValue &And = N->getOperand(0);
1970       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N->getOperand(1));
1971       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(And->getOperand(1));
1972 
1973       if (Shift && Mask) {
1974         uint32_t ShiftVal = Shift->getZExtValue();
1975         uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
1976 
1977         if (isMask_32(MaskVal)) {
1978           uint32_t WidthVal = countPopulation(MaskVal);
1979 
1980           ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N),
1981                                   And.getOperand(0), ShiftVal, WidthVal));
1982           return;
1983         }
1984       }
1985     } else if (N->getOperand(0).getOpcode() == ISD::SHL) {
1986       SelectS_BFEFromShifts(N);
1987       return;
1988     }
1989     break;
1990   case ISD::SRA:
1991     if (N->getOperand(0).getOpcode() == ISD::SHL) {
1992       SelectS_BFEFromShifts(N);
1993       return;
1994     }
1995     break;
1996 
1997   case ISD::SIGN_EXTEND_INREG: {
1998     // sext_inreg (srl x, 16), i8 -> bfe_i32 x, 16, 8
1999     SDValue Src = N->getOperand(0);
2000     if (Src.getOpcode() != ISD::SRL)
2001       break;
2002 
2003     const ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
2004     if (!Amt)
2005       break;
2006 
2007     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
2008     ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_I32, SDLoc(N), Src.getOperand(0),
2009                             Amt->getZExtValue(), Width));
2010     return;
2011   }
2012   }
2013 
2014   SelectCode(N);
2015 }
2016 
2017 bool AMDGPUDAGToDAGISel::isCBranchSCC(const SDNode *N) const {
2018   assert(N->getOpcode() == ISD::BRCOND);
2019   if (!N->hasOneUse())
2020     return false;
2021 
2022   SDValue Cond = N->getOperand(1);
2023   if (Cond.getOpcode() == ISD::CopyToReg)
2024     Cond = Cond.getOperand(2);
2025 
2026   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
2027     return false;
2028 
2029   MVT VT = Cond.getOperand(0).getSimpleValueType();
2030   if (VT == MVT::i32)
2031     return true;
2032 
2033   if (VT == MVT::i64) {
2034     auto ST = static_cast<const GCNSubtarget *>(Subtarget);
2035 
2036     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
2037     return (CC == ISD::SETEQ || CC == ISD::SETNE) && ST->hasScalarCompareEq64();
2038   }
2039 
2040   return false;
2041 }
2042 
2043 void AMDGPUDAGToDAGISel::SelectBRCOND(SDNode *N) {
2044   SDValue Cond = N->getOperand(1);
2045 
2046   if (Cond.isUndef()) {
2047     CurDAG->SelectNodeTo(N, AMDGPU::SI_BR_UNDEF, MVT::Other,
2048                          N->getOperand(2), N->getOperand(0));
2049     return;
2050   }
2051 
2052   const GCNSubtarget *ST = static_cast<const GCNSubtarget *>(Subtarget);
2053   const SIRegisterInfo *TRI = ST->getRegisterInfo();
2054 
2055   bool UseSCCBr = isCBranchSCC(N) && isUniformBr(N);
2056   unsigned BrOp = UseSCCBr ? AMDGPU::S_CBRANCH_SCC1 : AMDGPU::S_CBRANCH_VCCNZ;
2057   unsigned CondReg = UseSCCBr ? (unsigned)AMDGPU::SCC : TRI->getVCC();
2058   SDLoc SL(N);
2059 
2060   if (!UseSCCBr) {
2061     // This is the case that we are selecting to S_CBRANCH_VCCNZ.  We have not
2062     // analyzed what generates the vcc value, so we do not know whether vcc
2063     // bits for disabled lanes are 0.  Thus we need to mask out bits for
2064     // disabled lanes.
2065     //
2066     // For the case that we select S_CBRANCH_SCC1 and it gets
2067     // changed to S_CBRANCH_VCCNZ in SIFixSGPRCopies, SIFixSGPRCopies calls
2068     // SIInstrInfo::moveToVALU which inserts the S_AND).
2069     //
2070     // We could add an analysis of what generates the vcc value here and omit
2071     // the S_AND when is unnecessary. But it would be better to add a separate
2072     // pass after SIFixSGPRCopies to do the unnecessary S_AND removal, so it
2073     // catches both cases.
2074     Cond = SDValue(CurDAG->getMachineNode(ST->isWave32() ? AMDGPU::S_AND_B32
2075                                                          : AMDGPU::S_AND_B64,
2076                      SL, MVT::i1,
2077                      CurDAG->getRegister(ST->isWave32() ? AMDGPU::EXEC_LO
2078                                                         : AMDGPU::EXEC,
2079                                          MVT::i1),
2080                     Cond),
2081                    0);
2082   }
2083 
2084   SDValue VCC = CurDAG->getCopyToReg(N->getOperand(0), SL, CondReg, Cond);
2085   CurDAG->SelectNodeTo(N, BrOp, MVT::Other,
2086                        N->getOperand(2), // Basic Block
2087                        VCC.getValue(0));
2088 }
2089 
2090 void AMDGPUDAGToDAGISel::SelectFMAD_FMA(SDNode *N) {
2091   MVT VT = N->getSimpleValueType(0);
2092   bool IsFMA = N->getOpcode() == ISD::FMA;
2093   if (VT != MVT::f32 || (!Subtarget->hasMadMixInsts() &&
2094                          !Subtarget->hasFmaMixInsts()) ||
2095       ((IsFMA && Subtarget->hasMadMixInsts()) ||
2096        (!IsFMA && Subtarget->hasFmaMixInsts()))) {
2097     SelectCode(N);
2098     return;
2099   }
2100 
2101   SDValue Src0 = N->getOperand(0);
2102   SDValue Src1 = N->getOperand(1);
2103   SDValue Src2 = N->getOperand(2);
2104   unsigned Src0Mods, Src1Mods, Src2Mods;
2105 
2106   // Avoid using v_mad_mix_f32/v_fma_mix_f32 unless there is actually an operand
2107   // using the conversion from f16.
2108   bool Sel0 = SelectVOP3PMadMixModsImpl(Src0, Src0, Src0Mods);
2109   bool Sel1 = SelectVOP3PMadMixModsImpl(Src1, Src1, Src1Mods);
2110   bool Sel2 = SelectVOP3PMadMixModsImpl(Src2, Src2, Src2Mods);
2111 
2112   assert((IsFMA || !Mode.FP32Denormals) &&
2113          "fmad selected with denormals enabled");
2114   // TODO: We can select this with f32 denormals enabled if all the sources are
2115   // converted from f16 (in which case fmad isn't legal).
2116 
2117   if (Sel0 || Sel1 || Sel2) {
2118     // For dummy operands.
2119     SDValue Zero = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
2120     SDValue Ops[] = {
2121       CurDAG->getTargetConstant(Src0Mods, SDLoc(), MVT::i32), Src0,
2122       CurDAG->getTargetConstant(Src1Mods, SDLoc(), MVT::i32), Src1,
2123       CurDAG->getTargetConstant(Src2Mods, SDLoc(), MVT::i32), Src2,
2124       CurDAG->getTargetConstant(0, SDLoc(), MVT::i1),
2125       Zero, Zero
2126     };
2127 
2128     CurDAG->SelectNodeTo(N,
2129                          IsFMA ? AMDGPU::V_FMA_MIX_F32 : AMDGPU::V_MAD_MIX_F32,
2130                          MVT::f32, Ops);
2131   } else {
2132     SelectCode(N);
2133   }
2134 }
2135 
2136 // This is here because there isn't a way to use the generated sub0_sub1 as the
2137 // subreg index to EXTRACT_SUBREG in tablegen.
2138 void AMDGPUDAGToDAGISel::SelectATOMIC_CMP_SWAP(SDNode *N) {
2139   MemSDNode *Mem = cast<MemSDNode>(N);
2140   unsigned AS = Mem->getAddressSpace();
2141   if (AS == AMDGPUAS::FLAT_ADDRESS) {
2142     SelectCode(N);
2143     return;
2144   }
2145 
2146   MVT VT = N->getSimpleValueType(0);
2147   bool Is32 = (VT == MVT::i32);
2148   SDLoc SL(N);
2149 
2150   MachineSDNode *CmpSwap = nullptr;
2151   if (Subtarget->hasAddr64()) {
2152     SDValue SRsrc, VAddr, SOffset, Offset, SLC;
2153 
2154     if (SelectMUBUFAddr64(Mem->getBasePtr(), SRsrc, VAddr, SOffset, Offset, SLC)) {
2155       unsigned Opcode = Is32 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_ADDR64_RTN :
2156         AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_ADDR64_RTN;
2157       SDValue CmpVal = Mem->getOperand(2);
2158 
2159       // XXX - Do we care about glue operands?
2160 
2161       SDValue Ops[] = {
2162         CmpVal, VAddr, SRsrc, SOffset, Offset, SLC, Mem->getChain()
2163       };
2164 
2165       CmpSwap = CurDAG->getMachineNode(Opcode, SL, Mem->getVTList(), Ops);
2166     }
2167   }
2168 
2169   if (!CmpSwap) {
2170     SDValue SRsrc, SOffset, Offset, SLC;
2171     if (SelectMUBUFOffset(Mem->getBasePtr(), SRsrc, SOffset, Offset, SLC)) {
2172       unsigned Opcode = Is32 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_OFFSET_RTN :
2173         AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_OFFSET_RTN;
2174 
2175       SDValue CmpVal = Mem->getOperand(2);
2176       SDValue Ops[] = {
2177         CmpVal, SRsrc, SOffset, Offset, SLC, Mem->getChain()
2178       };
2179 
2180       CmpSwap = CurDAG->getMachineNode(Opcode, SL, Mem->getVTList(), Ops);
2181     }
2182   }
2183 
2184   if (!CmpSwap) {
2185     SelectCode(N);
2186     return;
2187   }
2188 
2189   MachineMemOperand *MMO = Mem->getMemOperand();
2190   CurDAG->setNodeMemRefs(CmpSwap, {MMO});
2191 
2192   unsigned SubReg = Is32 ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
2193   SDValue Extract
2194     = CurDAG->getTargetExtractSubreg(SubReg, SL, VT, SDValue(CmpSwap, 0));
2195 
2196   ReplaceUses(SDValue(N, 0), Extract);
2197   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 1));
2198   CurDAG->RemoveDeadNode(N);
2199 }
2200 
2201 void AMDGPUDAGToDAGISel::SelectDSAppendConsume(SDNode *N, unsigned IntrID) {
2202   // The address is assumed to be uniform, so if it ends up in a VGPR, it will
2203   // be copied to an SGPR with readfirstlane.
2204   unsigned Opc = IntrID == Intrinsic::amdgcn_ds_append ?
2205     AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
2206 
2207   SDValue Chain = N->getOperand(0);
2208   SDValue Ptr = N->getOperand(2);
2209   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2210   MachineMemOperand *MMO = M->getMemOperand();
2211   bool IsGDS = M->getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
2212 
2213   SDValue Offset;
2214   if (CurDAG->isBaseWithConstantOffset(Ptr)) {
2215     SDValue PtrBase = Ptr.getOperand(0);
2216     SDValue PtrOffset = Ptr.getOperand(1);
2217 
2218     const APInt &OffsetVal = cast<ConstantSDNode>(PtrOffset)->getAPIntValue();
2219     if (isDSOffsetLegal(PtrBase, OffsetVal.getZExtValue(), 16)) {
2220       N = glueCopyToM0(N, PtrBase);
2221       Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i32);
2222     }
2223   }
2224 
2225   if (!Offset) {
2226     N = glueCopyToM0(N, Ptr);
2227     Offset = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
2228   }
2229 
2230   SDValue Ops[] = {
2231     Offset,
2232     CurDAG->getTargetConstant(IsGDS, SDLoc(), MVT::i32),
2233     Chain,
2234     N->getOperand(N->getNumOperands() - 1) // New glue
2235   };
2236 
2237   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2238   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2239 }
2240 
2241 static unsigned gwsIntrinToOpcode(unsigned IntrID) {
2242   switch (IntrID) {
2243   case Intrinsic::amdgcn_ds_gws_init:
2244     return AMDGPU::DS_GWS_INIT;
2245   case Intrinsic::amdgcn_ds_gws_barrier:
2246     return AMDGPU::DS_GWS_BARRIER;
2247   case Intrinsic::amdgcn_ds_gws_sema_v:
2248     return AMDGPU::DS_GWS_SEMA_V;
2249   case Intrinsic::amdgcn_ds_gws_sema_br:
2250     return AMDGPU::DS_GWS_SEMA_BR;
2251   case Intrinsic::amdgcn_ds_gws_sema_p:
2252     return AMDGPU::DS_GWS_SEMA_P;
2253   case Intrinsic::amdgcn_ds_gws_sema_release_all:
2254     return AMDGPU::DS_GWS_SEMA_RELEASE_ALL;
2255   default:
2256     llvm_unreachable("not a gws intrinsic");
2257   }
2258 }
2259 
2260 void AMDGPUDAGToDAGISel::SelectDS_GWS(SDNode *N, unsigned IntrID) {
2261   if (IntrID == Intrinsic::amdgcn_ds_gws_sema_release_all &&
2262       !Subtarget->hasGWSSemaReleaseAll()) {
2263     // Let this error.
2264     SelectCode(N);
2265     return;
2266   }
2267 
2268   // Chain, intrinsic ID, vsrc, offset
2269   const bool HasVSrc = N->getNumOperands() == 4;
2270   assert(HasVSrc || N->getNumOperands() == 3);
2271 
2272   SDLoc SL(N);
2273   SDValue BaseOffset = N->getOperand(HasVSrc ? 3 : 2);
2274   int ImmOffset = 0;
2275   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2276   MachineMemOperand *MMO = M->getMemOperand();
2277 
2278   // Don't worry if the offset ends up in a VGPR. Only one lane will have
2279   // effect, so SIFixSGPRCopies will validly insert readfirstlane.
2280 
2281   // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
2282   // offset field) % 64. Some versions of the programming guide omit the m0
2283   // part, or claim it's from offset 0.
2284   if (ConstantSDNode *ConstOffset = dyn_cast<ConstantSDNode>(BaseOffset)) {
2285     // If we have a constant offset, try to use the 0 in m0 as the base.
2286     // TODO: Look into changing the default m0 initialization value. If the
2287     // default -1 only set the low 16-bits, we could leave it as-is and add 1 to
2288     // the immediate offset.
2289     glueCopyToM0(N, CurDAG->getTargetConstant(0, SL, MVT::i32));
2290     ImmOffset = ConstOffset->getZExtValue();
2291   } else {
2292     if (CurDAG->isBaseWithConstantOffset(BaseOffset)) {
2293       ImmOffset = BaseOffset.getConstantOperandVal(1);
2294       BaseOffset = BaseOffset.getOperand(0);
2295     }
2296 
2297     // Prefer to do the shift in an SGPR since it should be possible to use m0
2298     // as the result directly. If it's already an SGPR, it will be eliminated
2299     // later.
2300     SDNode *SGPROffset
2301       = CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL, MVT::i32,
2302                                BaseOffset);
2303     // Shift to offset in m0
2304     SDNode *M0Base
2305       = CurDAG->getMachineNode(AMDGPU::S_LSHL_B32, SL, MVT::i32,
2306                                SDValue(SGPROffset, 0),
2307                                CurDAG->getTargetConstant(16, SL, MVT::i32));
2308     glueCopyToM0(N, SDValue(M0Base, 0));
2309   }
2310 
2311   SDValue Chain = N->getOperand(0);
2312   SDValue OffsetField = CurDAG->getTargetConstant(ImmOffset, SL, MVT::i32);
2313 
2314   // TODO: Can this just be removed from the instruction?
2315   SDValue GDS = CurDAG->getTargetConstant(1, SL, MVT::i1);
2316 
2317   const unsigned Opc = gwsIntrinToOpcode(IntrID);
2318   SmallVector<SDValue, 5> Ops;
2319   if (HasVSrc)
2320     Ops.push_back(N->getOperand(2));
2321   Ops.push_back(OffsetField);
2322   Ops.push_back(GDS);
2323   Ops.push_back(Chain);
2324 
2325   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2326   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2327 }
2328 
2329 void AMDGPUDAGToDAGISel::SelectINTRINSIC_W_CHAIN(SDNode *N) {
2330   unsigned IntrID = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2331   switch (IntrID) {
2332   case Intrinsic::amdgcn_ds_append:
2333   case Intrinsic::amdgcn_ds_consume: {
2334     if (N->getValueType(0) != MVT::i32)
2335       break;
2336     SelectDSAppendConsume(N, IntrID);
2337     return;
2338   }
2339   }
2340 
2341   SelectCode(N);
2342 }
2343 
2344 void AMDGPUDAGToDAGISel::SelectINTRINSIC_WO_CHAIN(SDNode *N) {
2345   unsigned IntrID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2346   unsigned Opcode;
2347   switch (IntrID) {
2348   case Intrinsic::amdgcn_wqm:
2349     Opcode = AMDGPU::WQM;
2350     break;
2351   case Intrinsic::amdgcn_softwqm:
2352     Opcode = AMDGPU::SOFT_WQM;
2353     break;
2354   case Intrinsic::amdgcn_wwm:
2355     Opcode = AMDGPU::WWM;
2356     break;
2357   default:
2358     SelectCode(N);
2359     return;
2360   }
2361 
2362   SDValue Src = N->getOperand(1);
2363   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), {Src});
2364 }
2365 
2366 void AMDGPUDAGToDAGISel::SelectINTRINSIC_VOID(SDNode *N) {
2367   unsigned IntrID = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2368   switch (IntrID) {
2369   case Intrinsic::amdgcn_ds_gws_init:
2370   case Intrinsic::amdgcn_ds_gws_barrier:
2371   case Intrinsic::amdgcn_ds_gws_sema_v:
2372   case Intrinsic::amdgcn_ds_gws_sema_br:
2373   case Intrinsic::amdgcn_ds_gws_sema_p:
2374   case Intrinsic::amdgcn_ds_gws_sema_release_all:
2375     SelectDS_GWS(N, IntrID);
2376     return;
2377   default:
2378     break;
2379   }
2380 
2381   SelectCode(N);
2382 }
2383 
2384 bool AMDGPUDAGToDAGISel::SelectVOP3ModsImpl(SDValue In, SDValue &Src,
2385                                             unsigned &Mods) const {
2386   Mods = 0;
2387   Src = In;
2388 
2389   if (Src.getOpcode() == ISD::FNEG) {
2390     Mods |= SISrcMods::NEG;
2391     Src = Src.getOperand(0);
2392   }
2393 
2394   if (Src.getOpcode() == ISD::FABS) {
2395     Mods |= SISrcMods::ABS;
2396     Src = Src.getOperand(0);
2397   }
2398 
2399   return true;
2400 }
2401 
2402 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
2403                                         SDValue &SrcMods) const {
2404   unsigned Mods;
2405   if (SelectVOP3ModsImpl(In, Src, Mods)) {
2406     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2407     return true;
2408   }
2409 
2410   return false;
2411 }
2412 
2413 bool AMDGPUDAGToDAGISel::SelectVOP3Mods_NNaN(SDValue In, SDValue &Src,
2414                                              SDValue &SrcMods) const {
2415   SelectVOP3Mods(In, Src, SrcMods);
2416   return isNoNanSrc(Src);
2417 }
2418 
2419 bool AMDGPUDAGToDAGISel::SelectVOP3Mods_f32(SDValue In, SDValue &Src,
2420                                             SDValue &SrcMods) const {
2421   if (In.getValueType() == MVT::f32)
2422     return SelectVOP3Mods(In, Src, SrcMods);
2423   Src = In;
2424   SrcMods = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);;
2425   return true;
2426 }
2427 
2428 bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src) const {
2429   if (In.getOpcode() == ISD::FABS || In.getOpcode() == ISD::FNEG)
2430     return false;
2431 
2432   Src = In;
2433   return true;
2434 }
2435 
2436 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
2437                                          SDValue &SrcMods, SDValue &Clamp,
2438                                          SDValue &Omod) const {
2439   SDLoc DL(In);
2440   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2441   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2442 
2443   return SelectVOP3Mods(In, Src, SrcMods);
2444 }
2445 
2446 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src,
2447                                                    SDValue &SrcMods,
2448                                                    SDValue &Clamp,
2449                                                    SDValue &Omod) const {
2450   Clamp = Omod = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
2451   return SelectVOP3Mods(In, Src, SrcMods);
2452 }
2453 
2454 bool AMDGPUDAGToDAGISel::SelectVOP3OMods(SDValue In, SDValue &Src,
2455                                          SDValue &Clamp, SDValue &Omod) const {
2456   Src = In;
2457 
2458   SDLoc DL(In);
2459   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2460   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2461 
2462   return true;
2463 }
2464 
2465 bool AMDGPUDAGToDAGISel::SelectVOP3PMods(SDValue In, SDValue &Src,
2466                                          SDValue &SrcMods) const {
2467   unsigned Mods = 0;
2468   Src = In;
2469 
2470   if (Src.getOpcode() == ISD::FNEG) {
2471     Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
2472     Src = Src.getOperand(0);
2473   }
2474 
2475   if (Src.getOpcode() == ISD::BUILD_VECTOR) {
2476     unsigned VecMods = Mods;
2477 
2478     SDValue Lo = stripBitcast(Src.getOperand(0));
2479     SDValue Hi = stripBitcast(Src.getOperand(1));
2480 
2481     if (Lo.getOpcode() == ISD::FNEG) {
2482       Lo = stripBitcast(Lo.getOperand(0));
2483       Mods ^= SISrcMods::NEG;
2484     }
2485 
2486     if (Hi.getOpcode() == ISD::FNEG) {
2487       Hi = stripBitcast(Hi.getOperand(0));
2488       Mods ^= SISrcMods::NEG_HI;
2489     }
2490 
2491     if (isExtractHiElt(Lo, Lo))
2492       Mods |= SISrcMods::OP_SEL_0;
2493 
2494     if (isExtractHiElt(Hi, Hi))
2495       Mods |= SISrcMods::OP_SEL_1;
2496 
2497     Lo = stripExtractLoElt(Lo);
2498     Hi = stripExtractLoElt(Hi);
2499 
2500     if (Lo == Hi && !isInlineImmediate(Lo.getNode())) {
2501       // Really a scalar input. Just select from the low half of the register to
2502       // avoid packing.
2503 
2504       Src = Lo;
2505       SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2506       return true;
2507     }
2508 
2509     Mods = VecMods;
2510   }
2511 
2512   // Packed instructions do not have abs modifiers.
2513   Mods |= SISrcMods::OP_SEL_1;
2514 
2515   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2516   return true;
2517 }
2518 
2519 bool AMDGPUDAGToDAGISel::SelectVOP3PMods0(SDValue In, SDValue &Src,
2520                                           SDValue &SrcMods,
2521                                           SDValue &Clamp) const {
2522   SDLoc SL(In);
2523 
2524   // FIXME: Handle clamp and op_sel
2525   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
2526 
2527   return SelectVOP3PMods(In, Src, SrcMods);
2528 }
2529 
2530 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel(SDValue In, SDValue &Src,
2531                                          SDValue &SrcMods) const {
2532   Src = In;
2533   // FIXME: Handle op_sel
2534   SrcMods = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
2535   return true;
2536 }
2537 
2538 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel0(SDValue In, SDValue &Src,
2539                                           SDValue &SrcMods,
2540                                           SDValue &Clamp) const {
2541   SDLoc SL(In);
2542 
2543   // FIXME: Handle clamp
2544   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
2545 
2546   return SelectVOP3OpSel(In, Src, SrcMods);
2547 }
2548 
2549 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods(SDValue In, SDValue &Src,
2550                                              SDValue &SrcMods) const {
2551   // FIXME: Handle op_sel
2552   return SelectVOP3Mods(In, Src, SrcMods);
2553 }
2554 
2555 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods0(SDValue In, SDValue &Src,
2556                                               SDValue &SrcMods,
2557                                               SDValue &Clamp) const {
2558   SDLoc SL(In);
2559 
2560   // FIXME: Handle clamp
2561   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
2562 
2563   return SelectVOP3OpSelMods(In, Src, SrcMods);
2564 }
2565 
2566 // The return value is not whether the match is possible (which it always is),
2567 // but whether or not it a conversion is really used.
2568 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src,
2569                                                    unsigned &Mods) const {
2570   Mods = 0;
2571   SelectVOP3ModsImpl(In, Src, Mods);
2572 
2573   if (Src.getOpcode() == ISD::FP_EXTEND) {
2574     Src = Src.getOperand(0);
2575     assert(Src.getValueType() == MVT::f16);
2576     Src = stripBitcast(Src);
2577 
2578     // Be careful about folding modifiers if we already have an abs. fneg is
2579     // applied last, so we don't want to apply an earlier fneg.
2580     if ((Mods & SISrcMods::ABS) == 0) {
2581       unsigned ModsTmp;
2582       SelectVOP3ModsImpl(Src, Src, ModsTmp);
2583 
2584       if ((ModsTmp & SISrcMods::NEG) != 0)
2585         Mods ^= SISrcMods::NEG;
2586 
2587       if ((ModsTmp & SISrcMods::ABS) != 0)
2588         Mods |= SISrcMods::ABS;
2589     }
2590 
2591     // op_sel/op_sel_hi decide the source type and source.
2592     // If the source's op_sel_hi is set, it indicates to do a conversion from fp16.
2593     // If the sources's op_sel is set, it picks the high half of the source
2594     // register.
2595 
2596     Mods |= SISrcMods::OP_SEL_1;
2597     if (isExtractHiElt(Src, Src)) {
2598       Mods |= SISrcMods::OP_SEL_0;
2599 
2600       // TODO: Should we try to look for neg/abs here?
2601     }
2602 
2603     return true;
2604   }
2605 
2606   return false;
2607 }
2608 
2609 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixMods(SDValue In, SDValue &Src,
2610                                                SDValue &SrcMods) const {
2611   unsigned Mods = 0;
2612   SelectVOP3PMadMixModsImpl(In, Src, Mods);
2613   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2614   return true;
2615 }
2616 
2617 SDValue AMDGPUDAGToDAGISel::getHi16Elt(SDValue In) const {
2618   if (In.isUndef())
2619     return CurDAG->getUNDEF(MVT::i32);
2620 
2621   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(In)) {
2622     SDLoc SL(In);
2623     return CurDAG->getConstant(C->getZExtValue() << 16, SL, MVT::i32);
2624   }
2625 
2626   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(In)) {
2627     SDLoc SL(In);
2628     return CurDAG->getConstant(
2629       C->getValueAPF().bitcastToAPInt().getZExtValue() << 16, SL, MVT::i32);
2630   }
2631 
2632   SDValue Src;
2633   if (isExtractHiElt(In, Src))
2634     return Src;
2635 
2636   return SDValue();
2637 }
2638 
2639 bool AMDGPUDAGToDAGISel::isVGPRImm(const SDNode * N) const {
2640   assert(CurDAG->getTarget().getTargetTriple().getArch() == Triple::amdgcn);
2641 
2642   const SIRegisterInfo *SIRI =
2643     static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
2644   const SIInstrInfo * SII =
2645     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2646 
2647   unsigned Limit = 0;
2648   bool AllUsesAcceptSReg = true;
2649   for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
2650     Limit < 10 && U != E; ++U, ++Limit) {
2651     const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
2652 
2653     // If the register class is unknown, it could be an unknown
2654     // register class that needs to be an SGPR, e.g. an inline asm
2655     // constraint
2656     if (!RC || SIRI->isSGPRClass(RC))
2657       return false;
2658 
2659     if (RC != &AMDGPU::VS_32RegClass) {
2660       AllUsesAcceptSReg = false;
2661       SDNode * User = *U;
2662       if (User->isMachineOpcode()) {
2663         unsigned Opc = User->getMachineOpcode();
2664         MCInstrDesc Desc = SII->get(Opc);
2665         if (Desc.isCommutable()) {
2666           unsigned OpIdx = Desc.getNumDefs() + U.getOperandNo();
2667           unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
2668           if (SII->findCommutedOpIndices(Desc, OpIdx, CommuteIdx1)) {
2669             unsigned CommutedOpNo = CommuteIdx1 - Desc.getNumDefs();
2670             const TargetRegisterClass *CommutedRC = getOperandRegClass(*U, CommutedOpNo);
2671             if (CommutedRC == &AMDGPU::VS_32RegClass)
2672               AllUsesAcceptSReg = true;
2673           }
2674         }
2675       }
2676       // If "AllUsesAcceptSReg == false" so far we haven't suceeded
2677       // commuting current user. This means have at least one use
2678       // that strictly require VGPR. Thus, we will not attempt to commute
2679       // other user instructions.
2680       if (!AllUsesAcceptSReg)
2681         break;
2682     }
2683   }
2684   return !AllUsesAcceptSReg && (Limit < 10);
2685 }
2686 
2687 bool AMDGPUDAGToDAGISel::isUniformLoad(const SDNode * N) const {
2688   auto Ld = cast<LoadSDNode>(N);
2689 
2690   return Ld->getAlignment() >= 4 &&
2691         (
2692           (
2693             (
2694               Ld->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS       ||
2695               Ld->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT
2696             )
2697             &&
2698             !N->isDivergent()
2699           )
2700           ||
2701           (
2702             Subtarget->getScalarizeGlobalBehavior() &&
2703             Ld->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
2704             !Ld->isVolatile() &&
2705             !N->isDivergent() &&
2706             static_cast<const SITargetLowering *>(
2707               getTargetLowering())->isMemOpHasNoClobberedMemOperand(N)
2708           )
2709         );
2710 }
2711 
2712 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
2713   const AMDGPUTargetLowering& Lowering =
2714     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
2715   bool IsModified = false;
2716   do {
2717     IsModified = false;
2718 
2719     // Go over all selected nodes and try to fold them a bit more
2720     SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_begin();
2721     while (Position != CurDAG->allnodes_end()) {
2722       SDNode *Node = &*Position++;
2723       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(Node);
2724       if (!MachineNode)
2725         continue;
2726 
2727       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
2728       if (ResNode != Node) {
2729         if (ResNode)
2730           ReplaceUses(Node, ResNode);
2731         IsModified = true;
2732       }
2733     }
2734     CurDAG->RemoveDeadNodes();
2735   } while (IsModified);
2736 }
2737 
2738 bool R600DAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
2739   Subtarget = &MF.getSubtarget<R600Subtarget>();
2740   return SelectionDAGISel::runOnMachineFunction(MF);
2741 }
2742 
2743 bool R600DAGToDAGISel::isConstantLoad(const MemSDNode *N, int CbId) const {
2744   if (!N->readMem())
2745     return false;
2746   if (CbId == -1)
2747     return N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
2748            N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT;
2749 
2750   return N->getAddressSpace() == AMDGPUAS::CONSTANT_BUFFER_0 + CbId;
2751 }
2752 
2753 bool R600DAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
2754                                                          SDValue& IntPtr) {
2755   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
2756     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, SDLoc(Addr),
2757                                        true);
2758     return true;
2759   }
2760   return false;
2761 }
2762 
2763 bool R600DAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
2764     SDValue& BaseReg, SDValue &Offset) {
2765   if (!isa<ConstantSDNode>(Addr)) {
2766     BaseReg = Addr;
2767     Offset = CurDAG->getIntPtrConstant(0, SDLoc(Addr), true);
2768     return true;
2769   }
2770   return false;
2771 }
2772 
2773 void R600DAGToDAGISel::Select(SDNode *N) {
2774   unsigned int Opc = N->getOpcode();
2775   if (N->isMachineOpcode()) {
2776     N->setNodeId(-1);
2777     return;   // Already selected.
2778   }
2779 
2780   switch (Opc) {
2781   default: break;
2782   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
2783   case ISD::SCALAR_TO_VECTOR:
2784   case ISD::BUILD_VECTOR: {
2785     EVT VT = N->getValueType(0);
2786     unsigned NumVectorElts = VT.getVectorNumElements();
2787     unsigned RegClassID;
2788     // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
2789     // that adds a 128 bits reg copy when going through TwoAddressInstructions
2790     // pass. We want to avoid 128 bits copies as much as possible because they
2791     // can't be bundled by our scheduler.
2792     switch(NumVectorElts) {
2793     case 2: RegClassID = R600::R600_Reg64RegClassID; break;
2794     case 4:
2795       if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
2796         RegClassID = R600::R600_Reg128VerticalRegClassID;
2797       else
2798         RegClassID = R600::R600_Reg128RegClassID;
2799       break;
2800     default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
2801     }
2802     SelectBuildVector(N, RegClassID);
2803     return;
2804   }
2805   }
2806 
2807   SelectCode(N);
2808 }
2809 
2810 bool R600DAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
2811                                           SDValue &Offset) {
2812   ConstantSDNode *C;
2813   SDLoc DL(Addr);
2814 
2815   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
2816     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
2817     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2818   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
2819              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
2820     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
2821     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2822   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
2823             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
2824     Base = Addr.getOperand(0);
2825     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2826   } else {
2827     Base = Addr;
2828     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
2829   }
2830 
2831   return true;
2832 }
2833 
2834 bool R600DAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
2835                                           SDValue &Offset) {
2836   ConstantSDNode *IMMOffset;
2837 
2838   if (Addr.getOpcode() == ISD::ADD
2839       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
2840       && isInt<16>(IMMOffset->getZExtValue())) {
2841 
2842       Base = Addr.getOperand(0);
2843       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
2844                                          MVT::i32);
2845       return true;
2846   // If the pointer address is constant, we can move it to the offset field.
2847   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
2848              && isInt<16>(IMMOffset->getZExtValue())) {
2849     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
2850                                   SDLoc(CurDAG->getEntryNode()),
2851                                   R600::ZERO, MVT::i32);
2852     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
2853                                        MVT::i32);
2854     return true;
2855   }
2856 
2857   // Default case, no offset
2858   Base = Addr;
2859   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
2860   return true;
2861 }
2862