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