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