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