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