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   case AMDGPU::V_MOV_B64_e32:
494   case AMDGPU::V_MOV_B64_e64:
495     // Do not fold into an indirect mov.
496     return !MI.hasRegisterImplicitUseOperand(AMDGPU::M0);
497   }
498 
499   return true;
500   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
501 }
502 
503 // Find a def of the UseReg, check if it is a reg_sequence and find initializers
504 // for each subreg, tracking it to foldable inline immediate if possible.
505 // Returns true on success.
506 static bool getRegSeqInit(
507     SmallVectorImpl<std::pair<MachineOperand*, unsigned>> &Defs,
508     Register UseReg, uint8_t OpTy,
509     const SIInstrInfo *TII, const MachineRegisterInfo &MRI) {
510   MachineInstr *Def = MRI.getVRegDef(UseReg);
511   if (!Def || !Def->isRegSequence())
512     return false;
513 
514   for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) {
515     MachineOperand *Sub = &Def->getOperand(I);
516     assert(Sub->isReg());
517 
518     for (MachineInstr *SubDef = MRI.getVRegDef(Sub->getReg());
519          SubDef && Sub->isReg() && Sub->getReg().isVirtual() &&
520          !Sub->getSubReg() && TII->isFoldableCopy(*SubDef);
521          SubDef = MRI.getVRegDef(Sub->getReg())) {
522       MachineOperand *Op = &SubDef->getOperand(1);
523       if (Op->isImm()) {
524         if (TII->isInlineConstant(*Op, OpTy))
525           Sub = Op;
526         break;
527       }
528       if (!Op->isReg() || Op->getReg().isPhysical())
529         break;
530       Sub = Op;
531     }
532 
533     Defs.emplace_back(Sub, Def->getOperand(I + 1).getImm());
534   }
535 
536   return true;
537 }
538 
539 static bool tryToFoldACImm(const SIInstrInfo *TII,
540                            const MachineOperand &OpToFold,
541                            MachineInstr *UseMI,
542                            unsigned UseOpIdx,
543                            SmallVectorImpl<FoldCandidate> &FoldList) {
544   const MCInstrDesc &Desc = UseMI->getDesc();
545   const MCOperandInfo *OpInfo = Desc.OpInfo;
546   if (!OpInfo || UseOpIdx >= Desc.getNumOperands())
547     return false;
548 
549   uint8_t OpTy = OpInfo[UseOpIdx].OperandType;
550   if ((OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST ||
551        OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST) &&
552       (OpTy < AMDGPU::OPERAND_REG_INLINE_C_FIRST ||
553        OpTy > AMDGPU::OPERAND_REG_INLINE_C_LAST))
554     return false;
555 
556   if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) &&
557       TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) {
558     UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm());
559     return true;
560   }
561 
562   if (!OpToFold.isReg())
563     return false;
564 
565   Register UseReg = OpToFold.getReg();
566   if (!UseReg.isVirtual())
567     return false;
568 
569   if (isUseMIInFoldList(FoldList, UseMI))
570     return false;
571 
572   MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo();
573 
574   // Maybe it is just a COPY of an immediate itself.
575   MachineInstr *Def = MRI.getVRegDef(UseReg);
576   MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
577   if (!UseOp.getSubReg() && Def && TII->isFoldableCopy(*Def)) {
578     MachineOperand &DefOp = Def->getOperand(1);
579     if (DefOp.isImm() && TII->isInlineConstant(DefOp, OpTy) &&
580         TII->isOperandLegal(*UseMI, UseOpIdx, &DefOp)) {
581       UseMI->getOperand(UseOpIdx).ChangeToImmediate(DefOp.getImm());
582       return true;
583     }
584   }
585 
586   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
587   if (!getRegSeqInit(Defs, UseReg, OpTy, TII, MRI))
588     return false;
589 
590   int32_t Imm;
591   for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
592     const MachineOperand *Op = Defs[I].first;
593     if (!Op->isImm())
594       return false;
595 
596     auto SubImm = Op->getImm();
597     if (!I) {
598       Imm = SubImm;
599       if (!TII->isInlineConstant(*Op, OpTy) ||
600           !TII->isOperandLegal(*UseMI, UseOpIdx, Op))
601         return false;
602 
603       continue;
604     }
605     if (Imm != SubImm)
606       return false; // Can only fold splat constants
607   }
608 
609   appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first);
610   return true;
611 }
612 
613 void SIFoldOperands::foldOperand(
614   MachineOperand &OpToFold,
615   MachineInstr *UseMI,
616   int UseOpIdx,
617   SmallVectorImpl<FoldCandidate> &FoldList,
618   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
619   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
620 
621   if (!isUseSafeToFold(TII, *UseMI, UseOp))
622     return;
623 
624   // FIXME: Fold operands with subregs.
625   if (UseOp.isReg() && OpToFold.isReg()) {
626     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
627       return;
628   }
629 
630   // Special case for REG_SEQUENCE: We can't fold literals into
631   // REG_SEQUENCE instructions, so we have to fold them into the
632   // uses of REG_SEQUENCE.
633   if (UseMI->isRegSequence()) {
634     Register RegSeqDstReg = UseMI->getOperand(0).getReg();
635     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
636 
637     for (auto &RSUse : make_early_inc_range(MRI->use_nodbg_operands(RegSeqDstReg))) {
638       MachineInstr *RSUseMI = RSUse.getParent();
639 
640       if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI,
641                          RSUseMI->getOperandNo(&RSUse), FoldList))
642         continue;
643 
644       if (RSUse.getSubReg() != RegSeqDstSubReg)
645         continue;
646 
647       foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(&RSUse), FoldList,
648                   CopiesToReplace);
649     }
650 
651     return;
652   }
653 
654   if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList))
655     return;
656 
657   if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) {
658     // Verify that this is a stack access.
659     // FIXME: Should probably use stack pseudos before frame lowering.
660 
661     if (TII->isMUBUF(*UseMI)) {
662       if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
663           MFI->getScratchRSrcReg())
664         return;
665 
666       // Ensure this is either relative to the current frame or the current
667       // wave.
668       MachineOperand &SOff =
669           *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
670       if (!SOff.isImm() || SOff.getImm() != 0)
671         return;
672     }
673 
674     // A frame index will resolve to a positive constant, so it should always be
675     // safe to fold the addressing mode, even pre-GFX9.
676     UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex());
677 
678     if (TII->isFLATScratch(*UseMI) &&
679         AMDGPU::getNamedOperandIdx(UseMI->getOpcode(),
680                                    AMDGPU::OpName::vaddr) != -1 &&
681         AMDGPU::getNamedOperandIdx(UseMI->getOpcode(),
682                                    AMDGPU::OpName::saddr) == -1) {
683       unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(UseMI->getOpcode());
684       UseMI->setDesc(TII->get(NewOpc));
685     }
686 
687     return;
688   }
689 
690   bool FoldingImmLike =
691       OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
692 
693   if (FoldingImmLike && UseMI->isCopy()) {
694     Register DestReg = UseMI->getOperand(0).getReg();
695     Register SrcReg = UseMI->getOperand(1).getReg();
696     assert(SrcReg.isVirtual());
697 
698     const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
699 
700     // Don't fold into a copy to a physical register with the same class. Doing
701     // so would interfere with the register coalescer's logic which would avoid
702     // redundant initializations.
703     if (DestReg.isPhysical() && SrcRC->contains(DestReg))
704       return;
705 
706     const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
707     if (!DestReg.isPhysical()) {
708       if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) {
709         SmallVector<FoldCandidate, 4> CopyUses;
710         for (auto &Use : MRI->use_nodbg_operands(DestReg)) {
711           // There's no point trying to fold into an implicit operand.
712           if (Use.isImplicit())
713             continue;
714 
715           CopyUses.emplace_back(Use.getParent(),
716                                 Use.getParent()->getOperandNo(&Use),
717                                 &UseMI->getOperand(1));
718         }
719         for (auto &F : CopyUses) {
720           foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, FoldList, CopiesToReplace);
721         }
722       }
723 
724       if (DestRC == &AMDGPU::AGPR_32RegClass &&
725           TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
726         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
727         UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
728         CopiesToReplace.push_back(UseMI);
729         return;
730       }
731     }
732 
733     // In order to fold immediates into copies, we need to change the
734     // copy to a MOV.
735 
736     unsigned MovOp = TII->getMovOpcode(DestRC);
737     if (MovOp == AMDGPU::COPY)
738       return;
739 
740     UseMI->setDesc(TII->get(MovOp));
741     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
742     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
743     while (ImpOpI != ImpOpE) {
744       MachineInstr::mop_iterator Tmp = ImpOpI;
745       ImpOpI++;
746       UseMI->RemoveOperand(UseMI->getOperandNo(Tmp));
747     }
748     CopiesToReplace.push_back(UseMI);
749   } else {
750     if (UseMI->isCopy() && OpToFold.isReg() &&
751         UseMI->getOperand(0).getReg().isVirtual() &&
752         !UseMI->getOperand(1).getSubReg()) {
753       LLVM_DEBUG(dbgs() << "Folding " << OpToFold << "\n into " << *UseMI);
754       unsigned Size = TII->getOpSize(*UseMI, 1);
755       Register UseReg = OpToFold.getReg();
756       UseMI->getOperand(1).setReg(UseReg);
757       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
758       UseMI->getOperand(1).setIsKill(false);
759       CopiesToReplace.push_back(UseMI);
760       OpToFold.setIsKill(false);
761 
762       // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32
763       // can only accept VGPR or inline immediate. Recreate a reg_sequence with
764       // its initializers right here, so we will rematerialize immediates and
765       // avoid copies via different reg classes.
766       SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
767       if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
768           getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32, TII,
769                         *MRI)) {
770         const DebugLoc &DL = UseMI->getDebugLoc();
771         MachineBasicBlock &MBB = *UseMI->getParent();
772 
773         UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
774         for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I)
775           UseMI->RemoveOperand(I);
776 
777         MachineInstrBuilder B(*MBB.getParent(), UseMI);
778         DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
779         SmallSetVector<TargetInstrInfo::RegSubRegPair, 32> SeenAGPRs;
780         for (unsigned I = 0; I < Size / 4; ++I) {
781           MachineOperand *Def = Defs[I].first;
782           TargetInstrInfo::RegSubRegPair CopyToVGPR;
783           if (Def->isImm() &&
784               TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
785             int64_t Imm = Def->getImm();
786 
787             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
788             BuildMI(MBB, UseMI, DL,
789                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addImm(Imm);
790             B.addReg(Tmp);
791           } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) {
792             auto Src = getRegSubRegPair(*Def);
793             Def->setIsKill(false);
794             if (!SeenAGPRs.insert(Src)) {
795               // We cannot build a reg_sequence out of the same registers, they
796               // must be copied. Better do it here before copyPhysReg() created
797               // several reads to do the AGPR->VGPR->AGPR copy.
798               CopyToVGPR = Src;
799             } else {
800               B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0,
801                        Src.SubReg);
802             }
803           } else {
804             assert(Def->isReg());
805             Def->setIsKill(false);
806             auto Src = getRegSubRegPair(*Def);
807 
808             // Direct copy from SGPR to AGPR is not possible. To avoid creation
809             // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later,
810             // create a copy here and track if we already have such a copy.
811             if (TRI->isSGPRReg(*MRI, Src.Reg)) {
812               CopyToVGPR = Src;
813             } else {
814               auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
815               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def);
816               B.addReg(Tmp);
817             }
818           }
819 
820           if (CopyToVGPR.Reg) {
821             Register Vgpr;
822             if (VGPRCopies.count(CopyToVGPR)) {
823               Vgpr = VGPRCopies[CopyToVGPR];
824             } else {
825               Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
826               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def);
827               VGPRCopies[CopyToVGPR] = Vgpr;
828             }
829             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
830             BuildMI(MBB, UseMI, DL,
831                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addReg(Vgpr);
832             B.addReg(Tmp);
833           }
834 
835           B.addImm(Defs[I].second);
836         }
837         LLVM_DEBUG(dbgs() << "Folded " << *UseMI);
838         return;
839       }
840 
841       if (Size != 4)
842         return;
843       if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
844           TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()))
845         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
846       else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
847                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
848         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64));
849       else if (ST->hasGFX90AInsts() &&
850                TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
851                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
852         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_MOV_B32));
853       return;
854     }
855 
856     unsigned UseOpc = UseMI->getOpcode();
857     if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
858         (UseOpc == AMDGPU::V_READLANE_B32 &&
859          (int)UseOpIdx ==
860          AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
861       // %vgpr = V_MOV_B32 imm
862       // %sgpr = V_READFIRSTLANE_B32 %vgpr
863       // =>
864       // %sgpr = S_MOV_B32 imm
865       if (FoldingImmLike) {
866         if (execMayBeModifiedBeforeUse(*MRI,
867                                        UseMI->getOperand(UseOpIdx).getReg(),
868                                        *OpToFold.getParent(),
869                                        *UseMI))
870           return;
871 
872         UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
873 
874         if (OpToFold.isImm())
875           UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
876         else
877           UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex());
878         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
879         return;
880       }
881 
882       if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
883         if (execMayBeModifiedBeforeUse(*MRI,
884                                        UseMI->getOperand(UseOpIdx).getReg(),
885                                        *OpToFold.getParent(),
886                                        *UseMI))
887           return;
888 
889         // %vgpr = COPY %sgpr0
890         // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
891         // =>
892         // %sgpr1 = COPY %sgpr0
893         UseMI->setDesc(TII->get(AMDGPU::COPY));
894         UseMI->getOperand(1).setReg(OpToFold.getReg());
895         UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
896         UseMI->getOperand(1).setIsKill(false);
897         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
898         return;
899       }
900     }
901 
902     const MCInstrDesc &UseDesc = UseMI->getDesc();
903 
904     // Don't fold into target independent nodes.  Target independent opcodes
905     // don't have defined register classes.
906     if (UseDesc.isVariadic() ||
907         UseOp.isImplicit() ||
908         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
909       return;
910   }
911 
912   if (!FoldingImmLike) {
913     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
914 
915     // FIXME: We could try to change the instruction from 64-bit to 32-bit
916     // to enable more folding opportunities.  The shrink operands pass
917     // already does this.
918     return;
919   }
920 
921 
922   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
923   const TargetRegisterClass *FoldRC =
924     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
925 
926   // Split 64-bit constants into 32-bits for folding.
927   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
928     Register UseReg = UseOp.getReg();
929     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
930 
931     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
932       return;
933 
934     APInt Imm(64, OpToFold.getImm());
935     if (UseOp.getSubReg() == AMDGPU::sub0) {
936       Imm = Imm.getLoBits(32);
937     } else {
938       assert(UseOp.getSubReg() == AMDGPU::sub1);
939       Imm = Imm.getHiBits(32);
940     }
941 
942     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
943     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
944     return;
945   }
946 
947 
948 
949   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
950 }
951 
952 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
953                                   uint32_t LHS, uint32_t RHS) {
954   switch (Opcode) {
955   case AMDGPU::V_AND_B32_e64:
956   case AMDGPU::V_AND_B32_e32:
957   case AMDGPU::S_AND_B32:
958     Result = LHS & RHS;
959     return true;
960   case AMDGPU::V_OR_B32_e64:
961   case AMDGPU::V_OR_B32_e32:
962   case AMDGPU::S_OR_B32:
963     Result = LHS | RHS;
964     return true;
965   case AMDGPU::V_XOR_B32_e64:
966   case AMDGPU::V_XOR_B32_e32:
967   case AMDGPU::S_XOR_B32:
968     Result = LHS ^ RHS;
969     return true;
970   case AMDGPU::S_XNOR_B32:
971     Result = ~(LHS ^ RHS);
972     return true;
973   case AMDGPU::S_NAND_B32:
974     Result = ~(LHS & RHS);
975     return true;
976   case AMDGPU::S_NOR_B32:
977     Result = ~(LHS | RHS);
978     return true;
979   case AMDGPU::S_ANDN2_B32:
980     Result = LHS & ~RHS;
981     return true;
982   case AMDGPU::S_ORN2_B32:
983     Result = LHS | ~RHS;
984     return true;
985   case AMDGPU::V_LSHL_B32_e64:
986   case AMDGPU::V_LSHL_B32_e32:
987   case AMDGPU::S_LSHL_B32:
988     // The instruction ignores the high bits for out of bounds shifts.
989     Result = LHS << (RHS & 31);
990     return true;
991   case AMDGPU::V_LSHLREV_B32_e64:
992   case AMDGPU::V_LSHLREV_B32_e32:
993     Result = RHS << (LHS & 31);
994     return true;
995   case AMDGPU::V_LSHR_B32_e64:
996   case AMDGPU::V_LSHR_B32_e32:
997   case AMDGPU::S_LSHR_B32:
998     Result = LHS >> (RHS & 31);
999     return true;
1000   case AMDGPU::V_LSHRREV_B32_e64:
1001   case AMDGPU::V_LSHRREV_B32_e32:
1002     Result = RHS >> (LHS & 31);
1003     return true;
1004   case AMDGPU::V_ASHR_I32_e64:
1005   case AMDGPU::V_ASHR_I32_e32:
1006   case AMDGPU::S_ASHR_I32:
1007     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
1008     return true;
1009   case AMDGPU::V_ASHRREV_I32_e64:
1010   case AMDGPU::V_ASHRREV_I32_e32:
1011     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
1012     return true;
1013   default:
1014     return false;
1015   }
1016 }
1017 
1018 static unsigned getMovOpc(bool IsScalar) {
1019   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1020 }
1021 
1022 /// Remove any leftover implicit operands from mutating the instruction. e.g.
1023 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
1024 /// anymore.
1025 static void stripExtraCopyOperands(MachineInstr &MI) {
1026   const MCInstrDesc &Desc = MI.getDesc();
1027   unsigned NumOps = Desc.getNumOperands() +
1028                     Desc.getNumImplicitUses() +
1029                     Desc.getNumImplicitDefs();
1030 
1031   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
1032     MI.RemoveOperand(I);
1033 }
1034 
1035 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
1036   MI.setDesc(NewDesc);
1037   stripExtraCopyOperands(MI);
1038 }
1039 
1040 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
1041                                                MachineOperand &Op) {
1042   if (Op.isReg()) {
1043     // If this has a subregister, it obviously is a register source.
1044     if (Op.getSubReg() != AMDGPU::NoSubRegister || !Op.getReg().isVirtual())
1045       return &Op;
1046 
1047     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
1048     if (Def && Def->isMoveImmediate()) {
1049       MachineOperand &ImmSrc = Def->getOperand(1);
1050       if (ImmSrc.isImm())
1051         return &ImmSrc;
1052     }
1053   }
1054 
1055   return &Op;
1056 }
1057 
1058 // Try to simplify operations with a constant that may appear after instruction
1059 // selection.
1060 // TODO: See if a frame index with a fixed offset can fold.
1061 static bool tryConstantFoldOp(MachineRegisterInfo &MRI, const SIInstrInfo *TII,
1062                               MachineInstr *MI) {
1063   unsigned Opc = MI->getOpcode();
1064 
1065   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1066   if (Src0Idx == -1)
1067     return false;
1068   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
1069 
1070   if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1071        Opc == AMDGPU::S_NOT_B32) &&
1072       Src0->isImm()) {
1073     MI->getOperand(1).ChangeToImmediate(~Src0->getImm());
1074     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1075     return true;
1076   }
1077 
1078   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1079   if (Src1Idx == -1)
1080     return false;
1081   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
1082 
1083   if (!Src0->isImm() && !Src1->isImm())
1084     return false;
1085 
1086   // and k0, k1 -> v_mov_b32 (k0 & k1)
1087   // or k0, k1 -> v_mov_b32 (k0 | k1)
1088   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1089   if (Src0->isImm() && Src1->isImm()) {
1090     int32_t NewImm;
1091     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
1092       return false;
1093 
1094     const SIRegisterInfo &TRI = TII->getRegisterInfo();
1095     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
1096 
1097     // Be careful to change the right operand, src0 may belong to a different
1098     // instruction.
1099     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1100     MI->RemoveOperand(Src1Idx);
1101     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1102     return true;
1103   }
1104 
1105   if (!MI->isCommutable())
1106     return false;
1107 
1108   if (Src0->isImm() && !Src1->isImm()) {
1109     std::swap(Src0, Src1);
1110     std::swap(Src0Idx, Src1Idx);
1111   }
1112 
1113   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
1114   if (Opc == AMDGPU::V_OR_B32_e64 ||
1115       Opc == AMDGPU::V_OR_B32_e32 ||
1116       Opc == AMDGPU::S_OR_B32) {
1117     if (Src1Val == 0) {
1118       // y = or x, 0 => y = copy x
1119       MI->RemoveOperand(Src1Idx);
1120       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1121     } else if (Src1Val == -1) {
1122       // y = or x, -1 => y = v_mov_b32 -1
1123       MI->RemoveOperand(Src1Idx);
1124       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1125     } else
1126       return false;
1127 
1128     return true;
1129   }
1130 
1131   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
1132       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
1133       MI->getOpcode() == AMDGPU::S_AND_B32) {
1134     if (Src1Val == 0) {
1135       // y = and x, 0 => y = v_mov_b32 0
1136       MI->RemoveOperand(Src0Idx);
1137       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1138     } else if (Src1Val == -1) {
1139       // y = and x, -1 => y = copy x
1140       MI->RemoveOperand(Src1Idx);
1141       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1142       stripExtraCopyOperands(*MI);
1143     } else
1144       return false;
1145 
1146     return true;
1147   }
1148 
1149   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
1150       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
1151       MI->getOpcode() == AMDGPU::S_XOR_B32) {
1152     if (Src1Val == 0) {
1153       // y = xor x, 0 => y = copy x
1154       MI->RemoveOperand(Src1Idx);
1155       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1156       return true;
1157     }
1158   }
1159 
1160   return false;
1161 }
1162 
1163 // Try to fold an instruction into a simpler one
1164 bool SIFoldOperands::tryFoldCndMask(MachineInstr &MI) const {
1165   unsigned Opc = MI.getOpcode();
1166   if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1167       Opc != AMDGPU::V_CNDMASK_B64_PSEUDO)
1168     return false;
1169 
1170   MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1171   MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1172   if (!Src1->isIdenticalTo(*Src0)) {
1173     auto *Src0Imm = getImmOrMaterializedImm(*MRI, *Src0);
1174     auto *Src1Imm = getImmOrMaterializedImm(*MRI, *Src1);
1175     if (!Src1Imm->isIdenticalTo(*Src0Imm))
1176       return false;
1177   }
1178 
1179   int Src1ModIdx =
1180       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1181   int Src0ModIdx =
1182       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1183   if ((Src1ModIdx != -1 && MI.getOperand(Src1ModIdx).getImm() != 0) ||
1184       (Src0ModIdx != -1 && MI.getOperand(Src0ModIdx).getImm() != 0))
1185     return false;
1186 
1187   LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1188   auto &NewDesc =
1189       TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1190   int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1191   if (Src2Idx != -1)
1192     MI.RemoveOperand(Src2Idx);
1193   MI.RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1194   if (Src1ModIdx != -1)
1195     MI.RemoveOperand(Src1ModIdx);
1196   if (Src0ModIdx != -1)
1197     MI.RemoveOperand(Src0ModIdx);
1198   mutateCopyOp(MI, NewDesc);
1199   LLVM_DEBUG(dbgs() << MI);
1200   return true;
1201 }
1202 
1203 bool SIFoldOperands::tryFoldZeroHighBits(MachineInstr &MI) const {
1204   if (MI.getOpcode() != AMDGPU::V_AND_B32_e64 &&
1205       MI.getOpcode() != AMDGPU::V_AND_B32_e32)
1206     return false;
1207 
1208   MachineOperand *Src0 = getImmOrMaterializedImm(*MRI, MI.getOperand(1));
1209   if (!Src0->isImm() || Src0->getImm() != 0xffff)
1210     return false;
1211 
1212   Register Src1 = MI.getOperand(2).getReg();
1213   MachineInstr *SrcDef = MRI->getVRegDef(Src1);
1214   if (ST->zeroesHigh16BitsOfDest(SrcDef->getOpcode())) {
1215     Register Dst = MI.getOperand(0).getReg();
1216     MRI->replaceRegWith(Dst, SrcDef->getOperand(0).getReg());
1217     MI.eraseFromParent();
1218     return true;
1219   }
1220 
1221   return false;
1222 }
1223 
1224 bool SIFoldOperands::foldInstOperand(MachineInstr &MI,
1225                                      MachineOperand &OpToFold) const {
1226   // We need mutate the operands of new mov instructions to add implicit
1227   // uses of EXEC, but adding them invalidates the use_iterator, so defer
1228   // this.
1229   SmallVector<MachineInstr *, 4> CopiesToReplace;
1230   SmallVector<FoldCandidate, 4> FoldList;
1231   MachineOperand &Dst = MI.getOperand(0);
1232   bool Changed = false;
1233 
1234   if (OpToFold.isImm()) {
1235     for (auto &UseMI :
1236          make_early_inc_range(MRI->use_nodbg_instructions(Dst.getReg()))) {
1237       // Folding the immediate may reveal operations that can be constant
1238       // folded or replaced with a copy. This can happen for example after
1239       // frame indices are lowered to constants or from splitting 64-bit
1240       // constants.
1241       //
1242       // We may also encounter cases where one or both operands are
1243       // immediates materialized into a register, which would ordinarily not
1244       // be folded due to multiple uses or operand constraints.
1245       if (tryConstantFoldOp(*MRI, TII, &UseMI)) {
1246         LLVM_DEBUG(dbgs() << "Constant folded " << UseMI);
1247         Changed = true;
1248       }
1249     }
1250   }
1251 
1252   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1253   if (FoldingImm) {
1254     unsigned NumLiteralUses = 0;
1255     MachineOperand *NonInlineUse = nullptr;
1256     int NonInlineUseOpNo = -1;
1257 
1258     for (auto &Use :
1259          make_early_inc_range(MRI->use_nodbg_operands(Dst.getReg()))) {
1260       MachineInstr *UseMI = Use.getParent();
1261       unsigned OpNo = UseMI->getOperandNo(&Use);
1262 
1263       // Try to fold any inline immediate uses, and then only fold other
1264       // constants if they have one use.
1265       //
1266       // The legality of the inline immediate must be checked based on the use
1267       // operand, not the defining instruction, because 32-bit instructions
1268       // with 32-bit inline immediate sources may be used to materialize
1269       // constants used in 16-bit operands.
1270       //
1271       // e.g. it is unsafe to fold:
1272       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
1273       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
1274 
1275       // Folding immediates with more than one use will increase program size.
1276       // FIXME: This will also reduce register usage, which may be better
1277       // in some cases. A better heuristic is needed.
1278       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
1279         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1280       } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) {
1281         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1282       } else {
1283         if (++NumLiteralUses == 1) {
1284           NonInlineUse = &Use;
1285           NonInlineUseOpNo = OpNo;
1286         }
1287       }
1288     }
1289 
1290     if (NumLiteralUses == 1) {
1291       MachineInstr *UseMI = NonInlineUse->getParent();
1292       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
1293     }
1294   } else {
1295     // Folding register.
1296     SmallVector <MachineOperand *, 4> UsesToProcess;
1297     for (auto &Use : MRI->use_nodbg_operands(Dst.getReg()))
1298       UsesToProcess.push_back(&Use);
1299     for (auto U : UsesToProcess) {
1300       MachineInstr *UseMI = U->getParent();
1301 
1302       foldOperand(OpToFold, UseMI, UseMI->getOperandNo(U),
1303         FoldList, CopiesToReplace);
1304     }
1305   }
1306 
1307   if (CopiesToReplace.empty() && FoldList.empty())
1308     return Changed;
1309 
1310   MachineFunction *MF = MI.getParent()->getParent();
1311   // Make sure we add EXEC uses to any new v_mov instructions created.
1312   for (MachineInstr *Copy : CopiesToReplace)
1313     Copy->addImplicitDefUseOperands(*MF);
1314 
1315   for (FoldCandidate &Fold : FoldList) {
1316     assert(!Fold.isReg() || Fold.OpToFold);
1317     if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) {
1318       Register Reg = Fold.OpToFold->getReg();
1319       MachineInstr *DefMI = Fold.OpToFold->getParent();
1320       if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1321           execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1322         continue;
1323     }
1324     if (updateOperand(Fold, *TII, *TRI, *ST)) {
1325       // Clear kill flags.
1326       if (Fold.isReg()) {
1327         assert(Fold.OpToFold && Fold.OpToFold->isReg());
1328         // FIXME: Probably shouldn't bother trying to fold if not an
1329         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1330         // copies.
1331         MRI->clearKillFlags(Fold.OpToFold->getReg());
1332       }
1333       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1334                         << static_cast<int>(Fold.UseOpNo) << " of "
1335                         << *Fold.UseMI);
1336     } else if (Fold.isCommuted()) {
1337       // Restoring instruction's original operand order if fold has failed.
1338       TII->commuteInstruction(*Fold.UseMI, false);
1339     }
1340   }
1341   return true;
1342 }
1343 
1344 // Clamp patterns are canonically selected to v_max_* instructions, so only
1345 // handle them.
1346 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
1347   unsigned Op = MI.getOpcode();
1348   switch (Op) {
1349   case AMDGPU::V_MAX_F32_e64:
1350   case AMDGPU::V_MAX_F16_e64:
1351   case AMDGPU::V_MAX_F64_e64:
1352   case AMDGPU::V_PK_MAX_F16: {
1353     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1354       return nullptr;
1355 
1356     // Make sure sources are identical.
1357     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1358     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1359     if (!Src0->isReg() || !Src1->isReg() ||
1360         Src0->getReg() != Src1->getReg() ||
1361         Src0->getSubReg() != Src1->getSubReg() ||
1362         Src0->getSubReg() != AMDGPU::NoSubRegister)
1363       return nullptr;
1364 
1365     // Can't fold up if we have modifiers.
1366     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1367       return nullptr;
1368 
1369     unsigned Src0Mods
1370       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1371     unsigned Src1Mods
1372       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1373 
1374     // Having a 0 op_sel_hi would require swizzling the output in the source
1375     // instruction, which we can't do.
1376     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1377                                                       : 0u;
1378     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1379       return nullptr;
1380     return Src0;
1381   }
1382   default:
1383     return nullptr;
1384   }
1385 }
1386 
1387 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1388 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1389   const MachineOperand *ClampSrc = isClamp(MI);
1390   if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
1391     return false;
1392 
1393   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1394 
1395   // The type of clamp must be compatible.
1396   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1397     return false;
1398 
1399   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1400   if (!DefClamp)
1401     return false;
1402 
1403   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
1404 
1405   // Clamp is applied after omod, so it is OK if omod is set.
1406   DefClamp->setImm(1);
1407   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1408   MI.eraseFromParent();
1409 
1410   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1411   // instruction, so we might as well convert it to the more flexible VOP3-only
1412   // mad/fma form.
1413   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1414     Def->eraseFromParent();
1415 
1416   return true;
1417 }
1418 
1419 static int getOModValue(unsigned Opc, int64_t Val) {
1420   switch (Opc) {
1421   case AMDGPU::V_MUL_F64_e64: {
1422     switch (Val) {
1423     case 0x3fe0000000000000: // 0.5
1424       return SIOutMods::DIV2;
1425     case 0x4000000000000000: // 2.0
1426       return SIOutMods::MUL2;
1427     case 0x4010000000000000: // 4.0
1428       return SIOutMods::MUL4;
1429     default:
1430       return SIOutMods::NONE;
1431     }
1432   }
1433   case AMDGPU::V_MUL_F32_e64: {
1434     switch (static_cast<uint32_t>(Val)) {
1435     case 0x3f000000: // 0.5
1436       return SIOutMods::DIV2;
1437     case 0x40000000: // 2.0
1438       return SIOutMods::MUL2;
1439     case 0x40800000: // 4.0
1440       return SIOutMods::MUL4;
1441     default:
1442       return SIOutMods::NONE;
1443     }
1444   }
1445   case AMDGPU::V_MUL_F16_e64: {
1446     switch (static_cast<uint16_t>(Val)) {
1447     case 0x3800: // 0.5
1448       return SIOutMods::DIV2;
1449     case 0x4000: // 2.0
1450       return SIOutMods::MUL2;
1451     case 0x4400: // 4.0
1452       return SIOutMods::MUL4;
1453     default:
1454       return SIOutMods::NONE;
1455     }
1456   }
1457   default:
1458     llvm_unreachable("invalid mul opcode");
1459   }
1460 }
1461 
1462 // FIXME: Does this really not support denormals with f16?
1463 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1464 // handled, so will anything other than that break?
1465 std::pair<const MachineOperand *, int>
1466 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1467   unsigned Op = MI.getOpcode();
1468   switch (Op) {
1469   case AMDGPU::V_MUL_F64_e64:
1470   case AMDGPU::V_MUL_F32_e64:
1471   case AMDGPU::V_MUL_F16_e64: {
1472     // If output denormals are enabled, omod is ignored.
1473     if ((Op == AMDGPU::V_MUL_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1474         ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F16_e64) &&
1475          MFI->getMode().FP64FP16OutputDenormals))
1476       return std::make_pair(nullptr, SIOutMods::NONE);
1477 
1478     const MachineOperand *RegOp = nullptr;
1479     const MachineOperand *ImmOp = nullptr;
1480     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1481     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1482     if (Src0->isImm()) {
1483       ImmOp = Src0;
1484       RegOp = Src1;
1485     } else if (Src1->isImm()) {
1486       ImmOp = Src1;
1487       RegOp = Src0;
1488     } else
1489       return std::make_pair(nullptr, SIOutMods::NONE);
1490 
1491     int OMod = getOModValue(Op, ImmOp->getImm());
1492     if (OMod == SIOutMods::NONE ||
1493         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1494         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1495         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1496         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1497       return std::make_pair(nullptr, SIOutMods::NONE);
1498 
1499     return std::make_pair(RegOp, OMod);
1500   }
1501   case AMDGPU::V_ADD_F64_e64:
1502   case AMDGPU::V_ADD_F32_e64:
1503   case AMDGPU::V_ADD_F16_e64: {
1504     // If output denormals are enabled, omod is ignored.
1505     if ((Op == AMDGPU::V_ADD_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1506         ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F16_e64) &&
1507          MFI->getMode().FP64FP16OutputDenormals))
1508       return std::make_pair(nullptr, SIOutMods::NONE);
1509 
1510     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1511     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1512     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1513 
1514     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1515         Src0->getSubReg() == Src1->getSubReg() &&
1516         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1517         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1518         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1519         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1520       return std::make_pair(Src0, SIOutMods::MUL2);
1521 
1522     return std::make_pair(nullptr, SIOutMods::NONE);
1523   }
1524   default:
1525     return std::make_pair(nullptr, SIOutMods::NONE);
1526   }
1527 }
1528 
1529 // FIXME: Does this need to check IEEE bit on function?
1530 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1531   const MachineOperand *RegOp;
1532   int OMod;
1533   std::tie(RegOp, OMod) = isOMod(MI);
1534   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1535       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1536       !MRI->hasOneNonDBGUser(RegOp->getReg()))
1537     return false;
1538 
1539   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1540   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1541   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1542     return false;
1543 
1544   // Clamp is applied after omod. If the source already has clamp set, don't
1545   // fold it.
1546   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1547     return false;
1548 
1549   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
1550 
1551   DefOMod->setImm(OMod);
1552   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1553   MI.eraseFromParent();
1554 
1555   // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
1556   // instruction, so we might as well convert it to the more flexible VOP3-only
1557   // mad/fma form.
1558   if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
1559     Def->eraseFromParent();
1560 
1561   return true;
1562 }
1563 
1564 // Try to fold a reg_sequence with vgpr output and agpr inputs into an
1565 // instruction which can take an agpr. So far that means a store.
1566 bool SIFoldOperands::tryFoldRegSequence(MachineInstr &MI) {
1567   assert(MI.isRegSequence());
1568   auto Reg = MI.getOperand(0).getReg();
1569 
1570   if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
1571       !MRI->hasOneNonDBGUse(Reg))
1572     return false;
1573 
1574   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
1575   if (!getRegSeqInit(Defs, Reg, MCOI::OPERAND_REGISTER, TII, *MRI))
1576     return false;
1577 
1578   for (auto &Def : Defs) {
1579     const auto *Op = Def.first;
1580     if (!Op->isReg())
1581       return false;
1582     if (TRI->isAGPR(*MRI, Op->getReg()))
1583       continue;
1584     // Maybe this is a COPY from AREG
1585     const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
1586     if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
1587       return false;
1588     if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
1589       return false;
1590   }
1591 
1592   MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
1593   MachineInstr *UseMI = Op->getParent();
1594   while (UseMI->isCopy() && !Op->getSubReg()) {
1595     Reg = UseMI->getOperand(0).getReg();
1596     if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
1597       return false;
1598     Op = &*MRI->use_nodbg_begin(Reg);
1599     UseMI = Op->getParent();
1600   }
1601 
1602   if (Op->getSubReg())
1603     return false;
1604 
1605   unsigned OpIdx = Op - &UseMI->getOperand(0);
1606   const MCInstrDesc &InstDesc = UseMI->getDesc();
1607   const TargetRegisterClass *OpRC =
1608       TII->getRegClass(InstDesc, OpIdx, TRI, *MI.getMF());
1609   if (!OpRC || !TRI->isVectorSuperClass(OpRC))
1610     return false;
1611 
1612   const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
1613   auto Dst = MRI->createVirtualRegister(NewDstRC);
1614   auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1615                     TII->get(AMDGPU::REG_SEQUENCE), Dst);
1616 
1617   for (unsigned I = 0; I < Defs.size(); ++I) {
1618     MachineOperand *Def = Defs[I].first;
1619     Def->setIsKill(false);
1620     if (TRI->isAGPR(*MRI, Def->getReg())) {
1621       RS.add(*Def);
1622     } else { // This is a copy
1623       MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
1624       SubDef->getOperand(1).setIsKill(false);
1625       RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
1626     }
1627     RS.addImm(Defs[I].second);
1628   }
1629 
1630   Op->setReg(Dst);
1631   if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
1632     Op->setReg(Reg);
1633     RS->eraseFromParent();
1634     return false;
1635   }
1636 
1637   LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
1638 
1639   // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
1640   // in which case we can erase them all later in runOnMachineFunction.
1641   if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
1642     MI.eraseFromParent();
1643   return true;
1644 }
1645 
1646 // Try to hoist an AGPR to VGPR copy out of the loop across a LCSSA PHI.
1647 // This should allow folding of an AGPR into a consumer which may support it.
1648 // I.e.:
1649 //
1650 // loop:                             // loop:
1651 //   %1:vreg = COPY %0:areg          // exit:
1652 // exit:                          => //   %1:areg = PHI %0:areg, %loop
1653 //   %2:vreg = PHI %1:vreg, %loop    //   %2:vreg = COPY %1:areg
1654 bool SIFoldOperands::tryFoldLCSSAPhi(MachineInstr &PHI) {
1655   assert(PHI.isPHI());
1656 
1657   if (PHI.getNumExplicitOperands() != 3) // Single input LCSSA PHI
1658     return false;
1659 
1660   Register PhiIn = PHI.getOperand(1).getReg();
1661   Register PhiOut = PHI.getOperand(0).getReg();
1662   if (PHI.getOperand(1).getSubReg() ||
1663       !TRI->isVGPR(*MRI, PhiIn) || !TRI->isVGPR(*MRI, PhiOut))
1664     return false;
1665 
1666   // A single use should not matter for correctness, but if it has another use
1667   // inside the loop we may perform copy twice in a worst case.
1668   if (!MRI->hasOneNonDBGUse(PhiIn))
1669     return false;
1670 
1671   MachineInstr *Copy = MRI->getVRegDef(PhiIn);
1672   if (!Copy || !Copy->isCopy())
1673     return false;
1674 
1675   Register CopyIn = Copy->getOperand(1).getReg();
1676   if (!TRI->isAGPR(*MRI, CopyIn) || Copy->getOperand(1).getSubReg())
1677     return false;
1678 
1679   const TargetRegisterClass *ARC = MRI->getRegClass(CopyIn);
1680   Register NewReg = MRI->createVirtualRegister(ARC);
1681   PHI.getOperand(1).setReg(CopyIn);
1682   PHI.getOperand(0).setReg(NewReg);
1683 
1684   MachineBasicBlock *MBB = PHI.getParent();
1685   BuildMI(*MBB, MBB->getFirstNonPHI(), Copy->getDebugLoc(),
1686           TII->get(AMDGPU::COPY), PhiOut)
1687     .addReg(NewReg, RegState::Kill);
1688   Copy->eraseFromParent(); // We know this copy had a single use.
1689 
1690   LLVM_DEBUG(dbgs() << "Folded " << PHI);
1691 
1692   return true;
1693 }
1694 
1695 // Attempt to convert VGPR load to an AGPR load.
1696 bool SIFoldOperands::tryFoldLoad(MachineInstr &MI) {
1697   assert(MI.mayLoad());
1698   if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
1699     return false;
1700 
1701   MachineOperand &Def = MI.getOperand(0);
1702   if (!Def.isDef())
1703     return false;
1704 
1705   Register DefReg = Def.getReg();
1706 
1707   if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
1708     return false;
1709 
1710   SmallVector<const MachineInstr*, 8> Users;
1711   SmallVector<Register, 8> MoveRegs;
1712   for (const MachineInstr &I : MRI->use_nodbg_instructions(DefReg)) {
1713     Users.push_back(&I);
1714   }
1715   if (Users.empty())
1716     return false;
1717 
1718   // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
1719   while (!Users.empty()) {
1720     const MachineInstr *I = Users.pop_back_val();
1721     if (!I->isCopy() && !I->isRegSequence())
1722       return false;
1723     Register DstReg = I->getOperand(0).getReg();
1724     if (TRI->isAGPR(*MRI, DstReg))
1725       continue;
1726     MoveRegs.push_back(DstReg);
1727     for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg)) {
1728       Users.push_back(&U);
1729     }
1730   }
1731 
1732   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
1733   MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
1734   if (!TII->isOperandLegal(MI, 0, &Def)) {
1735     MRI->setRegClass(DefReg, RC);
1736     return false;
1737   }
1738 
1739   while (!MoveRegs.empty()) {
1740     Register Reg = MoveRegs.pop_back_val();
1741     MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
1742   }
1743 
1744   LLVM_DEBUG(dbgs() << "Folded " << MI);
1745 
1746   return true;
1747 }
1748 
1749 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1750   if (skipFunction(MF.getFunction()))
1751     return false;
1752 
1753   MRI = &MF.getRegInfo();
1754   ST = &MF.getSubtarget<GCNSubtarget>();
1755   TII = ST->getInstrInfo();
1756   TRI = &TII->getRegisterInfo();
1757   MFI = MF.getInfo<SIMachineFunctionInfo>();
1758 
1759   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1760   // correctly handle signed zeros.
1761   //
1762   // FIXME: Also need to check strictfp
1763   bool IsIEEEMode = MFI->getMode().IEEE;
1764   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1765 
1766   bool Changed = false;
1767   for (MachineBasicBlock *MBB : depth_first(&MF)) {
1768     MachineOperand *CurrentKnownM0Val = nullptr;
1769     for (auto &MI : make_early_inc_range(*MBB)) {
1770       Changed |= tryFoldCndMask(MI);
1771 
1772       if (tryFoldZeroHighBits(MI)) {
1773         Changed = true;
1774         continue;
1775       }
1776 
1777       if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
1778         Changed = true;
1779         continue;
1780       }
1781 
1782       if (MI.isPHI() && tryFoldLCSSAPhi(MI)) {
1783         Changed = true;
1784         continue;
1785       }
1786 
1787       if (MI.mayLoad() && tryFoldLoad(MI)) {
1788         Changed = true;
1789         continue;
1790       }
1791 
1792       if (!TII->isFoldableCopy(MI)) {
1793         // Saw an unknown clobber of m0, so we no longer know what it is.
1794         if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
1795           CurrentKnownM0Val = nullptr;
1796 
1797         // TODO: Omod might be OK if there is NSZ only on the source
1798         // instruction, and not the omod multiply.
1799         if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1800             !tryFoldOMod(MI))
1801           Changed |= tryFoldClamp(MI);
1802 
1803         continue;
1804       }
1805 
1806       // Specially track simple redefs of m0 to the same value in a block, so we
1807       // can erase the later ones.
1808       if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1809         MachineOperand &NewM0Val = MI.getOperand(1);
1810         if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1811           MI.eraseFromParent();
1812           Changed = true;
1813           continue;
1814         }
1815 
1816         // We aren't tracking other physical registers
1817         CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical()) ?
1818           nullptr : &NewM0Val;
1819         continue;
1820       }
1821 
1822       MachineOperand &OpToFold = MI.getOperand(1);
1823       bool FoldingImm =
1824           OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1825 
1826       // FIXME: We could also be folding things like TargetIndexes.
1827       if (!FoldingImm && !OpToFold.isReg())
1828         continue;
1829 
1830       if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1831         continue;
1832 
1833       // Prevent folding operands backwards in the function. For example,
1834       // the COPY opcode must not be replaced by 1 in this example:
1835       //
1836       //    %3 = COPY %vgpr0; VGPR_32:%3
1837       //    ...
1838       //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1839       if (!MI.getOperand(0).getReg().isVirtual())
1840         continue;
1841 
1842       Changed |= foldInstOperand(MI, OpToFold);
1843 
1844       // If we managed to fold all uses of this copy then we might as well
1845       // delete it now.
1846       // The only reason we need to follow chains of copies here is that
1847       // tryFoldRegSequence looks forward through copies before folding a
1848       // REG_SEQUENCE into its eventual users.
1849       auto *InstToErase = &MI;
1850       while (MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1851         auto &SrcOp = InstToErase->getOperand(1);
1852         auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
1853         InstToErase->eraseFromParent();
1854         Changed = true;
1855         InstToErase = nullptr;
1856         if (!SrcReg || SrcReg.isPhysical())
1857           break;
1858         InstToErase = MRI->getVRegDef(SrcReg);
1859         if (!InstToErase || !TII->isFoldableCopy(*InstToErase))
1860           break;
1861       }
1862       if (InstToErase && InstToErase->isRegSequence() &&
1863           MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
1864         InstToErase->eraseFromParent();
1865         Changed = true;
1866       }
1867     }
1868   }
1869   return Changed;
1870 }
1871