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