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