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_MAX_NUM_F64_e64:
1502   case AMDGPU::V_PK_MAX_F16: {
1503     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1504       return nullptr;
1505 
1506     // Make sure sources are identical.
1507     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1508     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1509     if (!Src0->isReg() || !Src1->isReg() ||
1510         Src0->getReg() != Src1->getReg() ||
1511         Src0->getSubReg() != Src1->getSubReg() ||
1512         Src0->getSubReg() != AMDGPU::NoSubRegister)
1513       return nullptr;
1514 
1515     // Can't fold up if we have modifiers.
1516     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1517       return nullptr;
1518 
1519     unsigned Src0Mods
1520       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1521     unsigned Src1Mods
1522       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1523 
1524     // Having a 0 op_sel_hi would require swizzling the output in the source
1525     // instruction, which we can't do.
1526     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1527                                                       : 0u;
1528     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1529       return nullptr;
1530     return Src0;
1531   }
1532   default:
1533     return nullptr;
1534   }
1535 }
1536 
1537 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1538 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1539   const MachineOperand *ClampSrc = isClamp(MI);
1540   if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
1541     return false;
1542 
1543   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1544 
1545   // The type of clamp must be compatible.
1546   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1547     return false;
1548 
1549   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1550   if (!DefClamp)
1551     return false;
1552 
1553   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
1554 
1555   // Clamp is applied after omod, so it is OK if omod is set.
1556   DefClamp->setImm(1);
1557   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1558   MI.eraseFromParent();
1559 
1560   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1561   // instruction, so we might as well convert it to the more flexible VOP3-only
1562   // mad/fma form.
1563   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1564     Def->eraseFromParent();
1565 
1566   return true;
1567 }
1568 
1569 static int getOModValue(unsigned Opc, int64_t Val) {
1570   switch (Opc) {
1571   case AMDGPU::V_MUL_F64_e64:
1572   case AMDGPU::V_MUL_F64_pseudo_e64: {
1573     switch (Val) {
1574     case 0x3fe0000000000000: // 0.5
1575       return SIOutMods::DIV2;
1576     case 0x4000000000000000: // 2.0
1577       return SIOutMods::MUL2;
1578     case 0x4010000000000000: // 4.0
1579       return SIOutMods::MUL4;
1580     default:
1581       return SIOutMods::NONE;
1582     }
1583   }
1584   case AMDGPU::V_MUL_F32_e64: {
1585     switch (static_cast<uint32_t>(Val)) {
1586     case 0x3f000000: // 0.5
1587       return SIOutMods::DIV2;
1588     case 0x40000000: // 2.0
1589       return SIOutMods::MUL2;
1590     case 0x40800000: // 4.0
1591       return SIOutMods::MUL4;
1592     default:
1593       return SIOutMods::NONE;
1594     }
1595   }
1596   case AMDGPU::V_MUL_F16_e64:
1597   case AMDGPU::V_MUL_F16_t16_e64:
1598   case AMDGPU::V_MUL_F16_fake16_e64: {
1599     switch (static_cast<uint16_t>(Val)) {
1600     case 0x3800: // 0.5
1601       return SIOutMods::DIV2;
1602     case 0x4000: // 2.0
1603       return SIOutMods::MUL2;
1604     case 0x4400: // 4.0
1605       return SIOutMods::MUL4;
1606     default:
1607       return SIOutMods::NONE;
1608     }
1609   }
1610   default:
1611     llvm_unreachable("invalid mul opcode");
1612   }
1613 }
1614 
1615 // FIXME: Does this really not support denormals with f16?
1616 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1617 // handled, so will anything other than that break?
1618 std::pair<const MachineOperand *, int>
1619 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1620   unsigned Op = MI.getOpcode();
1621   switch (Op) {
1622   case AMDGPU::V_MUL_F64_e64:
1623   case AMDGPU::V_MUL_F64_pseudo_e64:
1624   case AMDGPU::V_MUL_F32_e64:
1625   case AMDGPU::V_MUL_F16_t16_e64:
1626   case AMDGPU::V_MUL_F16_fake16_e64:
1627   case AMDGPU::V_MUL_F16_e64: {
1628     // If output denormals are enabled, omod is ignored.
1629     if ((Op == AMDGPU::V_MUL_F32_e64 &&
1630          MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
1631         ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F64_pseudo_e64 ||
1632           Op == AMDGPU::V_MUL_F16_e64 || Op == AMDGPU::V_MUL_F16_t16_e64 ||
1633           Op == AMDGPU::V_MUL_F16_fake16_e64) &&
1634          MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
1635       return std::pair(nullptr, SIOutMods::NONE);
1636 
1637     const MachineOperand *RegOp = nullptr;
1638     const MachineOperand *ImmOp = nullptr;
1639     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1640     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1641     if (Src0->isImm()) {
1642       ImmOp = Src0;
1643       RegOp = Src1;
1644     } else if (Src1->isImm()) {
1645       ImmOp = Src1;
1646       RegOp = Src0;
1647     } else
1648       return std::pair(nullptr, SIOutMods::NONE);
1649 
1650     int OMod = getOModValue(Op, ImmOp->getImm());
1651     if (OMod == SIOutMods::NONE ||
1652         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1653         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1654         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1655         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1656       return std::pair(nullptr, SIOutMods::NONE);
1657 
1658     return std::pair(RegOp, OMod);
1659   }
1660   case AMDGPU::V_ADD_F64_e64:
1661   case AMDGPU::V_ADD_F64_pseudo_e64:
1662   case AMDGPU::V_ADD_F32_e64:
1663   case AMDGPU::V_ADD_F16_e64:
1664   case AMDGPU::V_ADD_F16_t16_e64:
1665   case AMDGPU::V_ADD_F16_fake16_e64: {
1666     // If output denormals are enabled, omod is ignored.
1667     if ((Op == AMDGPU::V_ADD_F32_e64 &&
1668          MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
1669         ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F64_pseudo_e64 ||
1670           Op == AMDGPU::V_ADD_F16_e64 || Op == AMDGPU::V_ADD_F16_t16_e64 ||
1671           Op == AMDGPU::V_ADD_F16_fake16_e64) &&
1672          MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
1673       return std::pair(nullptr, SIOutMods::NONE);
1674 
1675     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1676     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1677     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1678 
1679     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1680         Src0->getSubReg() == Src1->getSubReg() &&
1681         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1682         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1683         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1684         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1685       return std::pair(Src0, SIOutMods::MUL2);
1686 
1687     return std::pair(nullptr, SIOutMods::NONE);
1688   }
1689   default:
1690     return std::pair(nullptr, SIOutMods::NONE);
1691   }
1692 }
1693 
1694 // FIXME: Does this need to check IEEE bit on function?
1695 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1696   const MachineOperand *RegOp;
1697   int OMod;
1698   std::tie(RegOp, OMod) = isOMod(MI);
1699   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1700       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1701       !MRI->hasOneNonDBGUser(RegOp->getReg()))
1702     return false;
1703 
1704   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1705   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1706   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1707     return false;
1708 
1709   // Clamp is applied after omod. If the source already has clamp set, don't
1710   // fold it.
1711   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1712     return false;
1713 
1714   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
1715 
1716   DefOMod->setImm(OMod);
1717   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1718   MI.eraseFromParent();
1719 
1720   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1721   // instruction, so we might as well convert it to the more flexible VOP3-only
1722   // mad/fma form.
1723   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1724     Def->eraseFromParent();
1725 
1726   return true;
1727 }
1728 
1729 // Try to fold a reg_sequence with vgpr output and agpr inputs into an
1730 // instruction which can take an agpr. So far that means a store.
1731 bool SIFoldOperands::tryFoldRegSequence(MachineInstr &MI) {
1732   assert(MI.isRegSequence());
1733   auto Reg = MI.getOperand(0).getReg();
1734 
1735   if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
1736       !MRI->hasOneNonDBGUse(Reg))
1737     return false;
1738 
1739   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
1740   if (!getRegSeqInit(Defs, Reg, MCOI::OPERAND_REGISTER))
1741     return false;
1742 
1743   for (auto &Def : Defs) {
1744     const auto *Op = Def.first;
1745     if (!Op->isReg())
1746       return false;
1747     if (TRI->isAGPR(*MRI, Op->getReg()))
1748       continue;
1749     // Maybe this is a COPY from AREG
1750     const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
1751     if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
1752       return false;
1753     if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
1754       return false;
1755   }
1756 
1757   MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
1758   MachineInstr *UseMI = Op->getParent();
1759   while (UseMI->isCopy() && !Op->getSubReg()) {
1760     Reg = UseMI->getOperand(0).getReg();
1761     if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
1762       return false;
1763     Op = &*MRI->use_nodbg_begin(Reg);
1764     UseMI = Op->getParent();
1765   }
1766 
1767   if (Op->getSubReg())
1768     return false;
1769 
1770   unsigned OpIdx = Op - &UseMI->getOperand(0);
1771   const MCInstrDesc &InstDesc = UseMI->getDesc();
1772   const TargetRegisterClass *OpRC =
1773       TII->getRegClass(InstDesc, OpIdx, TRI, *MI.getMF());
1774   if (!OpRC || !TRI->isVectorSuperClass(OpRC))
1775     return false;
1776 
1777   const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
1778   auto Dst = MRI->createVirtualRegister(NewDstRC);
1779   auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1780                     TII->get(AMDGPU::REG_SEQUENCE), Dst);
1781 
1782   for (unsigned I = 0; I < Defs.size(); ++I) {
1783     MachineOperand *Def = Defs[I].first;
1784     Def->setIsKill(false);
1785     if (TRI->isAGPR(*MRI, Def->getReg())) {
1786       RS.add(*Def);
1787     } else { // This is a copy
1788       MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
1789       SubDef->getOperand(1).setIsKill(false);
1790       RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
1791     }
1792     RS.addImm(Defs[I].second);
1793   }
1794 
1795   Op->setReg(Dst);
1796   if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
1797     Op->setReg(Reg);
1798     RS->eraseFromParent();
1799     return false;
1800   }
1801 
1802   LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
1803 
1804   // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
1805   // in which case we can erase them all later in runOnMachineFunction.
1806   if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
1807     MI.eraseFromParent();
1808   return true;
1809 }
1810 
1811 /// Checks whether \p Copy is a AGPR -> VGPR copy. Returns `true` on success and
1812 /// stores the AGPR register in \p OutReg and the subreg in \p OutSubReg
1813 static bool isAGPRCopy(const SIRegisterInfo &TRI,
1814                        const MachineRegisterInfo &MRI, const MachineInstr &Copy,
1815                        Register &OutReg, unsigned &OutSubReg) {
1816   assert(Copy.isCopy());
1817 
1818   const MachineOperand &CopySrc = Copy.getOperand(1);
1819   Register CopySrcReg = CopySrc.getReg();
1820   if (!CopySrcReg.isVirtual())
1821     return false;
1822 
1823   // Common case: copy from AGPR directly, e.g.
1824   //  %1:vgpr_32 = COPY %0:agpr_32
1825   if (TRI.isAGPR(MRI, CopySrcReg)) {
1826     OutReg = CopySrcReg;
1827     OutSubReg = CopySrc.getSubReg();
1828     return true;
1829   }
1830 
1831   // Sometimes it can also involve two copies, e.g.
1832   //  %1:vgpr_256 = COPY %0:agpr_256
1833   //  %2:vgpr_32 = COPY %1:vgpr_256.sub0
1834   const MachineInstr *CopySrcDef = MRI.getVRegDef(CopySrcReg);
1835   if (!CopySrcDef || !CopySrcDef->isCopy())
1836     return false;
1837 
1838   const MachineOperand &OtherCopySrc = CopySrcDef->getOperand(1);
1839   Register OtherCopySrcReg = OtherCopySrc.getReg();
1840   if (!OtherCopySrcReg.isVirtual() ||
1841       CopySrcDef->getOperand(0).getSubReg() != AMDGPU::NoSubRegister ||
1842       OtherCopySrc.getSubReg() != AMDGPU::NoSubRegister ||
1843       !TRI.isAGPR(MRI, OtherCopySrcReg))
1844     return false;
1845 
1846   OutReg = OtherCopySrcReg;
1847   OutSubReg = CopySrc.getSubReg();
1848   return true;
1849 }
1850 
1851 // Try to hoist an AGPR to VGPR copy across a PHI.
1852 // This should allow folding of an AGPR into a consumer which may support it.
1853 //
1854 // Example 1: LCSSA PHI
1855 //      loop:
1856 //        %1:vreg = COPY %0:areg
1857 //      exit:
1858 //        %2:vreg = PHI %1:vreg, %loop
1859 //  =>
1860 //      loop:
1861 //      exit:
1862 //        %1:areg = PHI %0:areg, %loop
1863 //        %2:vreg = COPY %1:areg
1864 //
1865 // Example 2: PHI with multiple incoming values:
1866 //      entry:
1867 //        %1:vreg = GLOBAL_LOAD(..)
1868 //      loop:
1869 //        %2:vreg = PHI %1:vreg, %entry, %5:vreg, %loop
1870 //        %3:areg = COPY %2:vreg
1871 //        %4:areg = (instr using %3:areg)
1872 //        %5:vreg = COPY %4:areg
1873 //  =>
1874 //      entry:
1875 //        %1:vreg = GLOBAL_LOAD(..)
1876 //        %2:areg = COPY %1:vreg
1877 //      loop:
1878 //        %3:areg = PHI %2:areg, %entry, %X:areg,
1879 //        %4:areg = (instr using %3:areg)
1880 bool SIFoldOperands::tryFoldPhiAGPR(MachineInstr &PHI) {
1881   assert(PHI.isPHI());
1882 
1883   Register PhiOut = PHI.getOperand(0).getReg();
1884   if (!TRI->isVGPR(*MRI, PhiOut))
1885     return false;
1886 
1887   // Iterate once over all incoming values of the PHI to check if this PHI is
1888   // eligible, and determine the exact AGPR RC we'll target.
1889   const TargetRegisterClass *ARC = nullptr;
1890   for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
1891     MachineOperand &MO = PHI.getOperand(K);
1892     MachineInstr *Copy = MRI->getVRegDef(MO.getReg());
1893     if (!Copy || !Copy->isCopy())
1894       continue;
1895 
1896     Register AGPRSrc;
1897     unsigned AGPRRegMask = AMDGPU::NoSubRegister;
1898     if (!isAGPRCopy(*TRI, *MRI, *Copy, AGPRSrc, AGPRRegMask))
1899       continue;
1900 
1901     const TargetRegisterClass *CopyInRC = MRI->getRegClass(AGPRSrc);
1902     if (const auto *SubRC = TRI->getSubRegisterClass(CopyInRC, AGPRRegMask))
1903       CopyInRC = SubRC;
1904 
1905     if (ARC && !ARC->hasSubClassEq(CopyInRC))
1906       return false;
1907     ARC = CopyInRC;
1908   }
1909 
1910   if (!ARC)
1911     return false;
1912 
1913   bool IsAGPR32 = (ARC == &AMDGPU::AGPR_32RegClass);
1914 
1915   // Rewrite the PHI's incoming values to ARC.
1916   LLVM_DEBUG(dbgs() << "Folding AGPR copies into: " << PHI);
1917   for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
1918     MachineOperand &MO = PHI.getOperand(K);
1919     Register Reg = MO.getReg();
1920 
1921     MachineBasicBlock::iterator InsertPt;
1922     MachineBasicBlock *InsertMBB = nullptr;
1923 
1924     // Look at the def of Reg, ignoring all copies.
1925     unsigned CopyOpc = AMDGPU::COPY;
1926     if (MachineInstr *Def = MRI->getVRegDef(Reg)) {
1927 
1928       // Look at pre-existing COPY instructions from ARC: Steal the operand. If
1929       // the copy was single-use, it will be removed by DCE later.
1930       if (Def->isCopy()) {
1931         Register AGPRSrc;
1932         unsigned AGPRSubReg = AMDGPU::NoSubRegister;
1933         if (isAGPRCopy(*TRI, *MRI, *Def, AGPRSrc, AGPRSubReg)) {
1934           MO.setReg(AGPRSrc);
1935           MO.setSubReg(AGPRSubReg);
1936           continue;
1937         }
1938 
1939         // If this is a multi-use SGPR -> VGPR copy, use V_ACCVGPR_WRITE on
1940         // GFX908 directly instead of a COPY. Otherwise, SIFoldOperand may try
1941         // to fold the sgpr -> vgpr -> agpr copy into a sgpr -> agpr copy which
1942         // is unlikely to be profitable.
1943         //
1944         // Note that V_ACCVGPR_WRITE is only used for AGPR_32.
1945         MachineOperand &CopyIn = Def->getOperand(1);
1946         if (IsAGPR32 && !ST->hasGFX90AInsts() && !MRI->hasOneNonDBGUse(Reg) &&
1947             TRI->isSGPRReg(*MRI, CopyIn.getReg()))
1948           CopyOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
1949       }
1950 
1951       InsertMBB = Def->getParent();
1952       InsertPt = InsertMBB->SkipPHIsLabelsAndDebug(++Def->getIterator());
1953     } else {
1954       InsertMBB = PHI.getOperand(MO.getOperandNo() + 1).getMBB();
1955       InsertPt = InsertMBB->getFirstTerminator();
1956     }
1957 
1958     Register NewReg = MRI->createVirtualRegister(ARC);
1959     MachineInstr *MI = BuildMI(*InsertMBB, InsertPt, PHI.getDebugLoc(),
1960                                TII->get(CopyOpc), NewReg)
1961                            .addReg(Reg);
1962     MO.setReg(NewReg);
1963 
1964     (void)MI;
1965     LLVM_DEBUG(dbgs() << "  Created COPY: " << *MI);
1966   }
1967 
1968   // Replace the PHI's result with a new register.
1969   Register NewReg = MRI->createVirtualRegister(ARC);
1970   PHI.getOperand(0).setReg(NewReg);
1971 
1972   // COPY that new register back to the original PhiOut register. This COPY will
1973   // usually be folded out later.
1974   MachineBasicBlock *MBB = PHI.getParent();
1975   BuildMI(*MBB, MBB->getFirstNonPHI(), PHI.getDebugLoc(),
1976           TII->get(AMDGPU::COPY), PhiOut)
1977       .addReg(NewReg);
1978 
1979   LLVM_DEBUG(dbgs() << "  Done: Folded " << PHI);
1980   return true;
1981 }
1982 
1983 // Attempt to convert VGPR load to an AGPR load.
1984 bool SIFoldOperands::tryFoldLoad(MachineInstr &MI) {
1985   assert(MI.mayLoad());
1986   if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
1987     return false;
1988 
1989   MachineOperand &Def = MI.getOperand(0);
1990   if (!Def.isDef())
1991     return false;
1992 
1993   Register DefReg = Def.getReg();
1994 
1995   if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
1996     return false;
1997 
1998   SmallVector<const MachineInstr*, 8> Users;
1999   SmallVector<Register, 8> MoveRegs;
2000   for (const MachineInstr &I : MRI->use_nodbg_instructions(DefReg))
2001     Users.push_back(&I);
2002 
2003   if (Users.empty())
2004     return false;
2005 
2006   // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
2007   while (!Users.empty()) {
2008     const MachineInstr *I = Users.pop_back_val();
2009     if (!I->isCopy() && !I->isRegSequence())
2010       return false;
2011     Register DstReg = I->getOperand(0).getReg();
2012     // Physical registers may have more than one instruction definitions
2013     if (DstReg.isPhysical())
2014       return false;
2015     if (TRI->isAGPR(*MRI, DstReg))
2016       continue;
2017     MoveRegs.push_back(DstReg);
2018     for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg))
2019       Users.push_back(&U);
2020   }
2021 
2022   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
2023   MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
2024   if (!TII->isOperandLegal(MI, 0, &Def)) {
2025     MRI->setRegClass(DefReg, RC);
2026     return false;
2027   }
2028 
2029   while (!MoveRegs.empty()) {
2030     Register Reg = MoveRegs.pop_back_val();
2031     MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
2032   }
2033 
2034   LLVM_DEBUG(dbgs() << "Folded " << MI);
2035 
2036   return true;
2037 }
2038 
2039 // tryFoldPhiAGPR will aggressively try to create AGPR PHIs.
2040 // For GFX90A and later, this is pretty much always a good thing, but for GFX908
2041 // there's cases where it can create a lot more AGPR-AGPR copies, which are
2042 // expensive on this architecture due to the lack of V_ACCVGPR_MOV.
2043 //
2044 // This function looks at all AGPR PHIs in a basic block and collects their
2045 // operands. Then, it checks for register that are used more than once across
2046 // all PHIs and caches them in a VGPR. This prevents ExpandPostRAPseudo from
2047 // having to create one VGPR temporary per use, which can get very messy if
2048 // these PHIs come from a broken-up large PHI (e.g. 32 AGPR phis, one per vector
2049 // element).
2050 //
2051 // Example
2052 //      a:
2053 //        %in:agpr_256 = COPY %foo:vgpr_256
2054 //      c:
2055 //        %x:agpr_32 = ..
2056 //      b:
2057 //        %0:areg = PHI %in.sub0:agpr_32, %a, %x, %c
2058 //        %1:areg = PHI %in.sub0:agpr_32, %a, %y, %c
2059 //        %2:areg = PHI %in.sub0:agpr_32, %a, %z, %c
2060 //  =>
2061 //      a:
2062 //        %in:agpr_256 = COPY %foo:vgpr_256
2063 //        %tmp:vgpr_32 = V_ACCVGPR_READ_B32_e64 %in.sub0:agpr_32
2064 //        %tmp_agpr:agpr_32 = COPY %tmp
2065 //      c:
2066 //        %x:agpr_32 = ..
2067 //      b:
2068 //        %0:areg = PHI %tmp_agpr, %a, %x, %c
2069 //        %1:areg = PHI %tmp_agpr, %a, %y, %c
2070 //        %2:areg = PHI %tmp_agpr, %a, %z, %c
2071 bool SIFoldOperands::tryOptimizeAGPRPhis(MachineBasicBlock &MBB) {
2072   // This is only really needed on GFX908 where AGPR-AGPR copies are
2073   // unreasonably difficult.
2074   if (ST->hasGFX90AInsts())
2075     return false;
2076 
2077   // Look at all AGPR Phis and collect the register + subregister used.
2078   DenseMap<std::pair<Register, unsigned>, std::vector<MachineOperand *>>
2079       RegToMO;
2080 
2081   for (auto &MI : MBB) {
2082     if (!MI.isPHI())
2083       break;
2084 
2085     if (!TRI->isAGPR(*MRI, MI.getOperand(0).getReg()))
2086       continue;
2087 
2088     for (unsigned K = 1; K < MI.getNumOperands(); K += 2) {
2089       MachineOperand &PhiMO = MI.getOperand(K);
2090       RegToMO[{PhiMO.getReg(), PhiMO.getSubReg()}].push_back(&PhiMO);
2091     }
2092   }
2093 
2094   // For all (Reg, SubReg) pair that are used more than once, cache the value in
2095   // a VGPR.
2096   bool Changed = false;
2097   for (const auto &[Entry, MOs] : RegToMO) {
2098     if (MOs.size() == 1)
2099       continue;
2100 
2101     const auto [Reg, SubReg] = Entry;
2102     MachineInstr *Def = MRI->getVRegDef(Reg);
2103     MachineBasicBlock *DefMBB = Def->getParent();
2104 
2105     // Create a copy in a VGPR using V_ACCVGPR_READ_B32_e64 so it's not folded
2106     // out.
2107     const TargetRegisterClass *ARC = getRegOpRC(*MRI, *TRI, *MOs.front());
2108     Register TempVGPR =
2109         MRI->createVirtualRegister(TRI->getEquivalentVGPRClass(ARC));
2110     MachineInstr *VGPRCopy =
2111         BuildMI(*DefMBB, ++Def->getIterator(), Def->getDebugLoc(),
2112                 TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64), TempVGPR)
2113             .addReg(Reg, /* flags */ 0, SubReg);
2114 
2115     // Copy back to an AGPR and use that instead of the AGPR subreg in all MOs.
2116     Register TempAGPR = MRI->createVirtualRegister(ARC);
2117     BuildMI(*DefMBB, ++VGPRCopy->getIterator(), Def->getDebugLoc(),
2118             TII->get(AMDGPU::COPY), TempAGPR)
2119         .addReg(TempVGPR);
2120 
2121     LLVM_DEBUG(dbgs() << "Caching AGPR into VGPR: " << *VGPRCopy);
2122     for (MachineOperand *MO : MOs) {
2123       MO->setReg(TempAGPR);
2124       MO->setSubReg(AMDGPU::NoSubRegister);
2125       LLVM_DEBUG(dbgs() << "  Changed PHI Operand: " << *MO << "\n");
2126     }
2127 
2128     Changed = true;
2129   }
2130 
2131   return Changed;
2132 }
2133 
2134 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
2135   if (skipFunction(MF.getFunction()))
2136     return false;
2137 
2138   MRI = &MF.getRegInfo();
2139   ST = &MF.getSubtarget<GCNSubtarget>();
2140   TII = ST->getInstrInfo();
2141   TRI = &TII->getRegisterInfo();
2142   MFI = MF.getInfo<SIMachineFunctionInfo>();
2143 
2144   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
2145   // correctly handle signed zeros.
2146   //
2147   // FIXME: Also need to check strictfp
2148   bool IsIEEEMode = MFI->getMode().IEEE;
2149   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
2150 
2151   bool Changed = false;
2152   for (MachineBasicBlock *MBB : depth_first(&MF)) {
2153     MachineOperand *CurrentKnownM0Val = nullptr;
2154     for (auto &MI : make_early_inc_range(*MBB)) {
2155       Changed |= tryFoldCndMask(MI);
2156 
2157       if (tryFoldZeroHighBits(MI)) {
2158         Changed = true;
2159         continue;
2160       }
2161 
2162       if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
2163         Changed = true;
2164         continue;
2165       }
2166 
2167       if (MI.isPHI() && tryFoldPhiAGPR(MI)) {
2168         Changed = true;
2169         continue;
2170       }
2171 
2172       if (MI.mayLoad() && tryFoldLoad(MI)) {
2173         Changed = true;
2174         continue;
2175       }
2176 
2177       if (TII->isFoldableCopy(MI)) {
2178         Changed |= tryFoldFoldableCopy(MI, CurrentKnownM0Val);
2179         continue;
2180       }
2181 
2182       // Saw an unknown clobber of m0, so we no longer know what it is.
2183       if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
2184         CurrentKnownM0Val = nullptr;
2185 
2186       // TODO: Omod might be OK if there is NSZ only on the source
2187       // instruction, and not the omod multiply.
2188       if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
2189           !tryFoldOMod(MI))
2190         Changed |= tryFoldClamp(MI);
2191     }
2192 
2193     Changed |= tryOptimizeAGPRPhis(*MBB);
2194   }
2195 
2196   return Changed;
2197 }
2198