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