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