xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision 69ab233a15bf63e706f14fbf53df4a755a2a37d9)
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 
18 #define DEBUG_TYPE "si-fold-operands"
19 using namespace llvm;
20 
21 namespace {
22 
23 struct FoldCandidate {
24   MachineInstr *UseMI;
25   union {
26     MachineOperand *OpToFold;
27     uint64_t ImmToFold;
28     int FrameIndexToFold;
29   };
30   int ShrinkOpcode;
31   unsigned UseOpNo;
32   MachineOperand::MachineOperandType Kind;
33   bool Commuted;
34 
35   FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
36                 bool Commuted_ = false,
37                 int ShrinkOp = -1) :
38     UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
39     Kind(FoldOp->getType()),
40     Commuted(Commuted_) {
41     if (FoldOp->isImm()) {
42       ImmToFold = FoldOp->getImm();
43     } else if (FoldOp->isFI()) {
44       FrameIndexToFold = FoldOp->getIndex();
45     } else {
46       assert(FoldOp->isReg() || FoldOp->isGlobal());
47       OpToFold = FoldOp;
48     }
49   }
50 
51   bool isFI() const {
52     return Kind == MachineOperand::MO_FrameIndex;
53   }
54 
55   bool isImm() const {
56     return Kind == MachineOperand::MO_Immediate;
57   }
58 
59   bool isReg() const {
60     return Kind == MachineOperand::MO_Register;
61   }
62 
63   bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; }
64 
65   bool isCommuted() const {
66     return Commuted;
67   }
68 
69   bool needsShrink() const {
70     return ShrinkOpcode != -1;
71   }
72 
73   int getShrinkOpcode() const {
74     return ShrinkOpcode;
75   }
76 };
77 
78 class SIFoldOperands : public MachineFunctionPass {
79 public:
80   static char ID;
81   MachineRegisterInfo *MRI;
82   const SIInstrInfo *TII;
83   const SIRegisterInfo *TRI;
84   const GCNSubtarget *ST;
85   const SIMachineFunctionInfo *MFI;
86 
87   void foldOperand(MachineOperand &OpToFold,
88                    MachineInstr *UseMI,
89                    int UseOpIdx,
90                    SmallVectorImpl<FoldCandidate> &FoldList,
91                    SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
92 
93   bool tryFoldCndMask(MachineInstr &MI) const;
94   bool tryFoldZeroHighBits(MachineInstr &MI) const;
95   bool foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
96 
97   const MachineOperand *isClamp(const MachineInstr &MI) const;
98   bool tryFoldClamp(MachineInstr &MI);
99 
100   std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
101   bool tryFoldOMod(MachineInstr &MI);
102   bool tryFoldRegSequence(MachineInstr &MI);
103   bool tryFoldLCSSAPhi(MachineInstr &MI);
104   bool tryFoldLoad(MachineInstr &MI);
105 
106 public:
107   SIFoldOperands() : MachineFunctionPass(ID) {
108     initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
109   }
110 
111   bool runOnMachineFunction(MachineFunction &MF) override;
112 
113   StringRef getPassName() const override { return "SI Fold Operands"; }
114 
115   void getAnalysisUsage(AnalysisUsage &AU) const override {
116     AU.setPreservesCFG();
117     MachineFunctionPass::getAnalysisUsage(AU);
118   }
119 };
120 
121 } // End anonymous namespace.
122 
123 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
124                 "SI Fold Operands", false, false)
125 
126 char SIFoldOperands::ID = 0;
127 
128 char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
129 
130 // Map multiply-accumulate opcode to corresponding multiply-add opcode if any.
131 static unsigned macToMad(unsigned Opc) {
132   switch (Opc) {
133   case AMDGPU::V_MAC_F32_e64:
134     return AMDGPU::V_MAD_F32_e64;
135   case AMDGPU::V_MAC_F16_e64:
136     return AMDGPU::V_MAD_F16_e64;
137   case AMDGPU::V_FMAC_F32_e64:
138     return AMDGPU::V_FMA_F32_e64;
139   case AMDGPU::V_FMAC_F16_e64:
140     return AMDGPU::V_FMA_F16_gfx9_e64;
141   case AMDGPU::V_FMAC_LEGACY_F32_e64:
142     return AMDGPU::V_FMA_LEGACY_F32_e64;
143   case AMDGPU::V_FMAC_F64_e64:
144     return AMDGPU::V_FMA_F64_e64;
145   }
146   return AMDGPU::INSTRUCTION_LIST_END;
147 }
148 
149 // Wrapper around isInlineConstant that understands special cases when
150 // instruction types are replaced during operand folding.
151 static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
152                                      const MachineInstr &UseMI,
153                                      unsigned OpNo,
154                                      const MachineOperand &OpToFold) {
155   if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
156     return true;
157 
158   unsigned Opc = UseMI.getOpcode();
159   unsigned NewOpc = macToMad(Opc);
160   if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
161     // Special case for mac. Since this is replaced with mad when folded into
162     // src2, we need to check the legality for the final instruction.
163     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
164     if (static_cast<int>(OpNo) == Src2Idx) {
165       const MCInstrDesc &MadDesc = TII->get(NewOpc);
166       return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
167     }
168   }
169 
170   return false;
171 }
172 
173 // TODO: Add heuristic that the frame index might not fit in the addressing mode
174 // immediate offset to avoid materializing in loops.
175 static bool frameIndexMayFold(const SIInstrInfo *TII,
176                               const MachineInstr &UseMI,
177                               int OpNo,
178                               const MachineOperand &OpToFold) {
179   if (!OpToFold.isFI())
180     return false;
181 
182   if (TII->isMUBUF(UseMI))
183     return OpNo == AMDGPU::getNamedOperandIdx(UseMI.getOpcode(),
184                                               AMDGPU::OpName::vaddr);
185   if (!TII->isFLATScratch(UseMI))
186     return false;
187 
188   int SIdx = AMDGPU::getNamedOperandIdx(UseMI.getOpcode(),
189                                         AMDGPU::OpName::saddr);
190   if (OpNo == SIdx)
191     return true;
192 
193   int VIdx = AMDGPU::getNamedOperandIdx(UseMI.getOpcode(),
194                                         AMDGPU::OpName::vaddr);
195   return OpNo == VIdx && SIdx == -1;
196 }
197 
198 FunctionPass *llvm::createSIFoldOperandsPass() {
199   return new SIFoldOperands();
200 }
201 
202 static bool updateOperand(FoldCandidate &Fold,
203                           const SIInstrInfo &TII,
204                           const TargetRegisterInfo &TRI,
205                           const GCNSubtarget &ST) {
206   MachineInstr *MI = Fold.UseMI;
207   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
208   assert(Old.isReg());
209 
210   if (Fold.isImm()) {
211     if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked &&
212         !(MI->getDesc().TSFlags & SIInstrFlags::IsMAI) &&
213         AMDGPU::isFoldableLiteralV216(Fold.ImmToFold,
214                                       ST.hasInv2PiInlineImm())) {
215       // Set op_sel/op_sel_hi on this operand or bail out if op_sel is
216       // already set.
217       unsigned Opcode = MI->getOpcode();
218       int OpNo = MI->getOperandNo(&Old);
219       int ModIdx = -1;
220       if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0))
221         ModIdx = AMDGPU::OpName::src0_modifiers;
222       else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1))
223         ModIdx = AMDGPU::OpName::src1_modifiers;
224       else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2))
225         ModIdx = AMDGPU::OpName::src2_modifiers;
226       assert(ModIdx != -1);
227       ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
228       MachineOperand &Mod = MI->getOperand(ModIdx);
229       unsigned Val = Mod.getImm();
230       if (!(Val & SISrcMods::OP_SEL_0) && (Val & SISrcMods::OP_SEL_1)) {
231         // Only apply the following transformation if that operand requires
232         // a packed immediate.
233         switch (TII.get(Opcode).OpInfo[OpNo].OperandType) {
234         case AMDGPU::OPERAND_REG_IMM_V2FP16:
235         case AMDGPU::OPERAND_REG_IMM_V2INT16:
236         case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
237         case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
238           // If upper part is all zero we do not need op_sel_hi.
239           if (!isUInt<16>(Fold.ImmToFold)) {
240             if (!(Fold.ImmToFold & 0xffff)) {
241               Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0);
242               Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
243               Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff);
244               return true;
245             }
246             Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
247             Old.ChangeToImmediate(Fold.ImmToFold & 0xffff);
248             return true;
249           }
250           break;
251         default:
252           break;
253         }
254       }
255     }
256   }
257 
258   if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) {
259     MachineBasicBlock *MBB = MI->getParent();
260     auto Liveness = MBB->computeRegisterLiveness(&TRI, AMDGPU::VCC, MI, 16);
261     if (Liveness != MachineBasicBlock::LQR_Dead) {
262       LLVM_DEBUG(dbgs() << "Not shrinking " << MI << " due to vcc liveness\n");
263       return false;
264     }
265 
266     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
267     int Op32 = Fold.getShrinkOpcode();
268     MachineOperand &Dst0 = MI->getOperand(0);
269     MachineOperand &Dst1 = MI->getOperand(1);
270     assert(Dst0.isDef() && Dst1.isDef());
271 
272     bool HaveNonDbgCarryUse = !MRI.use_nodbg_empty(Dst1.getReg());
273 
274     const TargetRegisterClass *Dst0RC = MRI.getRegClass(Dst0.getReg());
275     Register NewReg0 = MRI.createVirtualRegister(Dst0RC);
276 
277     MachineInstr *Inst32 = TII.buildShrunkInst(*MI, Op32);
278 
279     if (HaveNonDbgCarryUse) {
280       BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), Dst1.getReg())
281         .addReg(AMDGPU::VCC, RegState::Kill);
282     }
283 
284     // Keep the old instruction around to avoid breaking iterators, but
285     // replace it with a dummy instruction to remove uses.
286     //
287     // FIXME: We should not invert how this pass looks at operands to avoid
288     // this. Should track set of foldable movs instead of looking for uses
289     // when looking at a use.
290     Dst0.setReg(NewReg0);
291     for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
292       MI->RemoveOperand(I);
293     MI->setDesc(TII.get(AMDGPU::IMPLICIT_DEF));
294 
295     if (Fold.isCommuted())
296       TII.commuteInstruction(*Inst32, false);
297     return true;
298   }
299 
300   assert(!Fold.needsShrink() && "not handled");
301 
302   if (Fold.isImm()) {
303     if (Old.isTied()) {
304       int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(MI->getOpcode());
305       if (NewMFMAOpc == -1)
306         return false;
307       MI->setDesc(TII.get(NewMFMAOpc));
308       MI->untieRegOperand(0);
309     }
310     Old.ChangeToImmediate(Fold.ImmToFold);
311     return true;
312   }
313 
314   if (Fold.isGlobal()) {
315     Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(),
316                    Fold.OpToFold->getTargetFlags());
317     return true;
318   }
319 
320   if (Fold.isFI()) {
321     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
322     return true;
323   }
324 
325   MachineOperand *New = Fold.OpToFold;
326   Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
327   Old.setIsUndef(New->isUndef());
328   return true;
329 }
330 
331 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
332                               const MachineInstr *MI) {
333   for (auto Candidate : FoldList) {
334     if (Candidate.UseMI == MI)
335       return true;
336   }
337   return false;
338 }
339 
340 static void appendFoldCandidate(SmallVectorImpl<FoldCandidate> &FoldList,
341                                 MachineInstr *MI, unsigned OpNo,
342                                 MachineOperand *FoldOp, bool Commuted = false,
343                                 int ShrinkOp = -1) {
344   // Skip additional folding on the same operand.
345   for (FoldCandidate &Fold : FoldList)
346     if (Fold.UseMI == MI && Fold.UseOpNo == OpNo)
347       return;
348   LLVM_DEBUG(dbgs() << "Append " << (Commuted ? "commuted" : "normal")
349                     << " operand " << OpNo << "\n  " << *MI);
350   FoldList.emplace_back(MI, OpNo, FoldOp, Commuted, ShrinkOp);
351 }
352 
353 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
354                              MachineInstr *MI, unsigned OpNo,
355                              MachineOperand *OpToFold,
356                              const SIInstrInfo *TII) {
357   if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
358     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
359     unsigned Opc = MI->getOpcode();
360     unsigned NewOpc = macToMad(Opc);
361     if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
362       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
363       // to fold the operand.
364       MI->setDesc(TII->get(NewOpc));
365       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
366       if (FoldAsMAD) {
367         MI->untieRegOperand(OpNo);
368         return true;
369       }
370       MI->setDesc(TII->get(Opc));
371     }
372 
373     // Special case for s_setreg_b32
374     if (OpToFold->isImm()) {
375       unsigned ImmOpc = 0;
376       if (Opc == AMDGPU::S_SETREG_B32)
377         ImmOpc = AMDGPU::S_SETREG_IMM32_B32;
378       else if (Opc == AMDGPU::S_SETREG_B32_mode)
379         ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode;
380       if (ImmOpc) {
381         MI->setDesc(TII->get(ImmOpc));
382         appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
383         return true;
384       }
385     }
386 
387     // If we are already folding into another operand of MI, then
388     // we can't commute the instruction, otherwise we risk making the
389     // other fold illegal.
390     if (isUseMIInFoldList(FoldList, MI))
391       return false;
392 
393     unsigned CommuteOpNo = OpNo;
394 
395     // Operand is not legal, so try to commute the instruction to
396     // see if this makes it possible to fold.
397     unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
398     unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
399     bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
400 
401     if (CanCommute) {
402       if (CommuteIdx0 == OpNo)
403         CommuteOpNo = CommuteIdx1;
404       else if (CommuteIdx1 == OpNo)
405         CommuteOpNo = CommuteIdx0;
406     }
407 
408 
409     // One of operands might be an Imm operand, and OpNo may refer to it after
410     // the call of commuteInstruction() below. Such situations are avoided
411     // here explicitly as OpNo must be a register operand to be a candidate
412     // for memory folding.
413     if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
414                        !MI->getOperand(CommuteIdx1).isReg()))
415       return false;
416 
417     if (!CanCommute ||
418         !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
419       return false;
420 
421     if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
422       if ((Opc == AMDGPU::V_ADD_CO_U32_e64 ||
423            Opc == AMDGPU::V_SUB_CO_U32_e64 ||
424            Opc == AMDGPU::V_SUBREV_CO_U32_e64) && // FIXME
425           (OpToFold->isImm() || OpToFold->isFI() || OpToFold->isGlobal())) {
426         MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
427 
428         // Verify the other operand is a VGPR, otherwise we would violate the
429         // constant bus restriction.
430         unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0;
431         MachineOperand &OtherOp = MI->getOperand(OtherIdx);
432         if (!OtherOp.isReg() ||
433             !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg()))
434           return false;
435 
436         assert(MI->getOperand(1).isDef());
437 
438         // Make sure to get the 32-bit version of the commuted opcode.
439         unsigned MaybeCommutedOpc = MI->getOpcode();
440         int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
441 
442         appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true, Op32);
443         return true;
444       }
445 
446       TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
447       return false;
448     }
449 
450     appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true);
451     return true;
452   }
453 
454   // Check the case where we might introduce a second constant operand to a
455   // scalar instruction
456   if (TII->isSALU(MI->getOpcode())) {
457     const MCInstrDesc &InstDesc = MI->getDesc();
458     const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo];
459     const SIRegisterInfo &SRI = TII->getRegisterInfo();
460 
461     // Fine if the operand can be encoded as an inline constant
462     if (TII->isLiteralConstantLike(*OpToFold, OpInfo)) {
463       if (!SRI.opCanUseInlineConstant(OpInfo.OperandType) ||
464           !TII->isInlineConstant(*OpToFold, OpInfo)) {
465         // Otherwise check for another constant
466         for (unsigned i = 0, e = InstDesc.getNumOperands(); i != e; ++i) {
467           auto &Op = MI->getOperand(i);
468           if (OpNo != i &&
469               TII->isLiteralConstantLike(Op, OpInfo)) {
470             return false;
471           }
472         }
473       }
474     }
475   }
476 
477   appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
478   return true;
479 }
480 
481 // If the use operand doesn't care about the value, this may be an operand only
482 // used for register indexing, in which case it is unsafe to fold.
483 static bool isUseSafeToFold(const SIInstrInfo *TII,
484                             const MachineInstr &MI,
485                             const MachineOperand &UseMO) {
486   if (UseMO.isUndef() || TII->isSDWA(MI))
487     return false;
488 
489   switch (MI.getOpcode()) {
490   case AMDGPU::V_MOV_B32_e32:
491   case AMDGPU::V_MOV_B32_e64:
492   case AMDGPU::V_MOV_B64_PSEUDO:
493     // Do not fold into an indirect mov.
494     return !MI.hasRegisterImplicitUseOperand(AMDGPU::M0);
495   }
496 
497   return true;
498   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
499 }
500 
501 // Find a def of the UseReg, check if it is a reg_sequence and find initializers
502 // for each subreg, tracking it to foldable inline immediate if possible.
503 // Returns true on success.
504 static bool getRegSeqInit(
505     SmallVectorImpl<std::pair<MachineOperand*, unsigned>> &Defs,
506     Register UseReg, uint8_t OpTy,
507     const SIInstrInfo *TII, const MachineRegisterInfo &MRI) {
508   MachineInstr *Def = MRI.getVRegDef(UseReg);
509   if (!Def || !Def->isRegSequence())
510     return false;
511 
512   for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) {
513     MachineOperand *Sub = &Def->getOperand(I);
514     assert(Sub->isReg());
515 
516     for (MachineInstr *SubDef = MRI.getVRegDef(Sub->getReg());
517          SubDef && Sub->isReg() && Sub->getReg().isVirtual() &&
518          !Sub->getSubReg() && TII->isFoldableCopy(*SubDef);
519          SubDef = MRI.getVRegDef(Sub->getReg())) {
520       MachineOperand *Op = &SubDef->getOperand(1);
521       if (Op->isImm()) {
522         if (TII->isInlineConstant(*Op, OpTy))
523           Sub = Op;
524         break;
525       }
526       if (!Op->isReg() || Op->getReg().isPhysical())
527         break;
528       Sub = Op;
529     }
530 
531     Defs.emplace_back(Sub, Def->getOperand(I + 1).getImm());
532   }
533 
534   return true;
535 }
536 
537 static bool tryToFoldACImm(const SIInstrInfo *TII,
538                            const MachineOperand &OpToFold,
539                            MachineInstr *UseMI,
540                            unsigned UseOpIdx,
541                            SmallVectorImpl<FoldCandidate> &FoldList) {
542   const MCInstrDesc &Desc = UseMI->getDesc();
543   const MCOperandInfo *OpInfo = Desc.OpInfo;
544   if (!OpInfo || UseOpIdx >= Desc.getNumOperands())
545     return false;
546 
547   uint8_t OpTy = OpInfo[UseOpIdx].OperandType;
548   if ((OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST ||
549        OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST) &&
550       (OpTy < AMDGPU::OPERAND_REG_INLINE_C_FIRST ||
551        OpTy > AMDGPU::OPERAND_REG_INLINE_C_LAST))
552     return false;
553 
554   if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) &&
555       TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) {
556     UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm());
557     return true;
558   }
559 
560   if (!OpToFold.isReg())
561     return false;
562 
563   Register UseReg = OpToFold.getReg();
564   if (!UseReg.isVirtual())
565     return false;
566 
567   if (isUseMIInFoldList(FoldList, UseMI))
568     return false;
569 
570   MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo();
571 
572   // Maybe it is just a COPY of an immediate itself.
573   MachineInstr *Def = MRI.getVRegDef(UseReg);
574   MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
575   if (!UseOp.getSubReg() && Def && TII->isFoldableCopy(*Def)) {
576     MachineOperand &DefOp = Def->getOperand(1);
577     if (DefOp.isImm() && TII->isInlineConstant(DefOp, OpTy) &&
578         TII->isOperandLegal(*UseMI, UseOpIdx, &DefOp)) {
579       UseMI->getOperand(UseOpIdx).ChangeToImmediate(DefOp.getImm());
580       return true;
581     }
582   }
583 
584   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
585   if (!getRegSeqInit(Defs, UseReg, OpTy, TII, MRI))
586     return false;
587 
588   int32_t Imm;
589   for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
590     const MachineOperand *Op = Defs[I].first;
591     if (!Op->isImm())
592       return false;
593 
594     auto SubImm = Op->getImm();
595     if (!I) {
596       Imm = SubImm;
597       if (!TII->isInlineConstant(*Op, OpTy) ||
598           !TII->isOperandLegal(*UseMI, UseOpIdx, Op))
599         return false;
600 
601       continue;
602     }
603     if (Imm != SubImm)
604       return false; // Can only fold splat constants
605   }
606 
607   appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first);
608   return true;
609 }
610 
611 void SIFoldOperands::foldOperand(
612   MachineOperand &OpToFold,
613   MachineInstr *UseMI,
614   int UseOpIdx,
615   SmallVectorImpl<FoldCandidate> &FoldList,
616   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
617   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
618 
619   if (!isUseSafeToFold(TII, *UseMI, UseOp))
620     return;
621 
622   // FIXME: Fold operands with subregs.
623   if (UseOp.isReg() && OpToFold.isReg()) {
624     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
625       return;
626   }
627 
628   // Special case for REG_SEQUENCE: We can't fold literals into
629   // REG_SEQUENCE instructions, so we have to fold them into the
630   // uses of REG_SEQUENCE.
631   if (UseMI->isRegSequence()) {
632     Register RegSeqDstReg = UseMI->getOperand(0).getReg();
633     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
634 
635     for (auto &RSUse : make_early_inc_range(MRI->use_nodbg_operands(RegSeqDstReg))) {
636       MachineInstr *RSUseMI = RSUse.getParent();
637 
638       if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI,
639                          RSUseMI->getOperandNo(&RSUse), FoldList))
640         continue;
641 
642       if (RSUse.getSubReg() != RegSeqDstSubReg)
643         continue;
644 
645       foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(&RSUse), FoldList,
646                   CopiesToReplace);
647     }
648 
649     return;
650   }
651 
652   if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList))
653     return;
654 
655   if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) {
656     // Verify that this is a stack access.
657     // FIXME: Should probably use stack pseudos before frame lowering.
658 
659     if (TII->isMUBUF(*UseMI)) {
660       if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
661           MFI->getScratchRSrcReg())
662         return;
663 
664       // Ensure this is either relative to the current frame or the current
665       // wave.
666       MachineOperand &SOff =
667           *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
668       if (!SOff.isImm() || SOff.getImm() != 0)
669         return;
670     }
671 
672     // A frame index will resolve to a positive constant, so it should always be
673     // safe to fold the addressing mode, even pre-GFX9.
674     UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex());
675 
676     if (TII->isFLATScratch(*UseMI) &&
677         AMDGPU::getNamedOperandIdx(UseMI->getOpcode(),
678                                    AMDGPU::OpName::vaddr) != -1) {
679       unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(UseMI->getOpcode());
680       UseMI->setDesc(TII->get(NewOpc));
681     }
682 
683     return;
684   }
685 
686   bool FoldingImmLike =
687       OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
688 
689   if (FoldingImmLike && UseMI->isCopy()) {
690     Register DestReg = UseMI->getOperand(0).getReg();
691     Register SrcReg = UseMI->getOperand(1).getReg();
692     assert(SrcReg.isVirtual());
693 
694     const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
695 
696     // Don't fold into a copy to a physical register with the same class. Doing
697     // so would interfere with the register coalescer's logic which would avoid
698     // redundant initializations.
699     if (DestReg.isPhysical() && SrcRC->contains(DestReg))
700       return;
701 
702     const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
703     if (!DestReg.isPhysical()) {
704       if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) {
705         SmallVector<FoldCandidate, 4> CopyUses;
706         for (auto &Use : MRI->use_nodbg_operands(DestReg)) {
707           // There's no point trying to fold into an implicit operand.
708           if (Use.isImplicit())
709             continue;
710 
711           CopyUses.emplace_back(Use.getParent(),
712                                 Use.getParent()->getOperandNo(&Use),
713                                 &UseMI->getOperand(1));
714         }
715         for (auto &F : CopyUses) {
716           foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, FoldList, CopiesToReplace);
717         }
718       }
719 
720       if (DestRC == &AMDGPU::AGPR_32RegClass &&
721           TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
722         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
723         UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
724         CopiesToReplace.push_back(UseMI);
725         return;
726       }
727     }
728 
729     // In order to fold immediates into copies, we need to change the
730     // copy to a MOV.
731 
732     unsigned MovOp = TII->getMovOpcode(DestRC);
733     if (MovOp == AMDGPU::COPY)
734       return;
735 
736     UseMI->setDesc(TII->get(MovOp));
737     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
738     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
739     while (ImpOpI != ImpOpE) {
740       MachineInstr::mop_iterator Tmp = ImpOpI;
741       ImpOpI++;
742       UseMI->RemoveOperand(UseMI->getOperandNo(Tmp));
743     }
744     CopiesToReplace.push_back(UseMI);
745   } else {
746     if (UseMI->isCopy() && OpToFold.isReg() &&
747         UseMI->getOperand(0).getReg().isVirtual() &&
748         !UseMI->getOperand(1).getSubReg()) {
749       LLVM_DEBUG(dbgs() << "Folding " << OpToFold << "\n into " << *UseMI);
750       unsigned Size = TII->getOpSize(*UseMI, 1);
751       Register UseReg = OpToFold.getReg();
752       UseMI->getOperand(1).setReg(UseReg);
753       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
754       UseMI->getOperand(1).setIsKill(false);
755       CopiesToReplace.push_back(UseMI);
756       OpToFold.setIsKill(false);
757 
758       // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32
759       // can only accept VGPR or inline immediate. Recreate a reg_sequence with
760       // its initializers right here, so we will rematerialize immediates and
761       // avoid copies via different reg classes.
762       SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
763       if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
764           getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32, TII,
765                         *MRI)) {
766         const DebugLoc &DL = UseMI->getDebugLoc();
767         MachineBasicBlock &MBB = *UseMI->getParent();
768 
769         UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
770         for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I)
771           UseMI->RemoveOperand(I);
772 
773         MachineInstrBuilder B(*MBB.getParent(), UseMI);
774         DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
775         SmallSetVector<TargetInstrInfo::RegSubRegPair, 32> SeenAGPRs;
776         for (unsigned I = 0; I < Size / 4; ++I) {
777           MachineOperand *Def = Defs[I].first;
778           TargetInstrInfo::RegSubRegPair CopyToVGPR;
779           if (Def->isImm() &&
780               TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
781             int64_t Imm = Def->getImm();
782 
783             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
784             BuildMI(MBB, UseMI, DL,
785                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addImm(Imm);
786             B.addReg(Tmp);
787           } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) {
788             auto Src = getRegSubRegPair(*Def);
789             Def->setIsKill(false);
790             if (!SeenAGPRs.insert(Src)) {
791               // We cannot build a reg_sequence out of the same registers, they
792               // must be copied. Better do it here before copyPhysReg() created
793               // several reads to do the AGPR->VGPR->AGPR copy.
794               CopyToVGPR = Src;
795             } else {
796               B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0,
797                        Src.SubReg);
798             }
799           } else {
800             assert(Def->isReg());
801             Def->setIsKill(false);
802             auto Src = getRegSubRegPair(*Def);
803 
804             // Direct copy from SGPR to AGPR is not possible. To avoid creation
805             // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later,
806             // create a copy here and track if we already have such a copy.
807             if (TRI->isSGPRReg(*MRI, Src.Reg)) {
808               CopyToVGPR = Src;
809             } else {
810               auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
811               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def);
812               B.addReg(Tmp);
813             }
814           }
815 
816           if (CopyToVGPR.Reg) {
817             Register Vgpr;
818             if (VGPRCopies.count(CopyToVGPR)) {
819               Vgpr = VGPRCopies[CopyToVGPR];
820             } else {
821               Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
822               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def);
823               VGPRCopies[CopyToVGPR] = Vgpr;
824             }
825             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
826             BuildMI(MBB, UseMI, DL,
827                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addReg(Vgpr);
828             B.addReg(Tmp);
829           }
830 
831           B.addImm(Defs[I].second);
832         }
833         LLVM_DEBUG(dbgs() << "Folded " << *UseMI);
834         return;
835       }
836 
837       if (Size != 4)
838         return;
839       if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
840           TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()))
841         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
842       else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
843                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
844         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64));
845       else if (ST->hasGFX90AInsts() &&
846                TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
847                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
848         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_MOV_B32));
849       return;
850     }
851 
852     unsigned UseOpc = UseMI->getOpcode();
853     if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
854         (UseOpc == AMDGPU::V_READLANE_B32 &&
855          (int)UseOpIdx ==
856          AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
857       // %vgpr = V_MOV_B32 imm
858       // %sgpr = V_READFIRSTLANE_B32 %vgpr
859       // =>
860       // %sgpr = S_MOV_B32 imm
861       if (FoldingImmLike) {
862         if (execMayBeModifiedBeforeUse(*MRI,
863                                        UseMI->getOperand(UseOpIdx).getReg(),
864                                        *OpToFold.getParent(),
865                                        *UseMI))
866           return;
867 
868         UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
869 
870         if (OpToFold.isImm())
871           UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
872         else
873           UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex());
874         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
875         return;
876       }
877 
878       if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
879         if (execMayBeModifiedBeforeUse(*MRI,
880                                        UseMI->getOperand(UseOpIdx).getReg(),
881                                        *OpToFold.getParent(),
882                                        *UseMI))
883           return;
884 
885         // %vgpr = COPY %sgpr0
886         // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
887         // =>
888         // %sgpr1 = COPY %sgpr0
889         UseMI->setDesc(TII->get(AMDGPU::COPY));
890         UseMI->getOperand(1).setReg(OpToFold.getReg());
891         UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
892         UseMI->getOperand(1).setIsKill(false);
893         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
894         return;
895       }
896     }
897 
898     const MCInstrDesc &UseDesc = UseMI->getDesc();
899 
900     // Don't fold into target independent nodes.  Target independent opcodes
901     // don't have defined register classes.
902     if (UseDesc.isVariadic() ||
903         UseOp.isImplicit() ||
904         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
905       return;
906   }
907 
908   if (!FoldingImmLike) {
909     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
910 
911     // FIXME: We could try to change the instruction from 64-bit to 32-bit
912     // to enable more folding opportunities.  The shrink operands pass
913     // already does this.
914     return;
915   }
916 
917 
918   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
919   const TargetRegisterClass *FoldRC =
920     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
921 
922   // Split 64-bit constants into 32-bits for folding.
923   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
924     Register UseReg = UseOp.getReg();
925     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
926 
927     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
928       return;
929 
930     APInt Imm(64, OpToFold.getImm());
931     if (UseOp.getSubReg() == AMDGPU::sub0) {
932       Imm = Imm.getLoBits(32);
933     } else {
934       assert(UseOp.getSubReg() == AMDGPU::sub1);
935       Imm = Imm.getHiBits(32);
936     }
937 
938     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
939     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
940     return;
941   }
942 
943 
944 
945   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
946 }
947 
948 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
949                                   uint32_t LHS, uint32_t RHS) {
950   switch (Opcode) {
951   case AMDGPU::V_AND_B32_e64:
952   case AMDGPU::V_AND_B32_e32:
953   case AMDGPU::S_AND_B32:
954     Result = LHS & RHS;
955     return true;
956   case AMDGPU::V_OR_B32_e64:
957   case AMDGPU::V_OR_B32_e32:
958   case AMDGPU::S_OR_B32:
959     Result = LHS | RHS;
960     return true;
961   case AMDGPU::V_XOR_B32_e64:
962   case AMDGPU::V_XOR_B32_e32:
963   case AMDGPU::S_XOR_B32:
964     Result = LHS ^ RHS;
965     return true;
966   case AMDGPU::S_XNOR_B32:
967     Result = ~(LHS ^ RHS);
968     return true;
969   case AMDGPU::S_NAND_B32:
970     Result = ~(LHS & RHS);
971     return true;
972   case AMDGPU::S_NOR_B32:
973     Result = ~(LHS | RHS);
974     return true;
975   case AMDGPU::S_ANDN2_B32:
976     Result = LHS & ~RHS;
977     return true;
978   case AMDGPU::S_ORN2_B32:
979     Result = LHS | ~RHS;
980     return true;
981   case AMDGPU::V_LSHL_B32_e64:
982   case AMDGPU::V_LSHL_B32_e32:
983   case AMDGPU::S_LSHL_B32:
984     // The instruction ignores the high bits for out of bounds shifts.
985     Result = LHS << (RHS & 31);
986     return true;
987   case AMDGPU::V_LSHLREV_B32_e64:
988   case AMDGPU::V_LSHLREV_B32_e32:
989     Result = RHS << (LHS & 31);
990     return true;
991   case AMDGPU::V_LSHR_B32_e64:
992   case AMDGPU::V_LSHR_B32_e32:
993   case AMDGPU::S_LSHR_B32:
994     Result = LHS >> (RHS & 31);
995     return true;
996   case AMDGPU::V_LSHRREV_B32_e64:
997   case AMDGPU::V_LSHRREV_B32_e32:
998     Result = RHS >> (LHS & 31);
999     return true;
1000   case AMDGPU::V_ASHR_I32_e64:
1001   case AMDGPU::V_ASHR_I32_e32:
1002   case AMDGPU::S_ASHR_I32:
1003     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
1004     return true;
1005   case AMDGPU::V_ASHRREV_I32_e64:
1006   case AMDGPU::V_ASHRREV_I32_e32:
1007     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
1008     return true;
1009   default:
1010     return false;
1011   }
1012 }
1013 
1014 static unsigned getMovOpc(bool IsScalar) {
1015   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1016 }
1017 
1018 /// Remove any leftover implicit operands from mutating the instruction. e.g.
1019 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
1020 /// anymore.
1021 static void stripExtraCopyOperands(MachineInstr &MI) {
1022   const MCInstrDesc &Desc = MI.getDesc();
1023   unsigned NumOps = Desc.getNumOperands() +
1024                     Desc.getNumImplicitUses() +
1025                     Desc.getNumImplicitDefs();
1026 
1027   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
1028     MI.RemoveOperand(I);
1029 }
1030 
1031 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
1032   MI.setDesc(NewDesc);
1033   stripExtraCopyOperands(MI);
1034 }
1035 
1036 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
1037                                                MachineOperand &Op) {
1038   if (Op.isReg()) {
1039     // If this has a subregister, it obviously is a register source.
1040     if (Op.getSubReg() != AMDGPU::NoSubRegister || !Op.getReg().isVirtual())
1041       return &Op;
1042 
1043     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
1044     if (Def && Def->isMoveImmediate()) {
1045       MachineOperand &ImmSrc = Def->getOperand(1);
1046       if (ImmSrc.isImm())
1047         return &ImmSrc;
1048     }
1049   }
1050 
1051   return &Op;
1052 }
1053 
1054 // Try to simplify operations with a constant that may appear after instruction
1055 // selection.
1056 // TODO: See if a frame index with a fixed offset can fold.
1057 static bool tryConstantFoldOp(MachineRegisterInfo &MRI, const SIInstrInfo *TII,
1058                               MachineInstr *MI) {
1059   unsigned Opc = MI->getOpcode();
1060 
1061   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1062   if (Src0Idx == -1)
1063     return false;
1064   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
1065 
1066   if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1067        Opc == AMDGPU::S_NOT_B32) &&
1068       Src0->isImm()) {
1069     MI->getOperand(1).ChangeToImmediate(~Src0->getImm());
1070     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1071     return true;
1072   }
1073 
1074   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1075   if (Src1Idx == -1)
1076     return false;
1077   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
1078 
1079   if (!Src0->isImm() && !Src1->isImm())
1080     return false;
1081 
1082   // and k0, k1 -> v_mov_b32 (k0 & k1)
1083   // or k0, k1 -> v_mov_b32 (k0 | k1)
1084   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1085   if (Src0->isImm() && Src1->isImm()) {
1086     int32_t NewImm;
1087     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
1088       return false;
1089 
1090     const SIRegisterInfo &TRI = TII->getRegisterInfo();
1091     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
1092 
1093     // Be careful to change the right operand, src0 may belong to a different
1094     // instruction.
1095     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1096     MI->RemoveOperand(Src1Idx);
1097     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1098     return true;
1099   }
1100 
1101   if (!MI->isCommutable())
1102     return false;
1103 
1104   if (Src0->isImm() && !Src1->isImm()) {
1105     std::swap(Src0, Src1);
1106     std::swap(Src0Idx, Src1Idx);
1107   }
1108 
1109   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
1110   if (Opc == AMDGPU::V_OR_B32_e64 ||
1111       Opc == AMDGPU::V_OR_B32_e32 ||
1112       Opc == AMDGPU::S_OR_B32) {
1113     if (Src1Val == 0) {
1114       // y = or x, 0 => y = copy x
1115       MI->RemoveOperand(Src1Idx);
1116       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1117     } else if (Src1Val == -1) {
1118       // y = or x, -1 => y = v_mov_b32 -1
1119       MI->RemoveOperand(Src1Idx);
1120       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1121     } else
1122       return false;
1123 
1124     return true;
1125   }
1126 
1127   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
1128       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
1129       MI->getOpcode() == AMDGPU::S_AND_B32) {
1130     if (Src1Val == 0) {
1131       // y = and x, 0 => y = v_mov_b32 0
1132       MI->RemoveOperand(Src0Idx);
1133       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1134     } else if (Src1Val == -1) {
1135       // y = and x, -1 => y = copy x
1136       MI->RemoveOperand(Src1Idx);
1137       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1138       stripExtraCopyOperands(*MI);
1139     } else
1140       return false;
1141 
1142     return true;
1143   }
1144 
1145   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
1146       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
1147       MI->getOpcode() == AMDGPU::S_XOR_B32) {
1148     if (Src1Val == 0) {
1149       // y = xor x, 0 => y = copy x
1150       MI->RemoveOperand(Src1Idx);
1151       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1152       return true;
1153     }
1154   }
1155 
1156   return false;
1157 }
1158 
1159 // Try to fold an instruction into a simpler one
1160 bool SIFoldOperands::tryFoldCndMask(MachineInstr &MI) const {
1161   unsigned Opc = MI.getOpcode();
1162   if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1163       Opc != AMDGPU::V_CNDMASK_B64_PSEUDO)
1164     return false;
1165 
1166   MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1167   MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1168   if (!Src1->isIdenticalTo(*Src0)) {
1169     auto *Src0Imm = getImmOrMaterializedImm(*MRI, *Src0);
1170     auto *Src1Imm = getImmOrMaterializedImm(*MRI, *Src1);
1171     if (!Src1Imm->isIdenticalTo(*Src0Imm))
1172       return false;
1173   }
1174 
1175   int Src1ModIdx =
1176       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1177   int Src0ModIdx =
1178       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1179   if ((Src1ModIdx != -1 && MI.getOperand(Src1ModIdx).getImm() != 0) ||
1180       (Src0ModIdx != -1 && MI.getOperand(Src0ModIdx).getImm() != 0))
1181     return false;
1182 
1183   LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1184   auto &NewDesc =
1185       TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1186   int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1187   if (Src2Idx != -1)
1188     MI.RemoveOperand(Src2Idx);
1189   MI.RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1190   if (Src1ModIdx != -1)
1191     MI.RemoveOperand(Src1ModIdx);
1192   if (Src0ModIdx != -1)
1193     MI.RemoveOperand(Src0ModIdx);
1194   mutateCopyOp(MI, NewDesc);
1195   LLVM_DEBUG(dbgs() << MI);
1196   return true;
1197 }
1198 
1199 bool SIFoldOperands::tryFoldZeroHighBits(MachineInstr &MI) const {
1200   if (MI.getOpcode() != AMDGPU::V_AND_B32_e64 &&
1201       MI.getOpcode() != AMDGPU::V_AND_B32_e32)
1202     return false;
1203 
1204   MachineOperand *Src0 = getImmOrMaterializedImm(*MRI, MI.getOperand(1));
1205   if (!Src0->isImm() || Src0->getImm() != 0xffff)
1206     return false;
1207 
1208   Register Src1 = MI.getOperand(2).getReg();
1209   MachineInstr *SrcDef = MRI->getVRegDef(Src1);
1210   if (ST->zeroesHigh16BitsOfDest(SrcDef->getOpcode())) {
1211     Register Dst = MI.getOperand(0).getReg();
1212     MRI->replaceRegWith(Dst, SrcDef->getOperand(0).getReg());
1213     MI.eraseFromParent();
1214     return true;
1215   }
1216 
1217   return false;
1218 }
1219 
1220 bool SIFoldOperands::foldInstOperand(MachineInstr &MI,
1221                                      MachineOperand &OpToFold) const {
1222   // We need mutate the operands of new mov instructions to add implicit
1223   // uses of EXEC, but adding them invalidates the use_iterator, so defer
1224   // this.
1225   SmallVector<MachineInstr *, 4> CopiesToReplace;
1226   SmallVector<FoldCandidate, 4> FoldList;
1227   MachineOperand &Dst = MI.getOperand(0);
1228   bool Changed = false;
1229 
1230   if (OpToFold.isImm()) {
1231     for (auto &UseMI :
1232          make_early_inc_range(MRI->use_nodbg_instructions(Dst.getReg()))) {
1233       // Folding the immediate may reveal operations that can be constant
1234       // folded or replaced with a copy. This can happen for example after
1235       // frame indices are lowered to constants or from splitting 64-bit
1236       // constants.
1237       //
1238       // We may also encounter cases where one or both operands are
1239       // immediates materialized into a register, which would ordinarily not
1240       // be folded due to multiple uses or operand constraints.
1241       if (tryConstantFoldOp(*MRI, TII, &UseMI)) {
1242         LLVM_DEBUG(dbgs() << "Constant folded " << UseMI);
1243         Changed = true;
1244       }
1245     }
1246   }
1247 
1248   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1249   if (FoldingImm) {
1250     unsigned NumLiteralUses = 0;
1251     MachineOperand *NonInlineUse = nullptr;
1252     int NonInlineUseOpNo = -1;
1253 
1254     for (auto &Use :
1255          make_early_inc_range(MRI->use_nodbg_operands(Dst.getReg()))) {
1256       MachineInstr *UseMI = Use.getParent();
1257       unsigned OpNo = UseMI->getOperandNo(&Use);
1258 
1259       // Try to fold any inline immediate uses, and then only fold other
1260       // constants if they have one use.
1261       //
1262       // The legality of the inline immediate must be checked based on the use
1263       // operand, not the defining instruction, because 32-bit instructions
1264       // with 32-bit inline immediate sources may be used to materialize
1265       // constants used in 16-bit operands.
1266       //
1267       // e.g. it is unsafe to fold:
1268       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
1269       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
1270 
1271       // Folding immediates with more than one use will increase program size.
1272       // FIXME: This will also reduce register usage, which may be better
1273       // in some cases. A better heuristic is needed.
1274       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
1275         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1276       } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) {
1277         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1278       } else {
1279         if (++NumLiteralUses == 1) {
1280           NonInlineUse = &Use;
1281           NonInlineUseOpNo = OpNo;
1282         }
1283       }
1284     }
1285 
1286     if (NumLiteralUses == 1) {
1287       MachineInstr *UseMI = NonInlineUse->getParent();
1288       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
1289     }
1290   } else {
1291     // Folding register.
1292     SmallVector <MachineOperand *, 4> UsesToProcess;
1293     for (auto &Use : MRI->use_nodbg_operands(Dst.getReg()))
1294       UsesToProcess.push_back(&Use);
1295     for (auto U : UsesToProcess) {
1296       MachineInstr *UseMI = U->getParent();
1297 
1298       foldOperand(OpToFold, UseMI, UseMI->getOperandNo(U),
1299         FoldList, CopiesToReplace);
1300     }
1301   }
1302 
1303   if (CopiesToReplace.empty() && FoldList.empty())
1304     return Changed;
1305 
1306   MachineFunction *MF = MI.getParent()->getParent();
1307   // Make sure we add EXEC uses to any new v_mov instructions created.
1308   for (MachineInstr *Copy : CopiesToReplace)
1309     Copy->addImplicitDefUseOperands(*MF);
1310 
1311   for (FoldCandidate &Fold : FoldList) {
1312     assert(!Fold.isReg() || Fold.OpToFold);
1313     if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) {
1314       Register Reg = Fold.OpToFold->getReg();
1315       MachineInstr *DefMI = Fold.OpToFold->getParent();
1316       if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1317           execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1318         continue;
1319     }
1320     if (updateOperand(Fold, *TII, *TRI, *ST)) {
1321       // Clear kill flags.
1322       if (Fold.isReg()) {
1323         assert(Fold.OpToFold && Fold.OpToFold->isReg());
1324         // FIXME: Probably shouldn't bother trying to fold if not an
1325         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1326         // copies.
1327         MRI->clearKillFlags(Fold.OpToFold->getReg());
1328       }
1329       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1330                         << static_cast<int>(Fold.UseOpNo) << " of "
1331                         << *Fold.UseMI);
1332     } else if (Fold.isCommuted()) {
1333       // Restoring instruction's original operand order if fold has failed.
1334       TII->commuteInstruction(*Fold.UseMI, false);
1335     }
1336   }
1337   return true;
1338 }
1339 
1340 // Clamp patterns are canonically selected to v_max_* instructions, so only
1341 // handle them.
1342 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
1343   unsigned Op = MI.getOpcode();
1344   switch (Op) {
1345   case AMDGPU::V_MAX_F32_e64:
1346   case AMDGPU::V_MAX_F16_e64:
1347   case AMDGPU::V_MAX_F64_e64:
1348   case AMDGPU::V_PK_MAX_F16: {
1349     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1350       return nullptr;
1351 
1352     // Make sure sources are identical.
1353     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1354     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1355     if (!Src0->isReg() || !Src1->isReg() ||
1356         Src0->getReg() != Src1->getReg() ||
1357         Src0->getSubReg() != Src1->getSubReg() ||
1358         Src0->getSubReg() != AMDGPU::NoSubRegister)
1359       return nullptr;
1360 
1361     // Can't fold up if we have modifiers.
1362     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1363       return nullptr;
1364 
1365     unsigned Src0Mods
1366       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1367     unsigned Src1Mods
1368       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1369 
1370     // Having a 0 op_sel_hi would require swizzling the output in the source
1371     // instruction, which we can't do.
1372     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1373                                                       : 0u;
1374     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1375       return nullptr;
1376     return Src0;
1377   }
1378   default:
1379     return nullptr;
1380   }
1381 }
1382 
1383 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1384 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1385   const MachineOperand *ClampSrc = isClamp(MI);
1386   if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
1387     return false;
1388 
1389   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1390 
1391   // The type of clamp must be compatible.
1392   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1393     return false;
1394 
1395   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1396   if (!DefClamp)
1397     return false;
1398 
1399   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
1400 
1401   // Clamp is applied after omod, so it is OK if omod is set.
1402   DefClamp->setImm(1);
1403   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1404   MI.eraseFromParent();
1405 
1406   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1407   // instruction, so we might as well convert it to the more flexible VOP3-only
1408   // mad/fma form.
1409   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1410     Def->eraseFromParent();
1411 
1412   return true;
1413 }
1414 
1415 static int getOModValue(unsigned Opc, int64_t Val) {
1416   switch (Opc) {
1417   case AMDGPU::V_MUL_F64_e64: {
1418     switch (Val) {
1419     case 0x3fe0000000000000: // 0.5
1420       return SIOutMods::DIV2;
1421     case 0x4000000000000000: // 2.0
1422       return SIOutMods::MUL2;
1423     case 0x4010000000000000: // 4.0
1424       return SIOutMods::MUL4;
1425     default:
1426       return SIOutMods::NONE;
1427     }
1428   }
1429   case AMDGPU::V_MUL_F32_e64: {
1430     switch (static_cast<uint32_t>(Val)) {
1431     case 0x3f000000: // 0.5
1432       return SIOutMods::DIV2;
1433     case 0x40000000: // 2.0
1434       return SIOutMods::MUL2;
1435     case 0x40800000: // 4.0
1436       return SIOutMods::MUL4;
1437     default:
1438       return SIOutMods::NONE;
1439     }
1440   }
1441   case AMDGPU::V_MUL_F16_e64: {
1442     switch (static_cast<uint16_t>(Val)) {
1443     case 0x3800: // 0.5
1444       return SIOutMods::DIV2;
1445     case 0x4000: // 2.0
1446       return SIOutMods::MUL2;
1447     case 0x4400: // 4.0
1448       return SIOutMods::MUL4;
1449     default:
1450       return SIOutMods::NONE;
1451     }
1452   }
1453   default:
1454     llvm_unreachable("invalid mul opcode");
1455   }
1456 }
1457 
1458 // FIXME: Does this really not support denormals with f16?
1459 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1460 // handled, so will anything other than that break?
1461 std::pair<const MachineOperand *, int>
1462 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1463   unsigned Op = MI.getOpcode();
1464   switch (Op) {
1465   case AMDGPU::V_MUL_F64_e64:
1466   case AMDGPU::V_MUL_F32_e64:
1467   case AMDGPU::V_MUL_F16_e64: {
1468     // If output denormals are enabled, omod is ignored.
1469     if ((Op == AMDGPU::V_MUL_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1470         ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F16_e64) &&
1471          MFI->getMode().FP64FP16OutputDenormals))
1472       return std::make_pair(nullptr, SIOutMods::NONE);
1473 
1474     const MachineOperand *RegOp = nullptr;
1475     const MachineOperand *ImmOp = nullptr;
1476     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1477     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1478     if (Src0->isImm()) {
1479       ImmOp = Src0;
1480       RegOp = Src1;
1481     } else if (Src1->isImm()) {
1482       ImmOp = Src1;
1483       RegOp = Src0;
1484     } else
1485       return std::make_pair(nullptr, SIOutMods::NONE);
1486 
1487     int OMod = getOModValue(Op, ImmOp->getImm());
1488     if (OMod == SIOutMods::NONE ||
1489         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1490         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1491         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1492         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1493       return std::make_pair(nullptr, SIOutMods::NONE);
1494 
1495     return std::make_pair(RegOp, OMod);
1496   }
1497   case AMDGPU::V_ADD_F64_e64:
1498   case AMDGPU::V_ADD_F32_e64:
1499   case AMDGPU::V_ADD_F16_e64: {
1500     // If output denormals are enabled, omod is ignored.
1501     if ((Op == AMDGPU::V_ADD_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1502         ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F16_e64) &&
1503          MFI->getMode().FP64FP16OutputDenormals))
1504       return std::make_pair(nullptr, SIOutMods::NONE);
1505 
1506     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1507     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1508     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1509 
1510     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1511         Src0->getSubReg() == Src1->getSubReg() &&
1512         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1513         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1514         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1515         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1516       return std::make_pair(Src0, SIOutMods::MUL2);
1517 
1518     return std::make_pair(nullptr, SIOutMods::NONE);
1519   }
1520   default:
1521     return std::make_pair(nullptr, SIOutMods::NONE);
1522   }
1523 }
1524 
1525 // FIXME: Does this need to check IEEE bit on function?
1526 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1527   const MachineOperand *RegOp;
1528   int OMod;
1529   std::tie(RegOp, OMod) = isOMod(MI);
1530   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1531       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1532       !MRI->hasOneNonDBGUser(RegOp->getReg()))
1533     return false;
1534 
1535   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1536   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1537   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1538     return false;
1539 
1540   // Clamp is applied after omod. If the source already has clamp set, don't
1541   // fold it.
1542   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1543     return false;
1544 
1545   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
1546 
1547   DefOMod->setImm(OMod);
1548   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1549   MI.eraseFromParent();
1550 
1551   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1552   // instruction, so we might as well convert it to the more flexible VOP3-only
1553   // mad/fma form.
1554   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1555     Def->eraseFromParent();
1556 
1557   return true;
1558 }
1559 
1560 // Try to fold a reg_sequence with vgpr output and agpr inputs into an
1561 // instruction which can take an agpr. So far that means a store.
1562 bool SIFoldOperands::tryFoldRegSequence(MachineInstr &MI) {
1563   assert(MI.isRegSequence());
1564   auto Reg = MI.getOperand(0).getReg();
1565 
1566   if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
1567       !MRI->hasOneNonDBGUse(Reg))
1568     return false;
1569 
1570   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
1571   if (!getRegSeqInit(Defs, Reg, MCOI::OPERAND_REGISTER, TII, *MRI))
1572     return false;
1573 
1574   for (auto &Def : Defs) {
1575     const auto *Op = Def.first;
1576     if (!Op->isReg())
1577       return false;
1578     if (TRI->isAGPR(*MRI, Op->getReg()))
1579       continue;
1580     // Maybe this is a COPY from AREG
1581     const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
1582     if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
1583       return false;
1584     if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
1585       return false;
1586   }
1587 
1588   MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
1589   MachineInstr *UseMI = Op->getParent();
1590   while (UseMI->isCopy() && !Op->getSubReg()) {
1591     Reg = UseMI->getOperand(0).getReg();
1592     if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
1593       return false;
1594     Op = &*MRI->use_nodbg_begin(Reg);
1595     UseMI = Op->getParent();
1596   }
1597 
1598   if (Op->getSubReg())
1599     return false;
1600 
1601   unsigned OpIdx = Op - &UseMI->getOperand(0);
1602   const MCInstrDesc &InstDesc = UseMI->getDesc();
1603   if (!TRI->isVectorSuperClass(
1604           TRI->getRegClass(InstDesc.OpInfo[OpIdx].RegClass)))
1605     return false;
1606 
1607   const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
1608   auto Dst = MRI->createVirtualRegister(NewDstRC);
1609   auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1610                     TII->get(AMDGPU::REG_SEQUENCE), Dst);
1611 
1612   for (unsigned I = 0; I < Defs.size(); ++I) {
1613     MachineOperand *Def = Defs[I].first;
1614     Def->setIsKill(false);
1615     if (TRI->isAGPR(*MRI, Def->getReg())) {
1616       RS.add(*Def);
1617     } else { // This is a copy
1618       MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
1619       SubDef->getOperand(1).setIsKill(false);
1620       RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
1621     }
1622     RS.addImm(Defs[I].second);
1623   }
1624 
1625   Op->setReg(Dst);
1626   if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
1627     Op->setReg(Reg);
1628     RS->eraseFromParent();
1629     return false;
1630   }
1631 
1632   LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
1633 
1634   // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
1635   // in which case we can erase them all later in runOnMachineFunction.
1636   if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
1637     MI.eraseFromParent();
1638   return true;
1639 }
1640 
1641 // Try to hoist an AGPR to VGPR copy out of the loop across a LCSSA PHI.
1642 // This should allow folding of an AGPR into a consumer which may support it.
1643 // I.e.:
1644 //
1645 // loop:                             // loop:
1646 //   %1:vreg = COPY %0:areg          // exit:
1647 // exit:                          => //   %1:areg = PHI %0:areg, %loop
1648 //   %2:vreg = PHI %1:vreg, %loop    //   %2:vreg = COPY %1:areg
1649 bool SIFoldOperands::tryFoldLCSSAPhi(MachineInstr &PHI) {
1650   assert(PHI.isPHI());
1651 
1652   if (PHI.getNumExplicitOperands() != 3) // Single input LCSSA PHI
1653     return false;
1654 
1655   Register PhiIn = PHI.getOperand(1).getReg();
1656   Register PhiOut = PHI.getOperand(0).getReg();
1657   if (PHI.getOperand(1).getSubReg() ||
1658       !TRI->isVGPR(*MRI, PhiIn) || !TRI->isVGPR(*MRI, PhiOut))
1659     return false;
1660 
1661   // A single use should not matter for correctness, but if it has another use
1662   // inside the loop we may perform copy twice in a worst case.
1663   if (!MRI->hasOneNonDBGUse(PhiIn))
1664     return false;
1665 
1666   MachineInstr *Copy = MRI->getVRegDef(PhiIn);
1667   if (!Copy || !Copy->isCopy())
1668     return false;
1669 
1670   Register CopyIn = Copy->getOperand(1).getReg();
1671   if (!TRI->isAGPR(*MRI, CopyIn) || Copy->getOperand(1).getSubReg())
1672     return false;
1673 
1674   const TargetRegisterClass *ARC = MRI->getRegClass(CopyIn);
1675   Register NewReg = MRI->createVirtualRegister(ARC);
1676   PHI.getOperand(1).setReg(CopyIn);
1677   PHI.getOperand(0).setReg(NewReg);
1678 
1679   MachineBasicBlock *MBB = PHI.getParent();
1680   BuildMI(*MBB, MBB->getFirstNonPHI(), Copy->getDebugLoc(),
1681           TII->get(AMDGPU::COPY), PhiOut)
1682     .addReg(NewReg, RegState::Kill);
1683   Copy->eraseFromParent(); // We know this copy had a single use.
1684 
1685   LLVM_DEBUG(dbgs() << "Folded " << PHI);
1686 
1687   return true;
1688 }
1689 
1690 // Attempt to convert VGPR load to an AGPR load.
1691 bool SIFoldOperands::tryFoldLoad(MachineInstr &MI) {
1692   assert(MI.mayLoad());
1693   if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
1694     return false;
1695 
1696   MachineOperand &Def = MI.getOperand(0);
1697   if (!Def.isDef())
1698     return false;
1699 
1700   Register DefReg = Def.getReg();
1701 
1702   if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
1703     return false;
1704 
1705   SmallVector<const MachineInstr*, 8> Users;
1706   SmallVector<Register, 8> MoveRegs;
1707   for (const MachineInstr &I : MRI->use_nodbg_instructions(DefReg)) {
1708     Users.push_back(&I);
1709   }
1710   if (Users.empty())
1711     return false;
1712 
1713   // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
1714   while (!Users.empty()) {
1715     const MachineInstr *I = Users.pop_back_val();
1716     if (!I->isCopy() && !I->isRegSequence())
1717       return false;
1718     Register DstReg = I->getOperand(0).getReg();
1719     if (TRI->isAGPR(*MRI, DstReg))
1720       continue;
1721     MoveRegs.push_back(DstReg);
1722     for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg)) {
1723       Users.push_back(&U);
1724     }
1725   }
1726 
1727   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
1728   MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
1729   if (!TII->isOperandLegal(MI, 0, &Def)) {
1730     MRI->setRegClass(DefReg, RC);
1731     return false;
1732   }
1733 
1734   while (!MoveRegs.empty()) {
1735     Register Reg = MoveRegs.pop_back_val();
1736     MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
1737   }
1738 
1739   LLVM_DEBUG(dbgs() << "Folded " << MI);
1740 
1741   return true;
1742 }
1743 
1744 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1745   if (skipFunction(MF.getFunction()))
1746     return false;
1747 
1748   MRI = &MF.getRegInfo();
1749   ST = &MF.getSubtarget<GCNSubtarget>();
1750   TII = ST->getInstrInfo();
1751   TRI = &TII->getRegisterInfo();
1752   MFI = MF.getInfo<SIMachineFunctionInfo>();
1753 
1754   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1755   // correctly handle signed zeros.
1756   //
1757   // FIXME: Also need to check strictfp
1758   bool IsIEEEMode = MFI->getMode().IEEE;
1759   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1760 
1761   bool Changed = false;
1762   for (MachineBasicBlock *MBB : depth_first(&MF)) {
1763     MachineOperand *CurrentKnownM0Val = nullptr;
1764     for (auto &MI : make_early_inc_range(*MBB)) {
1765       Changed |= tryFoldCndMask(MI);
1766 
1767       if (tryFoldZeroHighBits(MI)) {
1768         Changed = true;
1769         continue;
1770       }
1771 
1772       if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
1773         Changed = true;
1774         continue;
1775       }
1776 
1777       if (MI.isPHI() && tryFoldLCSSAPhi(MI)) {
1778         Changed = true;
1779         continue;
1780       }
1781 
1782       if (MI.mayLoad() && tryFoldLoad(MI)) {
1783         Changed = true;
1784         continue;
1785       }
1786 
1787       if (!TII->isFoldableCopy(MI)) {
1788         // Saw an unknown clobber of m0, so we no longer know what it is.
1789         if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
1790           CurrentKnownM0Val = nullptr;
1791 
1792         // TODO: Omod might be OK if there is NSZ only on the source
1793         // instruction, and not the omod multiply.
1794         if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1795             !tryFoldOMod(MI))
1796           Changed |= tryFoldClamp(MI);
1797 
1798         continue;
1799       }
1800 
1801       // Specially track simple redefs of m0 to the same value in a block, so we
1802       // can erase the later ones.
1803       if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1804         MachineOperand &NewM0Val = MI.getOperand(1);
1805         if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1806           MI.eraseFromParent();
1807           Changed = true;
1808           continue;
1809         }
1810 
1811         // We aren't tracking other physical registers
1812         CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical()) ?
1813           nullptr : &NewM0Val;
1814         continue;
1815       }
1816 
1817       MachineOperand &OpToFold = MI.getOperand(1);
1818       bool FoldingImm =
1819           OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1820 
1821       // FIXME: We could also be folding things like TargetIndexes.
1822       if (!FoldingImm && !OpToFold.isReg())
1823         continue;
1824 
1825       if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1826         continue;
1827 
1828       // Prevent folding operands backwards in the function. For example,
1829       // the COPY opcode must not be replaced by 1 in this example:
1830       //
1831       //    %3 = COPY %vgpr0; VGPR_32:%3
1832       //    ...
1833       //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1834       if (!MI.getOperand(0).getReg().isVirtual())
1835         continue;
1836 
1837       Changed |= foldInstOperand(MI, OpToFold);
1838 
1839       // If we managed to fold all uses of this copy then we might as well
1840       // delete it now.
1841       // The only reason we need to follow chains of copies here is that
1842       // tryFoldRegSequence looks forward through copies before folding a
1843       // REG_SEQUENCE into its eventual users.
1844       auto *InstToErase = &MI;
1845       while (MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1846         auto &SrcOp = InstToErase->getOperand(1);
1847         auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
1848         InstToErase->eraseFromParent();
1849         Changed = true;
1850         InstToErase = nullptr;
1851         if (!SrcReg || SrcReg.isPhysical())
1852           break;
1853         InstToErase = MRI->getVRegDef(SrcReg);
1854         if (!InstToErase || !TII->isFoldableCopy(*InstToErase))
1855           break;
1856       }
1857       if (InstToErase && InstToErase->isRegSequence() &&
1858           MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1859         InstToErase->eraseFromParent();
1860         Changed = true;
1861       }
1862     }
1863   }
1864   return Changed;
1865 }
1866