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