xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision a156362e93eba9513611dc0989d516e9946cae48)
1 //===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
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 /// \file
8 //===----------------------------------------------------------------------===//
9 //
10 
11 #include "SIFoldOperands.h"
12 #include "AMDGPU.h"
13 #include "GCNSubtarget.h"
14 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
15 #include "SIMachineFunctionInfo.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineOperand.h"
19 
20 #define DEBUG_TYPE "si-fold-operands"
21 using namespace llvm;
22 
23 namespace {
24 
25 struct FoldCandidate {
26   MachineInstr *UseMI;
27   union {
28     MachineOperand *OpToFold;
29     uint64_t ImmToFold;
30     int FrameIndexToFold;
31   };
32   int ShrinkOpcode;
33   unsigned UseOpNo;
34   MachineOperand::MachineOperandType Kind;
35   bool Commuted;
36 
37   FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
38                 bool Commuted_ = false,
39                 int ShrinkOp = -1) :
40     UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
41     Kind(FoldOp->getType()),
42     Commuted(Commuted_) {
43     if (FoldOp->isImm()) {
44       ImmToFold = FoldOp->getImm();
45     } else if (FoldOp->isFI()) {
46       FrameIndexToFold = FoldOp->getIndex();
47     } else {
48       assert(FoldOp->isReg() || FoldOp->isGlobal());
49       OpToFold = FoldOp;
50     }
51   }
52 
53   bool isFI() const {
54     return Kind == MachineOperand::MO_FrameIndex;
55   }
56 
57   bool isImm() const {
58     return Kind == MachineOperand::MO_Immediate;
59   }
60 
61   bool isReg() const {
62     return Kind == MachineOperand::MO_Register;
63   }
64 
65   bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; }
66 
67   bool needsShrink() const { return ShrinkOpcode != -1; }
68 };
69 
70 class SIFoldOperandsImpl {
71 public:
72   MachineRegisterInfo *MRI;
73   const SIInstrInfo *TII;
74   const SIRegisterInfo *TRI;
75   const GCNSubtarget *ST;
76   const SIMachineFunctionInfo *MFI;
77 
78   bool frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
79                          const MachineOperand &OpToFold) const;
80 
81   bool updateOperand(FoldCandidate &Fold) const;
82 
83   bool canUseImmWithOpSel(FoldCandidate &Fold) const;
84 
85   bool tryFoldImmWithOpSel(FoldCandidate &Fold) const;
86 
87   bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
88                         MachineInstr *MI, unsigned OpNo,
89                         MachineOperand *OpToFold) const;
90   bool isUseSafeToFold(const MachineInstr &MI,
91                        const MachineOperand &UseMO) const;
92   bool
93   getRegSeqInit(SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
94                 Register UseReg, uint8_t OpTy) const;
95   bool tryToFoldACImm(const MachineOperand &OpToFold, MachineInstr *UseMI,
96                       unsigned UseOpIdx,
97                       SmallVectorImpl<FoldCandidate> &FoldList) const;
98   void foldOperand(MachineOperand &OpToFold,
99                    MachineInstr *UseMI,
100                    int UseOpIdx,
101                    SmallVectorImpl<FoldCandidate> &FoldList,
102                    SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
103 
104   MachineOperand *getImmOrMaterializedImm(MachineOperand &Op) const;
105   bool tryConstantFoldOp(MachineInstr *MI) const;
106   bool tryFoldCndMask(MachineInstr &MI) const;
107   bool tryFoldZeroHighBits(MachineInstr &MI) const;
108   bool foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
109   bool tryFoldFoldableCopy(MachineInstr &MI,
110                            MachineOperand *&CurrentKnownM0Val) const;
111 
112   const MachineOperand *isClamp(const MachineInstr &MI) const;
113   bool tryFoldClamp(MachineInstr &MI);
114 
115   std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
116   bool tryFoldOMod(MachineInstr &MI);
117   bool tryFoldRegSequence(MachineInstr &MI);
118   bool tryFoldPhiAGPR(MachineInstr &MI);
119   bool tryFoldLoad(MachineInstr &MI);
120 
121   bool tryOptimizeAGPRPhis(MachineBasicBlock &MBB);
122 
123 public:
124   SIFoldOperandsImpl() = default;
125 
126   bool run(MachineFunction &MF);
127 };
128 
129 class SIFoldOperandsLegacy : public MachineFunctionPass {
130 public:
131   static char ID;
132 
133   SIFoldOperandsLegacy() : MachineFunctionPass(ID) {}
134 
135   bool runOnMachineFunction(MachineFunction &MF) override {
136     if (skipFunction(MF.getFunction()))
137       return false;
138     return SIFoldOperandsImpl().run(MF);
139   }
140 
141   StringRef getPassName() const override { return "SI Fold Operands"; }
142 
143   void getAnalysisUsage(AnalysisUsage &AU) const override {
144     AU.setPreservesCFG();
145     MachineFunctionPass::getAnalysisUsage(AU);
146   }
147 };
148 
149 } // End anonymous namespace.
150 
151 INITIALIZE_PASS(SIFoldOperandsLegacy, DEBUG_TYPE, "SI Fold Operands", false,
152                 false)
153 
154 char SIFoldOperandsLegacy::ID = 0;
155 
156 char &llvm::SIFoldOperandsLegacyID = SIFoldOperandsLegacy::ID;
157 
158 static const TargetRegisterClass *getRegOpRC(const MachineRegisterInfo &MRI,
159                                              const TargetRegisterInfo &TRI,
160                                              const MachineOperand &MO) {
161   const TargetRegisterClass *RC = MRI.getRegClass(MO.getReg());
162   if (const TargetRegisterClass *SubRC =
163           TRI.getSubRegisterClass(RC, MO.getSubReg()))
164     RC = SubRC;
165   return RC;
166 }
167 
168 // Map multiply-accumulate opcode to corresponding multiply-add opcode if any.
169 static unsigned macToMad(unsigned Opc) {
170   switch (Opc) {
171   case AMDGPU::V_MAC_F32_e64:
172     return AMDGPU::V_MAD_F32_e64;
173   case AMDGPU::V_MAC_F16_e64:
174     return AMDGPU::V_MAD_F16_e64;
175   case AMDGPU::V_FMAC_F32_e64:
176     return AMDGPU::V_FMA_F32_e64;
177   case AMDGPU::V_FMAC_F16_e64:
178     return AMDGPU::V_FMA_F16_gfx9_e64;
179   case AMDGPU::V_FMAC_F16_t16_e64:
180     return AMDGPU::V_FMA_F16_gfx9_e64;
181   case AMDGPU::V_FMAC_LEGACY_F32_e64:
182     return AMDGPU::V_FMA_LEGACY_F32_e64;
183   case AMDGPU::V_FMAC_F64_e64:
184     return AMDGPU::V_FMA_F64_e64;
185   }
186   return AMDGPU::INSTRUCTION_LIST_END;
187 }
188 
189 // TODO: Add heuristic that the frame index might not fit in the addressing mode
190 // immediate offset to avoid materializing in loops.
191 bool SIFoldOperandsImpl::frameIndexMayFold(
192     const MachineInstr &UseMI, int OpNo, const MachineOperand &OpToFold) const {
193   if (!OpToFold.isFI())
194     return false;
195 
196   const unsigned Opc = UseMI.getOpcode();
197   switch (Opc) {
198   case AMDGPU::S_ADD_I32:
199   case AMDGPU::V_ADD_U32_e32:
200   case AMDGPU::V_ADD_CO_U32_e32:
201     // TODO: Possibly relax hasOneUse. It matters more for mubuf, since we have
202     // to insert the wave size shift at every point we use the index.
203     // TODO: Fix depending on visit order to fold immediates into the operand
204     return UseMI.getOperand(OpNo == 1 ? 2 : 1).isImm() &&
205            MRI->hasOneNonDBGUse(UseMI.getOperand(OpNo).getReg());
206   case AMDGPU::V_ADD_U32_e64:
207   case AMDGPU::V_ADD_CO_U32_e64:
208     return UseMI.getOperand(OpNo == 2 ? 3 : 2).isImm() &&
209            MRI->hasOneNonDBGUse(UseMI.getOperand(OpNo).getReg());
210   default:
211     break;
212   }
213 
214   if (TII->isMUBUF(UseMI))
215     return OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
216   if (!TII->isFLATScratch(UseMI))
217     return false;
218 
219   int SIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
220   if (OpNo == SIdx)
221     return true;
222 
223   int VIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
224   return OpNo == VIdx && SIdx == -1;
225 }
226 
227 FunctionPass *llvm::createSIFoldOperandsLegacyPass() {
228   return new SIFoldOperandsLegacy();
229 }
230 
231 bool SIFoldOperandsImpl::canUseImmWithOpSel(FoldCandidate &Fold) const {
232   MachineInstr *MI = Fold.UseMI;
233   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
234   const uint64_t TSFlags = MI->getDesc().TSFlags;
235 
236   assert(Old.isReg() && Fold.isImm());
237 
238   if (!(TSFlags & SIInstrFlags::IsPacked) || (TSFlags & SIInstrFlags::IsMAI) ||
239       (TSFlags & SIInstrFlags::IsWMMA) || (TSFlags & SIInstrFlags::IsSWMMAC) ||
240       (ST->hasDOTOpSelHazard() && (TSFlags & SIInstrFlags::IsDOT)))
241     return false;
242 
243   unsigned Opcode = MI->getOpcode();
244   int OpNo = MI->getOperandNo(&Old);
245   uint8_t OpType = TII->get(Opcode).operands()[OpNo].OperandType;
246   switch (OpType) {
247   default:
248     return false;
249   case AMDGPU::OPERAND_REG_IMM_V2FP16:
250   case AMDGPU::OPERAND_REG_IMM_V2BF16:
251   case AMDGPU::OPERAND_REG_IMM_V2INT16:
252   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
253   case AMDGPU::OPERAND_REG_INLINE_C_V2BF16:
254   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
255     break;
256   }
257 
258   return true;
259 }
260 
261 bool SIFoldOperandsImpl::tryFoldImmWithOpSel(FoldCandidate &Fold) const {
262   MachineInstr *MI = Fold.UseMI;
263   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
264   unsigned Opcode = MI->getOpcode();
265   int OpNo = MI->getOperandNo(&Old);
266   uint8_t OpType = TII->get(Opcode).operands()[OpNo].OperandType;
267 
268   // If the literal can be inlined as-is, apply it and short-circuit the
269   // tests below. The main motivation for this is to avoid unintuitive
270   // uses of opsel.
271   if (AMDGPU::isInlinableLiteralV216(Fold.ImmToFold, OpType)) {
272     Old.ChangeToImmediate(Fold.ImmToFold);
273     return true;
274   }
275 
276   // Refer to op_sel/op_sel_hi and check if we can change the immediate and
277   // op_sel in a way that allows an inline constant.
278   int ModIdx = -1;
279   unsigned SrcIdx = ~0;
280   if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0)) {
281     ModIdx = AMDGPU::OpName::src0_modifiers;
282     SrcIdx = 0;
283   } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1)) {
284     ModIdx = AMDGPU::OpName::src1_modifiers;
285     SrcIdx = 1;
286   } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2)) {
287     ModIdx = AMDGPU::OpName::src2_modifiers;
288     SrcIdx = 2;
289   }
290   assert(ModIdx != -1);
291   ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
292   MachineOperand &Mod = MI->getOperand(ModIdx);
293   unsigned ModVal = Mod.getImm();
294 
295   uint16_t ImmLo = static_cast<uint16_t>(
296       Fold.ImmToFold >> (ModVal & SISrcMods::OP_SEL_0 ? 16 : 0));
297   uint16_t ImmHi = static_cast<uint16_t>(
298       Fold.ImmToFold >> (ModVal & SISrcMods::OP_SEL_1 ? 16 : 0));
299   uint32_t Imm = (static_cast<uint32_t>(ImmHi) << 16) | ImmLo;
300   unsigned NewModVal = ModVal & ~(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1);
301 
302   // Helper function that attempts to inline the given value with a newly
303   // chosen opsel pattern.
304   auto tryFoldToInline = [&](uint32_t Imm) -> bool {
305     if (AMDGPU::isInlinableLiteralV216(Imm, OpType)) {
306       Mod.setImm(NewModVal | SISrcMods::OP_SEL_1);
307       Old.ChangeToImmediate(Imm);
308       return true;
309     }
310 
311     // Try to shuffle the halves around and leverage opsel to get an inline
312     // constant.
313     uint16_t Lo = static_cast<uint16_t>(Imm);
314     uint16_t Hi = static_cast<uint16_t>(Imm >> 16);
315     if (Lo == Hi) {
316       if (AMDGPU::isInlinableLiteralV216(Lo, OpType)) {
317         Mod.setImm(NewModVal);
318         Old.ChangeToImmediate(Lo);
319         return true;
320       }
321 
322       if (static_cast<int16_t>(Lo) < 0) {
323         int32_t SExt = static_cast<int16_t>(Lo);
324         if (AMDGPU::isInlinableLiteralV216(SExt, OpType)) {
325           Mod.setImm(NewModVal);
326           Old.ChangeToImmediate(SExt);
327           return true;
328         }
329       }
330 
331       // This check is only useful for integer instructions
332       if (OpType == AMDGPU::OPERAND_REG_IMM_V2INT16 ||
333           OpType == AMDGPU::OPERAND_REG_INLINE_AC_V2INT16) {
334         if (AMDGPU::isInlinableLiteralV216(Lo << 16, OpType)) {
335           Mod.setImm(NewModVal | SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1);
336           Old.ChangeToImmediate(static_cast<uint32_t>(Lo) << 16);
337           return true;
338         }
339       }
340     } else {
341       uint32_t Swapped = (static_cast<uint32_t>(Lo) << 16) | Hi;
342       if (AMDGPU::isInlinableLiteralV216(Swapped, OpType)) {
343         Mod.setImm(NewModVal | SISrcMods::OP_SEL_0);
344         Old.ChangeToImmediate(Swapped);
345         return true;
346       }
347     }
348 
349     return false;
350   };
351 
352   if (tryFoldToInline(Imm))
353     return true;
354 
355   // Replace integer addition by subtraction and vice versa if it allows
356   // folding the immediate to an inline constant.
357   //
358   // We should only ever get here for SrcIdx == 1 due to canonicalization
359   // earlier in the pipeline, but we double-check here to be safe / fully
360   // general.
361   bool IsUAdd = Opcode == AMDGPU::V_PK_ADD_U16;
362   bool IsUSub = Opcode == AMDGPU::V_PK_SUB_U16;
363   if (SrcIdx == 1 && (IsUAdd || IsUSub)) {
364     unsigned ClampIdx =
365         AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::clamp);
366     bool Clamp = MI->getOperand(ClampIdx).getImm() != 0;
367 
368     if (!Clamp) {
369       uint16_t NegLo = -static_cast<uint16_t>(Imm);
370       uint16_t NegHi = -static_cast<uint16_t>(Imm >> 16);
371       uint32_t NegImm = (static_cast<uint32_t>(NegHi) << 16) | NegLo;
372 
373       if (tryFoldToInline(NegImm)) {
374         unsigned NegOpcode =
375             IsUAdd ? AMDGPU::V_PK_SUB_U16 : AMDGPU::V_PK_ADD_U16;
376         MI->setDesc(TII->get(NegOpcode));
377         return true;
378       }
379     }
380   }
381 
382   return false;
383 }
384 
385 bool SIFoldOperandsImpl::updateOperand(FoldCandidate &Fold) const {
386   MachineInstr *MI = Fold.UseMI;
387   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
388   assert(Old.isReg());
389 
390   if (Fold.isImm() && canUseImmWithOpSel(Fold)) {
391     if (tryFoldImmWithOpSel(Fold))
392       return true;
393 
394     // We can't represent the candidate as an inline constant. Try as a literal
395     // with the original opsel, checking constant bus limitations.
396     MachineOperand New = MachineOperand::CreateImm(Fold.ImmToFold);
397     int OpNo = MI->getOperandNo(&Old);
398     if (!TII->isOperandLegal(*MI, OpNo, &New))
399       return false;
400     Old.ChangeToImmediate(Fold.ImmToFold);
401     return true;
402   }
403 
404   if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) {
405     MachineBasicBlock *MBB = MI->getParent();
406     auto Liveness = MBB->computeRegisterLiveness(TRI, AMDGPU::VCC, MI, 16);
407     if (Liveness != MachineBasicBlock::LQR_Dead) {
408       LLVM_DEBUG(dbgs() << "Not shrinking " << MI << " due to vcc liveness\n");
409       return false;
410     }
411 
412     int Op32 = Fold.ShrinkOpcode;
413     MachineOperand &Dst0 = MI->getOperand(0);
414     MachineOperand &Dst1 = MI->getOperand(1);
415     assert(Dst0.isDef() && Dst1.isDef());
416 
417     bool HaveNonDbgCarryUse = !MRI->use_nodbg_empty(Dst1.getReg());
418 
419     const TargetRegisterClass *Dst0RC = MRI->getRegClass(Dst0.getReg());
420     Register NewReg0 = MRI->createVirtualRegister(Dst0RC);
421 
422     MachineInstr *Inst32 = TII->buildShrunkInst(*MI, Op32);
423 
424     if (HaveNonDbgCarryUse) {
425       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::COPY),
426               Dst1.getReg())
427         .addReg(AMDGPU::VCC, RegState::Kill);
428     }
429 
430     // Keep the old instruction around to avoid breaking iterators, but
431     // replace it with a dummy instruction to remove uses.
432     //
433     // FIXME: We should not invert how this pass looks at operands to avoid
434     // this. Should track set of foldable movs instead of looking for uses
435     // when looking at a use.
436     Dst0.setReg(NewReg0);
437     for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
438       MI->removeOperand(I);
439     MI->setDesc(TII->get(AMDGPU::IMPLICIT_DEF));
440 
441     if (Fold.Commuted)
442       TII->commuteInstruction(*Inst32, false);
443     return true;
444   }
445 
446   assert(!Fold.needsShrink() && "not handled");
447 
448   if (Fold.isImm()) {
449     if (Old.isTied()) {
450       int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(MI->getOpcode());
451       if (NewMFMAOpc == -1)
452         return false;
453       MI->setDesc(TII->get(NewMFMAOpc));
454       MI->untieRegOperand(0);
455     }
456     Old.ChangeToImmediate(Fold.ImmToFold);
457     return true;
458   }
459 
460   if (Fold.isGlobal()) {
461     Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(),
462                    Fold.OpToFold->getTargetFlags());
463     return true;
464   }
465 
466   if (Fold.isFI()) {
467     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
468     return true;
469   }
470 
471   MachineOperand *New = Fold.OpToFold;
472   Old.substVirtReg(New->getReg(), New->getSubReg(), *TRI);
473   Old.setIsUndef(New->isUndef());
474   return true;
475 }
476 
477 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
478                               const MachineInstr *MI) {
479   return any_of(FoldList, [&](const auto &C) { return C.UseMI == MI; });
480 }
481 
482 static void appendFoldCandidate(SmallVectorImpl<FoldCandidate> &FoldList,
483                                 MachineInstr *MI, unsigned OpNo,
484                                 MachineOperand *FoldOp, bool Commuted = false,
485                                 int ShrinkOp = -1) {
486   // Skip additional folding on the same operand.
487   for (FoldCandidate &Fold : FoldList)
488     if (Fold.UseMI == MI && Fold.UseOpNo == OpNo)
489       return;
490   LLVM_DEBUG(dbgs() << "Append " << (Commuted ? "commuted" : "normal")
491                     << " operand " << OpNo << "\n  " << *MI);
492   FoldList.emplace_back(MI, OpNo, FoldOp, Commuted, ShrinkOp);
493 }
494 
495 bool SIFoldOperandsImpl::tryAddToFoldList(
496     SmallVectorImpl<FoldCandidate> &FoldList, MachineInstr *MI, unsigned OpNo,
497     MachineOperand *OpToFold) const {
498   const unsigned Opc = MI->getOpcode();
499 
500   auto tryToFoldAsFMAAKorMK = [&]() {
501     if (!OpToFold->isImm())
502       return false;
503 
504     const bool TryAK = OpNo == 3;
505     const unsigned NewOpc = TryAK ? AMDGPU::S_FMAAK_F32 : AMDGPU::S_FMAMK_F32;
506     MI->setDesc(TII->get(NewOpc));
507 
508     // We have to fold into operand which would be Imm not into OpNo.
509     bool FoldAsFMAAKorMK =
510         tryAddToFoldList(FoldList, MI, TryAK ? 3 : 2, OpToFold);
511     if (FoldAsFMAAKorMK) {
512       // Untie Src2 of fmac.
513       MI->untieRegOperand(3);
514       // For fmamk swap operands 1 and 2 if OpToFold was meant for operand 1.
515       if (OpNo == 1) {
516         MachineOperand &Op1 = MI->getOperand(1);
517         MachineOperand &Op2 = MI->getOperand(2);
518         Register OldReg = Op1.getReg();
519         // Operand 2 might be an inlinable constant
520         if (Op2.isImm()) {
521           Op1.ChangeToImmediate(Op2.getImm());
522           Op2.ChangeToRegister(OldReg, false);
523         } else {
524           Op1.setReg(Op2.getReg());
525           Op2.setReg(OldReg);
526         }
527       }
528       return true;
529     }
530     MI->setDesc(TII->get(Opc));
531     return false;
532   };
533 
534   bool IsLegal = TII->isOperandLegal(*MI, OpNo, OpToFold);
535   if (!IsLegal && OpToFold->isImm()) {
536     FoldCandidate Fold(MI, OpNo, OpToFold);
537     IsLegal = canUseImmWithOpSel(Fold);
538   }
539 
540   if (!IsLegal) {
541     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
542     unsigned NewOpc = macToMad(Opc);
543     if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
544       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
545       // to fold the operand.
546       MI->setDesc(TII->get(NewOpc));
547       bool AddOpSel = !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel) &&
548                       AMDGPU::hasNamedOperand(NewOpc, AMDGPU::OpName::op_sel);
549       if (AddOpSel)
550         MI->addOperand(MachineOperand::CreateImm(0));
551       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold);
552       if (FoldAsMAD) {
553         MI->untieRegOperand(OpNo);
554         return true;
555       }
556       if (AddOpSel)
557         MI->removeOperand(MI->getNumExplicitOperands() - 1);
558       MI->setDesc(TII->get(Opc));
559     }
560 
561     // Special case for s_fmac_f32 if we are trying to fold into Src2.
562     // By transforming into fmaak we can untie Src2 and make folding legal.
563     if (Opc == AMDGPU::S_FMAC_F32 && OpNo == 3) {
564       if (tryToFoldAsFMAAKorMK())
565         return true;
566     }
567 
568     // Special case for s_setreg_b32
569     if (OpToFold->isImm()) {
570       unsigned ImmOpc = 0;
571       if (Opc == AMDGPU::S_SETREG_B32)
572         ImmOpc = AMDGPU::S_SETREG_IMM32_B32;
573       else if (Opc == AMDGPU::S_SETREG_B32_mode)
574         ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode;
575       if (ImmOpc) {
576         MI->setDesc(TII->get(ImmOpc));
577         appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
578         return true;
579       }
580     }
581 
582     // If we are already folding into another operand of MI, then
583     // we can't commute the instruction, otherwise we risk making the
584     // other fold illegal.
585     if (isUseMIInFoldList(FoldList, MI))
586       return false;
587 
588     // Operand is not legal, so try to commute the instruction to
589     // see if this makes it possible to fold.
590     unsigned CommuteOpNo = TargetInstrInfo::CommuteAnyOperandIndex;
591     bool CanCommute = TII->findCommutedOpIndices(*MI, OpNo, CommuteOpNo);
592     if (!CanCommute)
593       return false;
594 
595     // One of operands might be an Imm operand, and OpNo may refer to it after
596     // the call of commuteInstruction() below. Such situations are avoided
597     // here explicitly as OpNo must be a register operand to be a candidate
598     // for memory folding.
599     if (!MI->getOperand(OpNo).isReg() || !MI->getOperand(CommuteOpNo).isReg())
600       return false;
601 
602     if (!TII->commuteInstruction(*MI, false, OpNo, CommuteOpNo))
603       return false;
604 
605     int Op32 = -1;
606     if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
607       if ((Opc != AMDGPU::V_ADD_CO_U32_e64 && Opc != AMDGPU::V_SUB_CO_U32_e64 &&
608            Opc != AMDGPU::V_SUBREV_CO_U32_e64) || // FIXME
609           (!OpToFold->isImm() && !OpToFold->isFI() && !OpToFold->isGlobal())) {
610         TII->commuteInstruction(*MI, false, OpNo, CommuteOpNo);
611         return false;
612       }
613 
614       // Verify the other operand is a VGPR, otherwise we would violate the
615       // constant bus restriction.
616       MachineOperand &OtherOp = MI->getOperand(OpNo);
617       if (!OtherOp.isReg() ||
618           !TII->getRegisterInfo().isVGPR(*MRI, OtherOp.getReg()))
619         return false;
620 
621       assert(MI->getOperand(1).isDef());
622 
623       // Make sure to get the 32-bit version of the commuted opcode.
624       unsigned MaybeCommutedOpc = MI->getOpcode();
625       Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
626     }
627 
628     appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true, Op32);
629     return true;
630   }
631 
632   // Inlineable constant might have been folded into Imm operand of fmaak or
633   // fmamk and we are trying to fold a non-inlinable constant.
634   if ((Opc == AMDGPU::S_FMAAK_F32 || Opc == AMDGPU::S_FMAMK_F32) &&
635       !OpToFold->isReg() && !TII->isInlineConstant(*OpToFold)) {
636     unsigned ImmIdx = Opc == AMDGPU::S_FMAAK_F32 ? 3 : 2;
637     MachineOperand &OpImm = MI->getOperand(ImmIdx);
638     if (!OpImm.isReg() &&
639         TII->isInlineConstant(*MI, MI->getOperand(OpNo), OpImm))
640       return tryToFoldAsFMAAKorMK();
641   }
642 
643   // Special case for s_fmac_f32 if we are trying to fold into Src0 or Src1.
644   // By changing into fmamk we can untie Src2.
645   // If folding for Src0 happens first and it is identical operand to Src1 we
646   // should avoid transforming into fmamk which requires commuting as it would
647   // cause folding into Src1 to fail later on due to wrong OpNo used.
648   if (Opc == AMDGPU::S_FMAC_F32 &&
649       (OpNo != 1 || !MI->getOperand(1).isIdenticalTo(MI->getOperand(2)))) {
650     if (tryToFoldAsFMAAKorMK())
651       return true;
652   }
653 
654   // Check the case where we might introduce a second constant operand to a
655   // scalar instruction
656   if (TII->isSALU(MI->getOpcode())) {
657     const MCInstrDesc &InstDesc = MI->getDesc();
658     const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
659 
660     // Fine if the operand can be encoded as an inline constant
661     if (!OpToFold->isReg() && !TII->isInlineConstant(*OpToFold, OpInfo)) {
662       // Otherwise check for another constant
663       for (unsigned i = 0, e = InstDesc.getNumOperands(); i != e; ++i) {
664         auto &Op = MI->getOperand(i);
665         if (OpNo != i && !Op.isReg() &&
666             !TII->isInlineConstant(Op, InstDesc.operands()[i]))
667           return false;
668       }
669     }
670   }
671 
672   appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
673   return true;
674 }
675 
676 bool SIFoldOperandsImpl::isUseSafeToFold(const MachineInstr &MI,
677                                          const MachineOperand &UseMO) const {
678   // Operands of SDWA instructions must be registers.
679   return !TII->isSDWA(MI);
680 }
681 
682 // Find a def of the UseReg, check if it is a reg_sequence and find initializers
683 // for each subreg, tracking it to foldable inline immediate if possible.
684 // Returns true on success.
685 bool SIFoldOperandsImpl::getRegSeqInit(
686     SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
687     Register UseReg, uint8_t OpTy) const {
688   MachineInstr *Def = MRI->getVRegDef(UseReg);
689   if (!Def || !Def->isRegSequence())
690     return false;
691 
692   for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) {
693     MachineOperand *Sub = &Def->getOperand(I);
694     assert(Sub->isReg());
695 
696     for (MachineInstr *SubDef = MRI->getVRegDef(Sub->getReg());
697          SubDef && Sub->isReg() && Sub->getReg().isVirtual() &&
698          !Sub->getSubReg() && TII->isFoldableCopy(*SubDef);
699          SubDef = MRI->getVRegDef(Sub->getReg())) {
700       MachineOperand *Op = &SubDef->getOperand(1);
701       if (Op->isImm()) {
702         if (TII->isInlineConstant(*Op, OpTy))
703           Sub = Op;
704         break;
705       }
706       if (!Op->isReg() || Op->getReg().isPhysical())
707         break;
708       Sub = Op;
709     }
710 
711     Defs.emplace_back(Sub, Def->getOperand(I + 1).getImm());
712   }
713 
714   return true;
715 }
716 
717 bool SIFoldOperandsImpl::tryToFoldACImm(
718     const MachineOperand &OpToFold, MachineInstr *UseMI, unsigned UseOpIdx,
719     SmallVectorImpl<FoldCandidate> &FoldList) const {
720   const MCInstrDesc &Desc = UseMI->getDesc();
721   if (UseOpIdx >= Desc.getNumOperands())
722     return false;
723 
724   if (!AMDGPU::isSISrcInlinableOperand(Desc, UseOpIdx))
725     return false;
726 
727   uint8_t OpTy = Desc.operands()[UseOpIdx].OperandType;
728   if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) &&
729       TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) {
730     UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm());
731     return true;
732   }
733 
734   if (!OpToFold.isReg())
735     return false;
736 
737   Register UseReg = OpToFold.getReg();
738   if (!UseReg.isVirtual())
739     return false;
740 
741   if (isUseMIInFoldList(FoldList, UseMI))
742     return false;
743 
744   // Maybe it is just a COPY of an immediate itself.
745   MachineInstr *Def = MRI->getVRegDef(UseReg);
746   MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
747   if (!UseOp.getSubReg() && Def && TII->isFoldableCopy(*Def)) {
748     MachineOperand &DefOp = Def->getOperand(1);
749     if (DefOp.isImm() && TII->isInlineConstant(DefOp, OpTy) &&
750         TII->isOperandLegal(*UseMI, UseOpIdx, &DefOp)) {
751       UseMI->getOperand(UseOpIdx).ChangeToImmediate(DefOp.getImm());
752       return true;
753     }
754   }
755 
756   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
757   if (!getRegSeqInit(Defs, UseReg, OpTy))
758     return false;
759 
760   int32_t Imm;
761   for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
762     const MachineOperand *Op = Defs[I].first;
763     if (!Op->isImm())
764       return false;
765 
766     auto SubImm = Op->getImm();
767     if (!I) {
768       Imm = SubImm;
769       if (!TII->isInlineConstant(*Op, OpTy) ||
770           !TII->isOperandLegal(*UseMI, UseOpIdx, Op))
771         return false;
772 
773       continue;
774     }
775     if (Imm != SubImm)
776       return false; // Can only fold splat constants
777   }
778 
779   appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first);
780   return true;
781 }
782 
783 void SIFoldOperandsImpl::foldOperand(
784     MachineOperand &OpToFold, MachineInstr *UseMI, int UseOpIdx,
785     SmallVectorImpl<FoldCandidate> &FoldList,
786     SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
787   const MachineOperand *UseOp = &UseMI->getOperand(UseOpIdx);
788 
789   if (!isUseSafeToFold(*UseMI, *UseOp))
790     return;
791 
792   // FIXME: Fold operands with subregs.
793   if (UseOp->isReg() && OpToFold.isReg() &&
794       (UseOp->isImplicit() || UseOp->getSubReg() != AMDGPU::NoSubRegister))
795     return;
796 
797   // Special case for REG_SEQUENCE: We can't fold literals into
798   // REG_SEQUENCE instructions, so we have to fold them into the
799   // uses of REG_SEQUENCE.
800   if (UseMI->isRegSequence()) {
801     Register RegSeqDstReg = UseMI->getOperand(0).getReg();
802     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
803 
804     // Grab the use operands first
805     SmallVector<MachineOperand *, 4> UsesToProcess;
806     for (auto &Use : MRI->use_nodbg_operands(RegSeqDstReg))
807       UsesToProcess.push_back(&Use);
808     for (auto *RSUse : UsesToProcess) {
809       MachineInstr *RSUseMI = RSUse->getParent();
810 
811       if (tryToFoldACImm(UseMI->getOperand(0), RSUseMI,
812                          RSUseMI->getOperandNo(RSUse), FoldList))
813         continue;
814 
815       if (RSUse->getSubReg() != RegSeqDstSubReg)
816         continue;
817 
818       foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(RSUse), FoldList,
819                   CopiesToReplace);
820     }
821     return;
822   }
823 
824   if (tryToFoldACImm(OpToFold, UseMI, UseOpIdx, FoldList))
825     return;
826 
827   if (frameIndexMayFold(*UseMI, UseOpIdx, OpToFold)) {
828     // Verify that this is a stack access.
829     // FIXME: Should probably use stack pseudos before frame lowering.
830 
831     if (TII->isMUBUF(*UseMI)) {
832       if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
833           MFI->getScratchRSrcReg())
834         return;
835 
836       // Ensure this is either relative to the current frame or the current
837       // wave.
838       MachineOperand &SOff =
839           *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
840       if (!SOff.isImm() || SOff.getImm() != 0)
841         return;
842     }
843 
844     // A frame index will resolve to a positive constant, so it should always be
845     // safe to fold the addressing mode, even pre-GFX9.
846     UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex());
847 
848     const unsigned Opc = UseMI->getOpcode();
849     if (TII->isFLATScratch(*UseMI) &&
850         AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vaddr) &&
851         !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::saddr)) {
852       unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(Opc);
853       UseMI->setDesc(TII->get(NewOpc));
854     }
855 
856     return;
857   }
858 
859   bool FoldingImmLike =
860       OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
861 
862   if (FoldingImmLike && UseMI->isCopy()) {
863     Register DestReg = UseMI->getOperand(0).getReg();
864     Register SrcReg = UseMI->getOperand(1).getReg();
865     assert(SrcReg.isVirtual());
866 
867     const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
868 
869     // Don't fold into a copy to a physical register with the same class. Doing
870     // so would interfere with the register coalescer's logic which would avoid
871     // redundant initializations.
872     if (DestReg.isPhysical() && SrcRC->contains(DestReg))
873       return;
874 
875     const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
876     if (!DestReg.isPhysical()) {
877       if (DestRC == &AMDGPU::AGPR_32RegClass &&
878           TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
879         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
880         UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
881         CopiesToReplace.push_back(UseMI);
882         return;
883       }
884     }
885 
886     // In order to fold immediates into copies, we need to change the
887     // copy to a MOV.
888 
889     unsigned MovOp = TII->getMovOpcode(DestRC);
890     if (MovOp == AMDGPU::COPY)
891       return;
892 
893     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
894     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
895     while (ImpOpI != ImpOpE) {
896       MachineInstr::mop_iterator Tmp = ImpOpI;
897       ImpOpI++;
898       UseMI->removeOperand(UseMI->getOperandNo(Tmp));
899     }
900     UseMI->setDesc(TII->get(MovOp));
901 
902     if (MovOp == AMDGPU::V_MOV_B16_t16_e64) {
903       const auto &SrcOp = UseMI->getOperand(UseOpIdx);
904       MachineOperand NewSrcOp(SrcOp);
905       MachineFunction *MF = UseMI->getParent()->getParent();
906       UseMI->removeOperand(1);
907       UseMI->addOperand(*MF, MachineOperand::CreateImm(0)); // src0_modifiers
908       UseMI->addOperand(NewSrcOp);                          // src0
909       UseMI->addOperand(*MF, MachineOperand::CreateImm(0)); // op_sel
910       UseOpIdx = 2;
911       UseOp = &UseMI->getOperand(UseOpIdx);
912     }
913     CopiesToReplace.push_back(UseMI);
914   } else {
915     if (UseMI->isCopy() && OpToFold.isReg() &&
916         UseMI->getOperand(0).getReg().isVirtual() &&
917         !UseMI->getOperand(1).getSubReg()) {
918       LLVM_DEBUG(dbgs() << "Folding " << OpToFold << "\n into " << *UseMI);
919       unsigned Size = TII->getOpSize(*UseMI, 1);
920       Register UseReg = OpToFold.getReg();
921       UseMI->getOperand(1).setReg(UseReg);
922       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
923       UseMI->getOperand(1).setIsKill(false);
924       CopiesToReplace.push_back(UseMI);
925       OpToFold.setIsKill(false);
926 
927       // Remove kill flags as kills may now be out of order with uses.
928       MRI->clearKillFlags(OpToFold.getReg());
929 
930       // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32
931       // can only accept VGPR or inline immediate. Recreate a reg_sequence with
932       // its initializers right here, so we will rematerialize immediates and
933       // avoid copies via different reg classes.
934       SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
935       if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
936           getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
937         const DebugLoc &DL = UseMI->getDebugLoc();
938         MachineBasicBlock &MBB = *UseMI->getParent();
939 
940         UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
941         for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I)
942           UseMI->removeOperand(I);
943 
944         MachineInstrBuilder B(*MBB.getParent(), UseMI);
945         DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
946         SmallSetVector<TargetInstrInfo::RegSubRegPair, 32> SeenAGPRs;
947         for (unsigned I = 0; I < Size / 4; ++I) {
948           MachineOperand *Def = Defs[I].first;
949           TargetInstrInfo::RegSubRegPair CopyToVGPR;
950           if (Def->isImm() &&
951               TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
952             int64_t Imm = Def->getImm();
953 
954             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
955             BuildMI(MBB, UseMI, DL,
956                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addImm(Imm);
957             B.addReg(Tmp);
958           } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) {
959             auto Src = getRegSubRegPair(*Def);
960             Def->setIsKill(false);
961             if (!SeenAGPRs.insert(Src)) {
962               // We cannot build a reg_sequence out of the same registers, they
963               // must be copied. Better do it here before copyPhysReg() created
964               // several reads to do the AGPR->VGPR->AGPR copy.
965               CopyToVGPR = Src;
966             } else {
967               B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0,
968                        Src.SubReg);
969             }
970           } else {
971             assert(Def->isReg());
972             Def->setIsKill(false);
973             auto Src = getRegSubRegPair(*Def);
974 
975             // Direct copy from SGPR to AGPR is not possible. To avoid creation
976             // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later,
977             // create a copy here and track if we already have such a copy.
978             if (TRI->isSGPRReg(*MRI, Src.Reg)) {
979               CopyToVGPR = Src;
980             } else {
981               auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
982               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def);
983               B.addReg(Tmp);
984             }
985           }
986 
987           if (CopyToVGPR.Reg) {
988             Register Vgpr;
989             if (VGPRCopies.count(CopyToVGPR)) {
990               Vgpr = VGPRCopies[CopyToVGPR];
991             } else {
992               Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
993               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def);
994               VGPRCopies[CopyToVGPR] = Vgpr;
995             }
996             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
997             BuildMI(MBB, UseMI, DL,
998                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addReg(Vgpr);
999             B.addReg(Tmp);
1000           }
1001 
1002           B.addImm(Defs[I].second);
1003         }
1004         LLVM_DEBUG(dbgs() << "Folded " << *UseMI);
1005         return;
1006       }
1007 
1008       if (Size != 4)
1009         return;
1010 
1011       Register Reg0 = UseMI->getOperand(0).getReg();
1012       Register Reg1 = UseMI->getOperand(1).getReg();
1013       if (TRI->isAGPR(*MRI, Reg0) && TRI->isVGPR(*MRI, Reg1))
1014         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
1015       else if (TRI->isVGPR(*MRI, Reg0) && TRI->isAGPR(*MRI, Reg1))
1016         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64));
1017       else if (ST->hasGFX90AInsts() && TRI->isAGPR(*MRI, Reg0) &&
1018                TRI->isAGPR(*MRI, Reg1))
1019         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_MOV_B32));
1020       return;
1021     }
1022 
1023     unsigned UseOpc = UseMI->getOpcode();
1024     if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
1025         (UseOpc == AMDGPU::V_READLANE_B32 &&
1026          (int)UseOpIdx ==
1027          AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
1028       // %vgpr = V_MOV_B32 imm
1029       // %sgpr = V_READFIRSTLANE_B32 %vgpr
1030       // =>
1031       // %sgpr = S_MOV_B32 imm
1032       if (FoldingImmLike) {
1033         if (execMayBeModifiedBeforeUse(*MRI,
1034                                        UseMI->getOperand(UseOpIdx).getReg(),
1035                                        *OpToFold.getParent(),
1036                                        *UseMI))
1037           return;
1038 
1039         UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
1040 
1041         if (OpToFold.isImm())
1042           UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
1043         else
1044           UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex());
1045         UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
1046         return;
1047       }
1048 
1049       if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
1050         if (execMayBeModifiedBeforeUse(*MRI,
1051                                        UseMI->getOperand(UseOpIdx).getReg(),
1052                                        *OpToFold.getParent(),
1053                                        *UseMI))
1054           return;
1055 
1056         // %vgpr = COPY %sgpr0
1057         // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
1058         // =>
1059         // %sgpr1 = COPY %sgpr0
1060         UseMI->setDesc(TII->get(AMDGPU::COPY));
1061         UseMI->getOperand(1).setReg(OpToFold.getReg());
1062         UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
1063         UseMI->getOperand(1).setIsKill(false);
1064         UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
1065         return;
1066       }
1067     }
1068 
1069     const MCInstrDesc &UseDesc = UseMI->getDesc();
1070 
1071     // Don't fold into target independent nodes.  Target independent opcodes
1072     // don't have defined register classes.
1073     if (UseDesc.isVariadic() || UseOp->isImplicit() ||
1074         UseDesc.operands()[UseOpIdx].RegClass == -1)
1075       return;
1076   }
1077 
1078   if (!FoldingImmLike) {
1079     if (OpToFold.isReg() && ST->needsAlignedVGPRs()) {
1080       // Don't fold if OpToFold doesn't hold an aligned register.
1081       const TargetRegisterClass *RC =
1082           TRI->getRegClassForReg(*MRI, OpToFold.getReg());
1083       assert(RC);
1084       if (TRI->hasVectorRegisters(RC) && OpToFold.getSubReg()) {
1085         unsigned SubReg = OpToFold.getSubReg();
1086         if (const TargetRegisterClass *SubRC =
1087                 TRI->getSubRegisterClass(RC, SubReg))
1088           RC = SubRC;
1089       }
1090 
1091       if (!RC || !TRI->isProperlyAlignedRC(*RC))
1092         return;
1093     }
1094 
1095     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold);
1096 
1097     // FIXME: We could try to change the instruction from 64-bit to 32-bit
1098     // to enable more folding opportunities.  The shrink operands pass
1099     // already does this.
1100     return;
1101   }
1102 
1103 
1104   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
1105   const TargetRegisterClass *FoldRC =
1106       TRI->getRegClass(FoldDesc.operands()[0].RegClass);
1107 
1108   // Split 64-bit constants into 32-bits for folding.
1109   if (UseOp->getSubReg() && AMDGPU::getRegBitWidth(*FoldRC) == 64) {
1110     Register UseReg = UseOp->getReg();
1111     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
1112     if (AMDGPU::getRegBitWidth(*UseRC) != 64)
1113       return;
1114 
1115     APInt Imm(64, OpToFold.getImm());
1116     if (UseOp->getSubReg() == AMDGPU::sub0) {
1117       Imm = Imm.getLoBits(32);
1118     } else {
1119       assert(UseOp->getSubReg() == AMDGPU::sub1);
1120       Imm = Imm.getHiBits(32);
1121     }
1122 
1123     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
1124     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp);
1125     return;
1126   }
1127 
1128   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold);
1129 }
1130 
1131 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
1132                                   uint32_t LHS, uint32_t RHS) {
1133   switch (Opcode) {
1134   case AMDGPU::V_AND_B32_e64:
1135   case AMDGPU::V_AND_B32_e32:
1136   case AMDGPU::S_AND_B32:
1137     Result = LHS & RHS;
1138     return true;
1139   case AMDGPU::V_OR_B32_e64:
1140   case AMDGPU::V_OR_B32_e32:
1141   case AMDGPU::S_OR_B32:
1142     Result = LHS | RHS;
1143     return true;
1144   case AMDGPU::V_XOR_B32_e64:
1145   case AMDGPU::V_XOR_B32_e32:
1146   case AMDGPU::S_XOR_B32:
1147     Result = LHS ^ RHS;
1148     return true;
1149   case AMDGPU::S_XNOR_B32:
1150     Result = ~(LHS ^ RHS);
1151     return true;
1152   case AMDGPU::S_NAND_B32:
1153     Result = ~(LHS & RHS);
1154     return true;
1155   case AMDGPU::S_NOR_B32:
1156     Result = ~(LHS | RHS);
1157     return true;
1158   case AMDGPU::S_ANDN2_B32:
1159     Result = LHS & ~RHS;
1160     return true;
1161   case AMDGPU::S_ORN2_B32:
1162     Result = LHS | ~RHS;
1163     return true;
1164   case AMDGPU::V_LSHL_B32_e64:
1165   case AMDGPU::V_LSHL_B32_e32:
1166   case AMDGPU::S_LSHL_B32:
1167     // The instruction ignores the high bits for out of bounds shifts.
1168     Result = LHS << (RHS & 31);
1169     return true;
1170   case AMDGPU::V_LSHLREV_B32_e64:
1171   case AMDGPU::V_LSHLREV_B32_e32:
1172     Result = RHS << (LHS & 31);
1173     return true;
1174   case AMDGPU::V_LSHR_B32_e64:
1175   case AMDGPU::V_LSHR_B32_e32:
1176   case AMDGPU::S_LSHR_B32:
1177     Result = LHS >> (RHS & 31);
1178     return true;
1179   case AMDGPU::V_LSHRREV_B32_e64:
1180   case AMDGPU::V_LSHRREV_B32_e32:
1181     Result = RHS >> (LHS & 31);
1182     return true;
1183   case AMDGPU::V_ASHR_I32_e64:
1184   case AMDGPU::V_ASHR_I32_e32:
1185   case AMDGPU::S_ASHR_I32:
1186     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
1187     return true;
1188   case AMDGPU::V_ASHRREV_I32_e64:
1189   case AMDGPU::V_ASHRREV_I32_e32:
1190     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
1191     return true;
1192   default:
1193     return false;
1194   }
1195 }
1196 
1197 static unsigned getMovOpc(bool IsScalar) {
1198   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1199 }
1200 
1201 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
1202   MI.setDesc(NewDesc);
1203 
1204   // Remove any leftover implicit operands from mutating the instruction. e.g.
1205   // if we replace an s_and_b32 with a copy, we don't need the implicit scc def
1206   // anymore.
1207   const MCInstrDesc &Desc = MI.getDesc();
1208   unsigned NumOps = Desc.getNumOperands() + Desc.implicit_uses().size() +
1209                     Desc.implicit_defs().size();
1210 
1211   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
1212     MI.removeOperand(I);
1213 }
1214 
1215 MachineOperand *
1216 SIFoldOperandsImpl::getImmOrMaterializedImm(MachineOperand &Op) const {
1217   // If this has a subregister, it obviously is a register source.
1218   if (!Op.isReg() || Op.getSubReg() != AMDGPU::NoSubRegister ||
1219       !Op.getReg().isVirtual())
1220     return &Op;
1221 
1222   MachineInstr *Def = MRI->getVRegDef(Op.getReg());
1223   if (Def && Def->isMoveImmediate()) {
1224     MachineOperand &ImmSrc = Def->getOperand(1);
1225     if (ImmSrc.isImm())
1226       return &ImmSrc;
1227   }
1228 
1229   return &Op;
1230 }
1231 
1232 // Try to simplify operations with a constant that may appear after instruction
1233 // selection.
1234 // TODO: See if a frame index with a fixed offset can fold.
1235 bool SIFoldOperandsImpl::tryConstantFoldOp(MachineInstr *MI) const {
1236   if (!MI->allImplicitDefsAreDead())
1237     return false;
1238 
1239   unsigned Opc = MI->getOpcode();
1240 
1241   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1242   if (Src0Idx == -1)
1243     return false;
1244   MachineOperand *Src0 = getImmOrMaterializedImm(MI->getOperand(Src0Idx));
1245 
1246   if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1247        Opc == AMDGPU::S_NOT_B32) &&
1248       Src0->isImm()) {
1249     MI->getOperand(1).ChangeToImmediate(~Src0->getImm());
1250     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1251     return true;
1252   }
1253 
1254   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1255   if (Src1Idx == -1)
1256     return false;
1257   MachineOperand *Src1 = getImmOrMaterializedImm(MI->getOperand(Src1Idx));
1258 
1259   if (!Src0->isImm() && !Src1->isImm())
1260     return false;
1261 
1262   // and k0, k1 -> v_mov_b32 (k0 & k1)
1263   // or k0, k1 -> v_mov_b32 (k0 | k1)
1264   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1265   if (Src0->isImm() && Src1->isImm()) {
1266     int32_t NewImm;
1267     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
1268       return false;
1269 
1270     bool IsSGPR = TRI->isSGPRReg(*MRI, MI->getOperand(0).getReg());
1271 
1272     // Be careful to change the right operand, src0 may belong to a different
1273     // instruction.
1274     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1275     MI->removeOperand(Src1Idx);
1276     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1277     return true;
1278   }
1279 
1280   if (!MI->isCommutable())
1281     return false;
1282 
1283   if (Src0->isImm() && !Src1->isImm()) {
1284     std::swap(Src0, Src1);
1285     std::swap(Src0Idx, Src1Idx);
1286   }
1287 
1288   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
1289   if (Opc == AMDGPU::V_OR_B32_e64 ||
1290       Opc == AMDGPU::V_OR_B32_e32 ||
1291       Opc == AMDGPU::S_OR_B32) {
1292     if (Src1Val == 0) {
1293       // y = or x, 0 => y = copy x
1294       MI->removeOperand(Src1Idx);
1295       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1296     } else if (Src1Val == -1) {
1297       // y = or x, -1 => y = v_mov_b32 -1
1298       MI->removeOperand(Src1Idx);
1299       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1300     } else
1301       return false;
1302 
1303     return true;
1304   }
1305 
1306   if (Opc == AMDGPU::V_AND_B32_e64 || Opc == AMDGPU::V_AND_B32_e32 ||
1307       Opc == AMDGPU::S_AND_B32) {
1308     if (Src1Val == 0) {
1309       // y = and x, 0 => y = v_mov_b32 0
1310       MI->removeOperand(Src0Idx);
1311       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1312     } else if (Src1Val == -1) {
1313       // y = and x, -1 => y = copy x
1314       MI->removeOperand(Src1Idx);
1315       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1316     } else
1317       return false;
1318 
1319     return true;
1320   }
1321 
1322   if (Opc == AMDGPU::V_XOR_B32_e64 || Opc == AMDGPU::V_XOR_B32_e32 ||
1323       Opc == AMDGPU::S_XOR_B32) {
1324     if (Src1Val == 0) {
1325       // y = xor x, 0 => y = copy x
1326       MI->removeOperand(Src1Idx);
1327       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1328       return true;
1329     }
1330   }
1331 
1332   return false;
1333 }
1334 
1335 // Try to fold an instruction into a simpler one
1336 bool SIFoldOperandsImpl::tryFoldCndMask(MachineInstr &MI) const {
1337   unsigned Opc = MI.getOpcode();
1338   if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1339       Opc != AMDGPU::V_CNDMASK_B64_PSEUDO)
1340     return false;
1341 
1342   MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1343   MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1344   if (!Src1->isIdenticalTo(*Src0)) {
1345     auto *Src0Imm = getImmOrMaterializedImm(*Src0);
1346     auto *Src1Imm = getImmOrMaterializedImm(*Src1);
1347     if (!Src1Imm->isIdenticalTo(*Src0Imm))
1348       return false;
1349   }
1350 
1351   int Src1ModIdx =
1352       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1353   int Src0ModIdx =
1354       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1355   if ((Src1ModIdx != -1 && MI.getOperand(Src1ModIdx).getImm() != 0) ||
1356       (Src0ModIdx != -1 && MI.getOperand(Src0ModIdx).getImm() != 0))
1357     return false;
1358 
1359   LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1360   auto &NewDesc =
1361       TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1362   int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1363   if (Src2Idx != -1)
1364     MI.removeOperand(Src2Idx);
1365   MI.removeOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1366   if (Src1ModIdx != -1)
1367     MI.removeOperand(Src1ModIdx);
1368   if (Src0ModIdx != -1)
1369     MI.removeOperand(Src0ModIdx);
1370   mutateCopyOp(MI, NewDesc);
1371   LLVM_DEBUG(dbgs() << MI);
1372   return true;
1373 }
1374 
1375 bool SIFoldOperandsImpl::tryFoldZeroHighBits(MachineInstr &MI) const {
1376   if (MI.getOpcode() != AMDGPU::V_AND_B32_e64 &&
1377       MI.getOpcode() != AMDGPU::V_AND_B32_e32)
1378     return false;
1379 
1380   MachineOperand *Src0 = getImmOrMaterializedImm(MI.getOperand(1));
1381   if (!Src0->isImm() || Src0->getImm() != 0xffff)
1382     return false;
1383 
1384   Register Src1 = MI.getOperand(2).getReg();
1385   MachineInstr *SrcDef = MRI->getVRegDef(Src1);
1386   if (!ST->zeroesHigh16BitsOfDest(SrcDef->getOpcode()))
1387     return false;
1388 
1389   Register Dst = MI.getOperand(0).getReg();
1390   MRI->replaceRegWith(Dst, Src1);
1391   if (!MI.getOperand(2).isKill())
1392     MRI->clearKillFlags(Src1);
1393   MI.eraseFromParent();
1394   return true;
1395 }
1396 
1397 bool SIFoldOperandsImpl::foldInstOperand(MachineInstr &MI,
1398                                          MachineOperand &OpToFold) const {
1399   // We need mutate the operands of new mov instructions to add implicit
1400   // uses of EXEC, but adding them invalidates the use_iterator, so defer
1401   // this.
1402   SmallVector<MachineInstr *, 4> CopiesToReplace;
1403   SmallVector<FoldCandidate, 4> FoldList;
1404   MachineOperand &Dst = MI.getOperand(0);
1405   bool Changed = false;
1406 
1407   if (OpToFold.isImm()) {
1408     for (auto &UseMI :
1409          make_early_inc_range(MRI->use_nodbg_instructions(Dst.getReg()))) {
1410       // Folding the immediate may reveal operations that can be constant
1411       // folded or replaced with a copy. This can happen for example after
1412       // frame indices are lowered to constants or from splitting 64-bit
1413       // constants.
1414       //
1415       // We may also encounter cases where one or both operands are
1416       // immediates materialized into a register, which would ordinarily not
1417       // be folded due to multiple uses or operand constraints.
1418       if (tryConstantFoldOp(&UseMI)) {
1419         LLVM_DEBUG(dbgs() << "Constant folded " << UseMI);
1420         Changed = true;
1421       }
1422     }
1423   }
1424 
1425   SmallVector<MachineOperand *, 4> UsesToProcess;
1426   for (auto &Use : MRI->use_nodbg_operands(Dst.getReg()))
1427     UsesToProcess.push_back(&Use);
1428   for (auto *U : UsesToProcess) {
1429     MachineInstr *UseMI = U->getParent();
1430     foldOperand(OpToFold, UseMI, UseMI->getOperandNo(U), FoldList,
1431                 CopiesToReplace);
1432   }
1433 
1434   if (CopiesToReplace.empty() && FoldList.empty())
1435     return Changed;
1436 
1437   MachineFunction *MF = MI.getParent()->getParent();
1438   // Make sure we add EXEC uses to any new v_mov instructions created.
1439   for (MachineInstr *Copy : CopiesToReplace)
1440     Copy->addImplicitDefUseOperands(*MF);
1441 
1442   for (FoldCandidate &Fold : FoldList) {
1443     assert(!Fold.isReg() || Fold.OpToFold);
1444     if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) {
1445       Register Reg = Fold.OpToFold->getReg();
1446       MachineInstr *DefMI = Fold.OpToFold->getParent();
1447       if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1448           execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1449         continue;
1450     }
1451     if (updateOperand(Fold)) {
1452       // Clear kill flags.
1453       if (Fold.isReg()) {
1454         assert(Fold.OpToFold && Fold.OpToFold->isReg());
1455         // FIXME: Probably shouldn't bother trying to fold if not an
1456         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1457         // copies.
1458         MRI->clearKillFlags(Fold.OpToFold->getReg());
1459       }
1460       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1461                         << static_cast<int>(Fold.UseOpNo) << " of "
1462                         << *Fold.UseMI);
1463     } else if (Fold.Commuted) {
1464       // Restoring instruction's original operand order if fold has failed.
1465       TII->commuteInstruction(*Fold.UseMI, false);
1466     }
1467   }
1468   return true;
1469 }
1470 
1471 bool SIFoldOperandsImpl::tryFoldFoldableCopy(
1472     MachineInstr &MI, MachineOperand *&CurrentKnownM0Val) const {
1473   // Specially track simple redefs of m0 to the same value in a block, so we
1474   // can erase the later ones.
1475   if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1476     MachineOperand &NewM0Val = MI.getOperand(1);
1477     if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1478       MI.eraseFromParent();
1479       return true;
1480     }
1481 
1482     // We aren't tracking other physical registers
1483     CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical())
1484                             ? nullptr
1485                             : &NewM0Val;
1486     return false;
1487   }
1488 
1489   MachineOperand *OpToFoldPtr;
1490   if (MI.getOpcode() == AMDGPU::V_MOV_B16_t16_e64) {
1491     // Folding when any src_modifiers are non-zero is unsupported
1492     if (TII->hasAnyModifiersSet(MI))
1493       return false;
1494     OpToFoldPtr = &MI.getOperand(2);
1495   } else
1496     OpToFoldPtr = &MI.getOperand(1);
1497   MachineOperand &OpToFold = *OpToFoldPtr;
1498   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1499 
1500   // FIXME: We could also be folding things like TargetIndexes.
1501   if (!FoldingImm && !OpToFold.isReg())
1502     return false;
1503 
1504   if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1505     return false;
1506 
1507   // Prevent folding operands backwards in the function. For example,
1508   // the COPY opcode must not be replaced by 1 in this example:
1509   //
1510   //    %3 = COPY %vgpr0; VGPR_32:%3
1511   //    ...
1512   //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1513   if (!MI.getOperand(0).getReg().isVirtual())
1514     return false;
1515 
1516   bool Changed = foldInstOperand(MI, OpToFold);
1517 
1518   // If we managed to fold all uses of this copy then we might as well
1519   // delete it now.
1520   // The only reason we need to follow chains of copies here is that
1521   // tryFoldRegSequence looks forward through copies before folding a
1522   // REG_SEQUENCE into its eventual users.
1523   auto *InstToErase = &MI;
1524   while (MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1525     auto &SrcOp = InstToErase->getOperand(1);
1526     auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
1527     InstToErase->eraseFromParent();
1528     Changed = true;
1529     InstToErase = nullptr;
1530     if (!SrcReg || SrcReg.isPhysical())
1531       break;
1532     InstToErase = MRI->getVRegDef(SrcReg);
1533     if (!InstToErase || !TII->isFoldableCopy(*InstToErase))
1534       break;
1535   }
1536 
1537   if (InstToErase && InstToErase->isRegSequence() &&
1538       MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1539     InstToErase->eraseFromParent();
1540     Changed = true;
1541   }
1542 
1543   return Changed;
1544 }
1545 
1546 // Clamp patterns are canonically selected to v_max_* instructions, so only
1547 // handle them.
1548 const MachineOperand *
1549 SIFoldOperandsImpl::isClamp(const MachineInstr &MI) const {
1550   unsigned Op = MI.getOpcode();
1551   switch (Op) {
1552   case AMDGPU::V_MAX_F32_e64:
1553   case AMDGPU::V_MAX_F16_e64:
1554   case AMDGPU::V_MAX_F16_t16_e64:
1555   case AMDGPU::V_MAX_F16_fake16_e64:
1556   case AMDGPU::V_MAX_F64_e64:
1557   case AMDGPU::V_MAX_NUM_F64_e64:
1558   case AMDGPU::V_PK_MAX_F16: {
1559     if (MI.mayRaiseFPException())
1560       return nullptr;
1561 
1562     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1563       return nullptr;
1564 
1565     // Make sure sources are identical.
1566     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1567     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1568     if (!Src0->isReg() || !Src1->isReg() ||
1569         Src0->getReg() != Src1->getReg() ||
1570         Src0->getSubReg() != Src1->getSubReg() ||
1571         Src0->getSubReg() != AMDGPU::NoSubRegister)
1572       return nullptr;
1573 
1574     // Can't fold up if we have modifiers.
1575     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1576       return nullptr;
1577 
1578     unsigned Src0Mods
1579       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1580     unsigned Src1Mods
1581       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1582 
1583     // Having a 0 op_sel_hi would require swizzling the output in the source
1584     // instruction, which we can't do.
1585     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1586                                                       : 0u;
1587     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1588       return nullptr;
1589     return Src0;
1590   }
1591   default:
1592     return nullptr;
1593   }
1594 }
1595 
1596 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1597 bool SIFoldOperandsImpl::tryFoldClamp(MachineInstr &MI) {
1598   const MachineOperand *ClampSrc = isClamp(MI);
1599   if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
1600     return false;
1601 
1602   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1603 
1604   // The type of clamp must be compatible.
1605   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1606     return false;
1607 
1608   if (Def->mayRaiseFPException())
1609     return false;
1610 
1611   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1612   if (!DefClamp)
1613     return false;
1614 
1615   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
1616 
1617   // Clamp is applied after omod, so it is OK if omod is set.
1618   DefClamp->setImm(1);
1619 
1620   Register DefReg = Def->getOperand(0).getReg();
1621   Register MIDstReg = MI.getOperand(0).getReg();
1622   if (TRI->isSGPRReg(*MRI, DefReg)) {
1623     // Pseudo scalar instructions have a SGPR for dst and clamp is a v_max*
1624     // instruction with a VGPR dst.
1625     BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
1626             MIDstReg)
1627         .addReg(DefReg);
1628   } else {
1629     MRI->replaceRegWith(MIDstReg, DefReg);
1630   }
1631   MI.eraseFromParent();
1632 
1633   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1634   // instruction, so we might as well convert it to the more flexible VOP3-only
1635   // mad/fma form.
1636   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1637     Def->eraseFromParent();
1638 
1639   return true;
1640 }
1641 
1642 static int getOModValue(unsigned Opc, int64_t Val) {
1643   switch (Opc) {
1644   case AMDGPU::V_MUL_F64_e64:
1645   case AMDGPU::V_MUL_F64_pseudo_e64: {
1646     switch (Val) {
1647     case 0x3fe0000000000000: // 0.5
1648       return SIOutMods::DIV2;
1649     case 0x4000000000000000: // 2.0
1650       return SIOutMods::MUL2;
1651     case 0x4010000000000000: // 4.0
1652       return SIOutMods::MUL4;
1653     default:
1654       return SIOutMods::NONE;
1655     }
1656   }
1657   case AMDGPU::V_MUL_F32_e64: {
1658     switch (static_cast<uint32_t>(Val)) {
1659     case 0x3f000000: // 0.5
1660       return SIOutMods::DIV2;
1661     case 0x40000000: // 2.0
1662       return SIOutMods::MUL2;
1663     case 0x40800000: // 4.0
1664       return SIOutMods::MUL4;
1665     default:
1666       return SIOutMods::NONE;
1667     }
1668   }
1669   case AMDGPU::V_MUL_F16_e64:
1670   case AMDGPU::V_MUL_F16_t16_e64:
1671   case AMDGPU::V_MUL_F16_fake16_e64: {
1672     switch (static_cast<uint16_t>(Val)) {
1673     case 0x3800: // 0.5
1674       return SIOutMods::DIV2;
1675     case 0x4000: // 2.0
1676       return SIOutMods::MUL2;
1677     case 0x4400: // 4.0
1678       return SIOutMods::MUL4;
1679     default:
1680       return SIOutMods::NONE;
1681     }
1682   }
1683   default:
1684     llvm_unreachable("invalid mul opcode");
1685   }
1686 }
1687 
1688 // FIXME: Does this really not support denormals with f16?
1689 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1690 // handled, so will anything other than that break?
1691 std::pair<const MachineOperand *, int>
1692 SIFoldOperandsImpl::isOMod(const MachineInstr &MI) const {
1693   unsigned Op = MI.getOpcode();
1694   switch (Op) {
1695   case AMDGPU::V_MUL_F64_e64:
1696   case AMDGPU::V_MUL_F64_pseudo_e64:
1697   case AMDGPU::V_MUL_F32_e64:
1698   case AMDGPU::V_MUL_F16_t16_e64:
1699   case AMDGPU::V_MUL_F16_fake16_e64:
1700   case AMDGPU::V_MUL_F16_e64: {
1701     // If output denormals are enabled, omod is ignored.
1702     if ((Op == AMDGPU::V_MUL_F32_e64 &&
1703          MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
1704         ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F64_pseudo_e64 ||
1705           Op == AMDGPU::V_MUL_F16_e64 || Op == AMDGPU::V_MUL_F16_t16_e64 ||
1706           Op == AMDGPU::V_MUL_F16_fake16_e64) &&
1707          MFI->getMode().FP64FP16Denormals.Output !=
1708              DenormalMode::PreserveSign) ||
1709         MI.mayRaiseFPException())
1710       return std::pair(nullptr, SIOutMods::NONE);
1711 
1712     const MachineOperand *RegOp = nullptr;
1713     const MachineOperand *ImmOp = nullptr;
1714     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1715     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1716     if (Src0->isImm()) {
1717       ImmOp = Src0;
1718       RegOp = Src1;
1719     } else if (Src1->isImm()) {
1720       ImmOp = Src1;
1721       RegOp = Src0;
1722     } else
1723       return std::pair(nullptr, SIOutMods::NONE);
1724 
1725     int OMod = getOModValue(Op, ImmOp->getImm());
1726     if (OMod == SIOutMods::NONE ||
1727         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1728         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1729         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1730         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1731       return std::pair(nullptr, SIOutMods::NONE);
1732 
1733     return std::pair(RegOp, OMod);
1734   }
1735   case AMDGPU::V_ADD_F64_e64:
1736   case AMDGPU::V_ADD_F64_pseudo_e64:
1737   case AMDGPU::V_ADD_F32_e64:
1738   case AMDGPU::V_ADD_F16_e64:
1739   case AMDGPU::V_ADD_F16_t16_e64:
1740   case AMDGPU::V_ADD_F16_fake16_e64: {
1741     // If output denormals are enabled, omod is ignored.
1742     if ((Op == AMDGPU::V_ADD_F32_e64 &&
1743          MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
1744         ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F64_pseudo_e64 ||
1745           Op == AMDGPU::V_ADD_F16_e64 || Op == AMDGPU::V_ADD_F16_t16_e64 ||
1746           Op == AMDGPU::V_ADD_F16_fake16_e64) &&
1747          MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
1748       return std::pair(nullptr, SIOutMods::NONE);
1749 
1750     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1751     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1752     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1753 
1754     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1755         Src0->getSubReg() == Src1->getSubReg() &&
1756         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1757         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1758         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1759         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1760       return std::pair(Src0, SIOutMods::MUL2);
1761 
1762     return std::pair(nullptr, SIOutMods::NONE);
1763   }
1764   default:
1765     return std::pair(nullptr, SIOutMods::NONE);
1766   }
1767 }
1768 
1769 // FIXME: Does this need to check IEEE bit on function?
1770 bool SIFoldOperandsImpl::tryFoldOMod(MachineInstr &MI) {
1771   const MachineOperand *RegOp;
1772   int OMod;
1773   std::tie(RegOp, OMod) = isOMod(MI);
1774   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1775       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1776       !MRI->hasOneNonDBGUser(RegOp->getReg()))
1777     return false;
1778 
1779   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1780   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1781   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1782     return false;
1783 
1784   if (Def->mayRaiseFPException())
1785     return false;
1786 
1787   // Clamp is applied after omod. If the source already has clamp set, don't
1788   // fold it.
1789   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1790     return false;
1791 
1792   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
1793 
1794   DefOMod->setImm(OMod);
1795   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1796   // Kill flags can be wrong if we replaced a def inside a loop with a def
1797   // outside the loop.
1798   MRI->clearKillFlags(Def->getOperand(0).getReg());
1799   MI.eraseFromParent();
1800 
1801   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1802   // instruction, so we might as well convert it to the more flexible VOP3-only
1803   // mad/fma form.
1804   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1805     Def->eraseFromParent();
1806 
1807   return true;
1808 }
1809 
1810 // Try to fold a reg_sequence with vgpr output and agpr inputs into an
1811 // instruction which can take an agpr. So far that means a store.
1812 bool SIFoldOperandsImpl::tryFoldRegSequence(MachineInstr &MI) {
1813   assert(MI.isRegSequence());
1814   auto Reg = MI.getOperand(0).getReg();
1815 
1816   if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
1817       !MRI->hasOneNonDBGUse(Reg))
1818     return false;
1819 
1820   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
1821   if (!getRegSeqInit(Defs, Reg, MCOI::OPERAND_REGISTER))
1822     return false;
1823 
1824   for (auto &[Op, SubIdx] : Defs) {
1825     if (!Op->isReg())
1826       return false;
1827     if (TRI->isAGPR(*MRI, Op->getReg()))
1828       continue;
1829     // Maybe this is a COPY from AREG
1830     const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
1831     if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
1832       return false;
1833     if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
1834       return false;
1835   }
1836 
1837   MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
1838   MachineInstr *UseMI = Op->getParent();
1839   while (UseMI->isCopy() && !Op->getSubReg()) {
1840     Reg = UseMI->getOperand(0).getReg();
1841     if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
1842       return false;
1843     Op = &*MRI->use_nodbg_begin(Reg);
1844     UseMI = Op->getParent();
1845   }
1846 
1847   if (Op->getSubReg())
1848     return false;
1849 
1850   unsigned OpIdx = Op - &UseMI->getOperand(0);
1851   const MCInstrDesc &InstDesc = UseMI->getDesc();
1852   const TargetRegisterClass *OpRC =
1853       TII->getRegClass(InstDesc, OpIdx, TRI, *MI.getMF());
1854   if (!OpRC || !TRI->isVectorSuperClass(OpRC))
1855     return false;
1856 
1857   const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
1858   auto Dst = MRI->createVirtualRegister(NewDstRC);
1859   auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1860                     TII->get(AMDGPU::REG_SEQUENCE), Dst);
1861 
1862   for (auto &[Def, SubIdx] : Defs) {
1863     Def->setIsKill(false);
1864     if (TRI->isAGPR(*MRI, Def->getReg())) {
1865       RS.add(*Def);
1866     } else { // This is a copy
1867       MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
1868       SubDef->getOperand(1).setIsKill(false);
1869       RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
1870     }
1871     RS.addImm(SubIdx);
1872   }
1873 
1874   Op->setReg(Dst);
1875   if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
1876     Op->setReg(Reg);
1877     RS->eraseFromParent();
1878     return false;
1879   }
1880 
1881   LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
1882 
1883   // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
1884   // in which case we can erase them all later in runOnMachineFunction.
1885   if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
1886     MI.eraseFromParent();
1887   return true;
1888 }
1889 
1890 /// Checks whether \p Copy is a AGPR -> VGPR copy. Returns `true` on success and
1891 /// stores the AGPR register in \p OutReg and the subreg in \p OutSubReg
1892 static bool isAGPRCopy(const SIRegisterInfo &TRI,
1893                        const MachineRegisterInfo &MRI, const MachineInstr &Copy,
1894                        Register &OutReg, unsigned &OutSubReg) {
1895   assert(Copy.isCopy());
1896 
1897   const MachineOperand &CopySrc = Copy.getOperand(1);
1898   Register CopySrcReg = CopySrc.getReg();
1899   if (!CopySrcReg.isVirtual())
1900     return false;
1901 
1902   // Common case: copy from AGPR directly, e.g.
1903   //  %1:vgpr_32 = COPY %0:agpr_32
1904   if (TRI.isAGPR(MRI, CopySrcReg)) {
1905     OutReg = CopySrcReg;
1906     OutSubReg = CopySrc.getSubReg();
1907     return true;
1908   }
1909 
1910   // Sometimes it can also involve two copies, e.g.
1911   //  %1:vgpr_256 = COPY %0:agpr_256
1912   //  %2:vgpr_32 = COPY %1:vgpr_256.sub0
1913   const MachineInstr *CopySrcDef = MRI.getVRegDef(CopySrcReg);
1914   if (!CopySrcDef || !CopySrcDef->isCopy())
1915     return false;
1916 
1917   const MachineOperand &OtherCopySrc = CopySrcDef->getOperand(1);
1918   Register OtherCopySrcReg = OtherCopySrc.getReg();
1919   if (!OtherCopySrcReg.isVirtual() ||
1920       CopySrcDef->getOperand(0).getSubReg() != AMDGPU::NoSubRegister ||
1921       OtherCopySrc.getSubReg() != AMDGPU::NoSubRegister ||
1922       !TRI.isAGPR(MRI, OtherCopySrcReg))
1923     return false;
1924 
1925   OutReg = OtherCopySrcReg;
1926   OutSubReg = CopySrc.getSubReg();
1927   return true;
1928 }
1929 
1930 // Try to hoist an AGPR to VGPR copy across a PHI.
1931 // This should allow folding of an AGPR into a consumer which may support it.
1932 //
1933 // Example 1: LCSSA PHI
1934 //      loop:
1935 //        %1:vreg = COPY %0:areg
1936 //      exit:
1937 //        %2:vreg = PHI %1:vreg, %loop
1938 //  =>
1939 //      loop:
1940 //      exit:
1941 //        %1:areg = PHI %0:areg, %loop
1942 //        %2:vreg = COPY %1:areg
1943 //
1944 // Example 2: PHI with multiple incoming values:
1945 //      entry:
1946 //        %1:vreg = GLOBAL_LOAD(..)
1947 //      loop:
1948 //        %2:vreg = PHI %1:vreg, %entry, %5:vreg, %loop
1949 //        %3:areg = COPY %2:vreg
1950 //        %4:areg = (instr using %3:areg)
1951 //        %5:vreg = COPY %4:areg
1952 //  =>
1953 //      entry:
1954 //        %1:vreg = GLOBAL_LOAD(..)
1955 //        %2:areg = COPY %1:vreg
1956 //      loop:
1957 //        %3:areg = PHI %2:areg, %entry, %X:areg,
1958 //        %4:areg = (instr using %3:areg)
1959 bool SIFoldOperandsImpl::tryFoldPhiAGPR(MachineInstr &PHI) {
1960   assert(PHI.isPHI());
1961 
1962   Register PhiOut = PHI.getOperand(0).getReg();
1963   if (!TRI->isVGPR(*MRI, PhiOut))
1964     return false;
1965 
1966   // Iterate once over all incoming values of the PHI to check if this PHI is
1967   // eligible, and determine the exact AGPR RC we'll target.
1968   const TargetRegisterClass *ARC = nullptr;
1969   for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
1970     MachineOperand &MO = PHI.getOperand(K);
1971     MachineInstr *Copy = MRI->getVRegDef(MO.getReg());
1972     if (!Copy || !Copy->isCopy())
1973       continue;
1974 
1975     Register AGPRSrc;
1976     unsigned AGPRRegMask = AMDGPU::NoSubRegister;
1977     if (!isAGPRCopy(*TRI, *MRI, *Copy, AGPRSrc, AGPRRegMask))
1978       continue;
1979 
1980     const TargetRegisterClass *CopyInRC = MRI->getRegClass(AGPRSrc);
1981     if (const auto *SubRC = TRI->getSubRegisterClass(CopyInRC, AGPRRegMask))
1982       CopyInRC = SubRC;
1983 
1984     if (ARC && !ARC->hasSubClassEq(CopyInRC))
1985       return false;
1986     ARC = CopyInRC;
1987   }
1988 
1989   if (!ARC)
1990     return false;
1991 
1992   bool IsAGPR32 = (ARC == &AMDGPU::AGPR_32RegClass);
1993 
1994   // Rewrite the PHI's incoming values to ARC.
1995   LLVM_DEBUG(dbgs() << "Folding AGPR copies into: " << PHI);
1996   for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
1997     MachineOperand &MO = PHI.getOperand(K);
1998     Register Reg = MO.getReg();
1999 
2000     MachineBasicBlock::iterator InsertPt;
2001     MachineBasicBlock *InsertMBB = nullptr;
2002 
2003     // Look at the def of Reg, ignoring all copies.
2004     unsigned CopyOpc = AMDGPU::COPY;
2005     if (MachineInstr *Def = MRI->getVRegDef(Reg)) {
2006 
2007       // Look at pre-existing COPY instructions from ARC: Steal the operand. If
2008       // the copy was single-use, it will be removed by DCE later.
2009       if (Def->isCopy()) {
2010         Register AGPRSrc;
2011         unsigned AGPRSubReg = AMDGPU::NoSubRegister;
2012         if (isAGPRCopy(*TRI, *MRI, *Def, AGPRSrc, AGPRSubReg)) {
2013           MO.setReg(AGPRSrc);
2014           MO.setSubReg(AGPRSubReg);
2015           continue;
2016         }
2017 
2018         // If this is a multi-use SGPR -> VGPR copy, use V_ACCVGPR_WRITE on
2019         // GFX908 directly instead of a COPY. Otherwise, SIFoldOperand may try
2020         // to fold the sgpr -> vgpr -> agpr copy into a sgpr -> agpr copy which
2021         // is unlikely to be profitable.
2022         //
2023         // Note that V_ACCVGPR_WRITE is only used for AGPR_32.
2024         MachineOperand &CopyIn = Def->getOperand(1);
2025         if (IsAGPR32 && !ST->hasGFX90AInsts() && !MRI->hasOneNonDBGUse(Reg) &&
2026             TRI->isSGPRReg(*MRI, CopyIn.getReg()))
2027           CopyOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
2028       }
2029 
2030       InsertMBB = Def->getParent();
2031       InsertPt = InsertMBB->SkipPHIsLabelsAndDebug(++Def->getIterator());
2032     } else {
2033       InsertMBB = PHI.getOperand(MO.getOperandNo() + 1).getMBB();
2034       InsertPt = InsertMBB->getFirstTerminator();
2035     }
2036 
2037     Register NewReg = MRI->createVirtualRegister(ARC);
2038     MachineInstr *MI = BuildMI(*InsertMBB, InsertPt, PHI.getDebugLoc(),
2039                                TII->get(CopyOpc), NewReg)
2040                            .addReg(Reg);
2041     MO.setReg(NewReg);
2042 
2043     (void)MI;
2044     LLVM_DEBUG(dbgs() << "  Created COPY: " << *MI);
2045   }
2046 
2047   // Replace the PHI's result with a new register.
2048   Register NewReg = MRI->createVirtualRegister(ARC);
2049   PHI.getOperand(0).setReg(NewReg);
2050 
2051   // COPY that new register back to the original PhiOut register. This COPY will
2052   // usually be folded out later.
2053   MachineBasicBlock *MBB = PHI.getParent();
2054   BuildMI(*MBB, MBB->getFirstNonPHI(), PHI.getDebugLoc(),
2055           TII->get(AMDGPU::COPY), PhiOut)
2056       .addReg(NewReg);
2057 
2058   LLVM_DEBUG(dbgs() << "  Done: Folded " << PHI);
2059   return true;
2060 }
2061 
2062 // Attempt to convert VGPR load to an AGPR load.
2063 bool SIFoldOperandsImpl::tryFoldLoad(MachineInstr &MI) {
2064   assert(MI.mayLoad());
2065   if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
2066     return false;
2067 
2068   MachineOperand &Def = MI.getOperand(0);
2069   if (!Def.isDef())
2070     return false;
2071 
2072   Register DefReg = Def.getReg();
2073 
2074   if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
2075     return false;
2076 
2077   SmallVector<const MachineInstr*, 8> Users;
2078   SmallVector<Register, 8> MoveRegs;
2079   for (const MachineInstr &I : MRI->use_nodbg_instructions(DefReg))
2080     Users.push_back(&I);
2081 
2082   if (Users.empty())
2083     return false;
2084 
2085   // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
2086   while (!Users.empty()) {
2087     const MachineInstr *I = Users.pop_back_val();
2088     if (!I->isCopy() && !I->isRegSequence())
2089       return false;
2090     Register DstReg = I->getOperand(0).getReg();
2091     // Physical registers may have more than one instruction definitions
2092     if (DstReg.isPhysical())
2093       return false;
2094     if (TRI->isAGPR(*MRI, DstReg))
2095       continue;
2096     MoveRegs.push_back(DstReg);
2097     for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg))
2098       Users.push_back(&U);
2099   }
2100 
2101   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
2102   MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
2103   if (!TII->isOperandLegal(MI, 0, &Def)) {
2104     MRI->setRegClass(DefReg, RC);
2105     return false;
2106   }
2107 
2108   while (!MoveRegs.empty()) {
2109     Register Reg = MoveRegs.pop_back_val();
2110     MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
2111   }
2112 
2113   LLVM_DEBUG(dbgs() << "Folded " << MI);
2114 
2115   return true;
2116 }
2117 
2118 // tryFoldPhiAGPR will aggressively try to create AGPR PHIs.
2119 // For GFX90A and later, this is pretty much always a good thing, but for GFX908
2120 // there's cases where it can create a lot more AGPR-AGPR copies, which are
2121 // expensive on this architecture due to the lack of V_ACCVGPR_MOV.
2122 //
2123 // This function looks at all AGPR PHIs in a basic block and collects their
2124 // operands. Then, it checks for register that are used more than once across
2125 // all PHIs and caches them in a VGPR. This prevents ExpandPostRAPseudo from
2126 // having to create one VGPR temporary per use, which can get very messy if
2127 // these PHIs come from a broken-up large PHI (e.g. 32 AGPR phis, one per vector
2128 // element).
2129 //
2130 // Example
2131 //      a:
2132 //        %in:agpr_256 = COPY %foo:vgpr_256
2133 //      c:
2134 //        %x:agpr_32 = ..
2135 //      b:
2136 //        %0:areg = PHI %in.sub0:agpr_32, %a, %x, %c
2137 //        %1:areg = PHI %in.sub0:agpr_32, %a, %y, %c
2138 //        %2:areg = PHI %in.sub0:agpr_32, %a, %z, %c
2139 //  =>
2140 //      a:
2141 //        %in:agpr_256 = COPY %foo:vgpr_256
2142 //        %tmp:vgpr_32 = V_ACCVGPR_READ_B32_e64 %in.sub0:agpr_32
2143 //        %tmp_agpr:agpr_32 = COPY %tmp
2144 //      c:
2145 //        %x:agpr_32 = ..
2146 //      b:
2147 //        %0:areg = PHI %tmp_agpr, %a, %x, %c
2148 //        %1:areg = PHI %tmp_agpr, %a, %y, %c
2149 //        %2:areg = PHI %tmp_agpr, %a, %z, %c
2150 bool SIFoldOperandsImpl::tryOptimizeAGPRPhis(MachineBasicBlock &MBB) {
2151   // This is only really needed on GFX908 where AGPR-AGPR copies are
2152   // unreasonably difficult.
2153   if (ST->hasGFX90AInsts())
2154     return false;
2155 
2156   // Look at all AGPR Phis and collect the register + subregister used.
2157   DenseMap<std::pair<Register, unsigned>, std::vector<MachineOperand *>>
2158       RegToMO;
2159 
2160   for (auto &MI : MBB) {
2161     if (!MI.isPHI())
2162       break;
2163 
2164     if (!TRI->isAGPR(*MRI, MI.getOperand(0).getReg()))
2165       continue;
2166 
2167     for (unsigned K = 1; K < MI.getNumOperands(); K += 2) {
2168       MachineOperand &PhiMO = MI.getOperand(K);
2169       if (!PhiMO.getSubReg())
2170         continue;
2171       RegToMO[{PhiMO.getReg(), PhiMO.getSubReg()}].push_back(&PhiMO);
2172     }
2173   }
2174 
2175   // For all (Reg, SubReg) pair that are used more than once, cache the value in
2176   // a VGPR.
2177   bool Changed = false;
2178   for (const auto &[Entry, MOs] : RegToMO) {
2179     if (MOs.size() == 1)
2180       continue;
2181 
2182     const auto [Reg, SubReg] = Entry;
2183     MachineInstr *Def = MRI->getVRegDef(Reg);
2184     MachineBasicBlock *DefMBB = Def->getParent();
2185 
2186     // Create a copy in a VGPR using V_ACCVGPR_READ_B32_e64 so it's not folded
2187     // out.
2188     const TargetRegisterClass *ARC = getRegOpRC(*MRI, *TRI, *MOs.front());
2189     Register TempVGPR =
2190         MRI->createVirtualRegister(TRI->getEquivalentVGPRClass(ARC));
2191     MachineInstr *VGPRCopy =
2192         BuildMI(*DefMBB, ++Def->getIterator(), Def->getDebugLoc(),
2193                 TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64), TempVGPR)
2194             .addReg(Reg, /* flags */ 0, SubReg);
2195 
2196     // Copy back to an AGPR and use that instead of the AGPR subreg in all MOs.
2197     Register TempAGPR = MRI->createVirtualRegister(ARC);
2198     BuildMI(*DefMBB, ++VGPRCopy->getIterator(), Def->getDebugLoc(),
2199             TII->get(AMDGPU::COPY), TempAGPR)
2200         .addReg(TempVGPR);
2201 
2202     LLVM_DEBUG(dbgs() << "Caching AGPR into VGPR: " << *VGPRCopy);
2203     for (MachineOperand *MO : MOs) {
2204       MO->setReg(TempAGPR);
2205       MO->setSubReg(AMDGPU::NoSubRegister);
2206       LLVM_DEBUG(dbgs() << "  Changed PHI Operand: " << *MO << "\n");
2207     }
2208 
2209     Changed = true;
2210   }
2211 
2212   return Changed;
2213 }
2214 
2215 bool SIFoldOperandsImpl::run(MachineFunction &MF) {
2216   MRI = &MF.getRegInfo();
2217   ST = &MF.getSubtarget<GCNSubtarget>();
2218   TII = ST->getInstrInfo();
2219   TRI = &TII->getRegisterInfo();
2220   MFI = MF.getInfo<SIMachineFunctionInfo>();
2221 
2222   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
2223   // correctly handle signed zeros.
2224   //
2225   // FIXME: Also need to check strictfp
2226   bool IsIEEEMode = MFI->getMode().IEEE;
2227   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
2228 
2229   bool Changed = false;
2230   for (MachineBasicBlock *MBB : depth_first(&MF)) {
2231     MachineOperand *CurrentKnownM0Val = nullptr;
2232     for (auto &MI : make_early_inc_range(*MBB)) {
2233       Changed |= tryFoldCndMask(MI);
2234 
2235       if (tryFoldZeroHighBits(MI)) {
2236         Changed = true;
2237         continue;
2238       }
2239 
2240       if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
2241         Changed = true;
2242         continue;
2243       }
2244 
2245       if (MI.isPHI() && tryFoldPhiAGPR(MI)) {
2246         Changed = true;
2247         continue;
2248       }
2249 
2250       if (MI.mayLoad() && tryFoldLoad(MI)) {
2251         Changed = true;
2252         continue;
2253       }
2254 
2255       if (TII->isFoldableCopy(MI)) {
2256         Changed |= tryFoldFoldableCopy(MI, CurrentKnownM0Val);
2257         continue;
2258       }
2259 
2260       // Saw an unknown clobber of m0, so we no longer know what it is.
2261       if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
2262         CurrentKnownM0Val = nullptr;
2263 
2264       // TODO: Omod might be OK if there is NSZ only on the source
2265       // instruction, and not the omod multiply.
2266       if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
2267           !tryFoldOMod(MI))
2268         Changed |= tryFoldClamp(MI);
2269     }
2270 
2271     Changed |= tryOptimizeAGPRPhis(*MBB);
2272   }
2273 
2274   return Changed;
2275 }
2276 
2277 PreservedAnalyses SIFoldOperandsPass::run(MachineFunction &MF,
2278                                           MachineFunctionAnalysisManager &) {
2279   bool Changed = SIFoldOperandsImpl().run(MF);
2280   if (!Changed) {
2281     return PreservedAnalyses::all();
2282   }
2283   auto PA = getMachineFunctionPassPreservedAnalyses();
2284   PA.preserveSet<CFGAnalyses>();
2285   return PA;
2286 }
2287