xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision b2a65f0d70f529ce52004934867461fa5329da63)
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/CodeGen/LiveIntervals.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 char 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     Old.ChangeToImmediate(Fold.ImmToFold);
286     return true;
287   }
288 
289   if (Fold.isGlobal()) {
290     Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(),
291                    Fold.OpToFold->getTargetFlags());
292     return true;
293   }
294 
295   if (Fold.isFI()) {
296     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
297     return true;
298   }
299 
300   MachineOperand *New = Fold.OpToFold;
301   Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
302   Old.setIsUndef(New->isUndef());
303   return true;
304 }
305 
306 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
307                               const MachineInstr *MI) {
308   for (auto Candidate : FoldList) {
309     if (Candidate.UseMI == MI)
310       return true;
311   }
312   return false;
313 }
314 
315 static void appendFoldCandidate(SmallVectorImpl<FoldCandidate> &FoldList,
316                                 MachineInstr *MI, unsigned OpNo,
317                                 MachineOperand *FoldOp, bool Commuted = false,
318                                 int ShrinkOp = -1) {
319   // Skip additional folding on the same operand.
320   for (FoldCandidate &Fold : FoldList)
321     if (Fold.UseMI == MI && Fold.UseOpNo == OpNo)
322       return;
323   LLVM_DEBUG(dbgs() << "Append " << (Commuted ? "commuted" : "normal")
324                     << " operand " << OpNo << "\n  " << *MI << '\n');
325   FoldList.push_back(FoldCandidate(MI, OpNo, FoldOp, Commuted, ShrinkOp));
326 }
327 
328 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
329                              MachineInstr *MI, unsigned OpNo,
330                              MachineOperand *OpToFold,
331                              const SIInstrInfo *TII) {
332   if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
333     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
334     unsigned Opc = MI->getOpcode();
335     if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
336          Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_e64) &&
337         (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
338       bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64 ||
339                    Opc == AMDGPU::V_FMAC_F16_e64;
340       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64 ||
341                    Opc == AMDGPU::V_FMAC_F32_e64;
342       unsigned NewOpc = IsFMA ?
343         (IsF32 ? AMDGPU::V_FMA_F32 : AMDGPU::V_FMA_F16_gfx9) :
344         (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
345 
346       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
347       // to fold the operand.
348       MI->setDesc(TII->get(NewOpc));
349       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
350       if (FoldAsMAD) {
351         MI->untieRegOperand(OpNo);
352         return true;
353       }
354       MI->setDesc(TII->get(Opc));
355     }
356 
357     // Special case for s_setreg_b32
358     if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
359       MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
360       appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
361       return true;
362     }
363 
364     // If we are already folding into another operand of MI, then
365     // we can't commute the instruction, otherwise we risk making the
366     // other fold illegal.
367     if (isUseMIInFoldList(FoldList, MI))
368       return false;
369 
370     unsigned CommuteOpNo = OpNo;
371 
372     // Operand is not legal, so try to commute the instruction to
373     // see if this makes it possible to fold.
374     unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
375     unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
376     bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
377 
378     if (CanCommute) {
379       if (CommuteIdx0 == OpNo)
380         CommuteOpNo = CommuteIdx1;
381       else if (CommuteIdx1 == OpNo)
382         CommuteOpNo = CommuteIdx0;
383     }
384 
385 
386     // One of operands might be an Imm operand, and OpNo may refer to it after
387     // the call of commuteInstruction() below. Such situations are avoided
388     // here explicitly as OpNo must be a register operand to be a candidate
389     // for memory folding.
390     if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
391                        !MI->getOperand(CommuteIdx1).isReg()))
392       return false;
393 
394     if (!CanCommute ||
395         !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
396       return false;
397 
398     if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
399       if ((Opc == AMDGPU::V_ADD_I32_e64 ||
400            Opc == AMDGPU::V_SUB_I32_e64 ||
401            Opc == AMDGPU::V_SUBREV_I32_e64) && // FIXME
402           (OpToFold->isImm() || OpToFold->isFI() || OpToFold->isGlobal())) {
403         MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
404 
405         // Verify the other operand is a VGPR, otherwise we would violate the
406         // constant bus restriction.
407         unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0;
408         MachineOperand &OtherOp = MI->getOperand(OtherIdx);
409         if (!OtherOp.isReg() ||
410             !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg()))
411           return false;
412 
413         assert(MI->getOperand(1).isDef());
414 
415         // Make sure to get the 32-bit version of the commuted opcode.
416         unsigned MaybeCommutedOpc = MI->getOpcode();
417         int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
418 
419         appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true, Op32);
420         return true;
421       }
422 
423       TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
424       return false;
425     }
426 
427     appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true);
428     return true;
429   }
430 
431   appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
432   return true;
433 }
434 
435 // If the use operand doesn't care about the value, this may be an operand only
436 // used for register indexing, in which case it is unsafe to fold.
437 static bool isUseSafeToFold(const SIInstrInfo *TII,
438                             const MachineInstr &MI,
439                             const MachineOperand &UseMO) {
440   return !UseMO.isUndef() && !TII->isSDWA(MI);
441   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
442 }
443 
444 static bool tryToFoldACImm(const SIInstrInfo *TII,
445                            const MachineOperand &OpToFold,
446                            MachineInstr *UseMI,
447                            unsigned UseOpIdx,
448                            SmallVectorImpl<FoldCandidate> &FoldList) {
449   const MCInstrDesc &Desc = UseMI->getDesc();
450   const MCOperandInfo *OpInfo = Desc.OpInfo;
451   if (!OpInfo || UseOpIdx >= Desc.getNumOperands())
452     return false;
453 
454   uint8_t OpTy = OpInfo[UseOpIdx].OperandType;
455   if (OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST ||
456       OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST)
457     return false;
458 
459   if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) &&
460       TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) {
461     UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm());
462     return true;
463   }
464 
465   if (!OpToFold.isReg())
466     return false;
467 
468   Register UseReg = OpToFold.getReg();
469   if (!Register::isVirtualRegister(UseReg))
470     return false;
471 
472   if (llvm::find_if(FoldList, [UseMI](const FoldCandidate &FC) {
473         return FC.UseMI == UseMI; }) != FoldList.end())
474     return false;
475 
476   MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo();
477   const MachineInstr *Def = MRI.getUniqueVRegDef(UseReg);
478   if (!Def || !Def->isRegSequence())
479     return false;
480 
481   int64_t Imm;
482   MachineOperand *Op;
483   for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) {
484     const MachineOperand &Sub = Def->getOperand(I);
485     if (!Sub.isReg() || Sub.getSubReg())
486       return false;
487     MachineInstr *SubDef = MRI.getUniqueVRegDef(Sub.getReg());
488     while (SubDef && !SubDef->isMoveImmediate() &&
489            !SubDef->getOperand(1).isImm() && TII->isFoldableCopy(*SubDef))
490       SubDef = MRI.getUniqueVRegDef(SubDef->getOperand(1).getReg());
491     if (!SubDef || !SubDef->isMoveImmediate() || !SubDef->getOperand(1).isImm())
492       return false;
493     Op = &SubDef->getOperand(1);
494     auto SubImm = Op->getImm();
495     if (I == 1) {
496       if (!TII->isInlineConstant(SubDef->getOperand(1), OpTy))
497         return false;
498 
499       Imm = SubImm;
500       continue;
501     }
502     if (Imm != SubImm)
503       return false; // Can only fold splat constants
504   }
505 
506   if (!TII->isOperandLegal(*UseMI, UseOpIdx, Op))
507     return false;
508 
509   appendFoldCandidate(FoldList, UseMI, UseOpIdx, Op);
510   return true;
511 }
512 
513 void SIFoldOperands::foldOperand(
514   MachineOperand &OpToFold,
515   MachineInstr *UseMI,
516   int UseOpIdx,
517   SmallVectorImpl<FoldCandidate> &FoldList,
518   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
519   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
520 
521   if (!isUseSafeToFold(TII, *UseMI, UseOp))
522     return;
523 
524   // FIXME: Fold operands with subregs.
525   if (UseOp.isReg() && OpToFold.isReg()) {
526     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
527       return;
528   }
529 
530   // Special case for REG_SEQUENCE: We can't fold literals into
531   // REG_SEQUENCE instructions, so we have to fold them into the
532   // uses of REG_SEQUENCE.
533   if (UseMI->isRegSequence()) {
534     Register RegSeqDstReg = UseMI->getOperand(0).getReg();
535     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
536 
537     MachineRegisterInfo::use_iterator Next;
538     for (MachineRegisterInfo::use_iterator
539            RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
540          RSUse != RSE; RSUse = Next) {
541       Next = std::next(RSUse);
542 
543       MachineInstr *RSUseMI = RSUse->getParent();
544 
545       if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI,
546                          RSUse.getOperandNo(), FoldList))
547         continue;
548 
549       if (RSUse->getSubReg() != RegSeqDstSubReg)
550         continue;
551 
552       foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
553                   CopiesToReplace);
554     }
555 
556     return;
557   }
558 
559   if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList))
560     return;
561 
562   if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) {
563     // Sanity check that this is a stack access.
564     // FIXME: Should probably use stack pseudos before frame lowering.
565     MachineOperand *SOff = TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
566     if (!SOff->isReg() || (SOff->getReg() != MFI->getScratchWaveOffsetReg() &&
567                            SOff->getReg() != MFI->getStackPtrOffsetReg()))
568       return;
569 
570     if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
571         MFI->getScratchRSrcReg())
572       return;
573 
574     // A frame index will resolve to a positive constant, so it should always be
575     // safe to fold the addressing mode, even pre-GFX9.
576     UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex());
577     SOff->setReg(MFI->getStackPtrOffsetReg());
578     return;
579   }
580 
581   bool FoldingImmLike =
582       OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
583 
584   if (FoldingImmLike && UseMI->isCopy()) {
585     Register DestReg = UseMI->getOperand(0).getReg();
586 
587     // Don't fold into a copy to a physical register. Doing so would interfere
588     // with the register coalescer's logic which would avoid redundant
589     // initalizations.
590     if (DestReg.isPhysical())
591       return;
592 
593     const TargetRegisterClass *DestRC =  MRI->getRegClass(DestReg);
594 
595     Register SrcReg = UseMI->getOperand(1).getReg();
596     if (SrcReg.isVirtual()) { // XXX - This can be an assert?
597       const TargetRegisterClass * SrcRC = MRI->getRegClass(SrcReg);
598       if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) {
599         MachineRegisterInfo::use_iterator NextUse;
600         SmallVector<FoldCandidate, 4> CopyUses;
601         for (MachineRegisterInfo::use_iterator
602           Use = MRI->use_begin(DestReg), E = MRI->use_end();
603           Use != E; Use = NextUse) {
604           NextUse = std::next(Use);
605           FoldCandidate FC = FoldCandidate(Use->getParent(),
606            Use.getOperandNo(), &UseMI->getOperand(1));
607           CopyUses.push_back(FC);
608        }
609         for (auto & F : CopyUses) {
610           foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo,
611            FoldList, CopiesToReplace);
612         }
613       }
614     }
615 
616     if (DestRC == &AMDGPU::AGPR_32RegClass &&
617         TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
618       UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32));
619       UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
620       CopiesToReplace.push_back(UseMI);
621       return;
622     }
623 
624     // In order to fold immediates into copies, we need to change the
625     // copy to a MOV.
626 
627     unsigned MovOp = TII->getMovOpcode(DestRC);
628     if (MovOp == AMDGPU::COPY)
629       return;
630 
631     UseMI->setDesc(TII->get(MovOp));
632     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
633     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
634     while (ImpOpI != ImpOpE) {
635       MachineInstr::mop_iterator Tmp = ImpOpI;
636       ImpOpI++;
637       UseMI->RemoveOperand(UseMI->getOperandNo(Tmp));
638     }
639     CopiesToReplace.push_back(UseMI);
640   } else {
641     if (UseMI->isCopy() && OpToFold.isReg() &&
642         UseMI->getOperand(0).getReg().isVirtual() &&
643         TRI->isVectorRegister(*MRI, UseMI->getOperand(0).getReg()) &&
644         !UseMI->getOperand(1).getSubReg()) {
645       LLVM_DEBUG(dbgs() << "Folding " << OpToFold
646                         << "\n into " << *UseMI << '\n');
647       unsigned Size = TII->getOpSize(*UseMI, 1);
648       UseMI->getOperand(1).setReg(OpToFold.getReg());
649       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
650       UseMI->getOperand(1).setIsKill(false);
651       CopiesToReplace.push_back(UseMI);
652       OpToFold.setIsKill(false);
653       if (Size != 4)
654         return;
655       if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
656           TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()))
657         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32));
658       else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
659                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
660         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32));
661       return;
662     }
663 
664     unsigned UseOpc = UseMI->getOpcode();
665     if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
666         (UseOpc == AMDGPU::V_READLANE_B32 &&
667          (int)UseOpIdx ==
668          AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
669       // %vgpr = V_MOV_B32 imm
670       // %sgpr = V_READFIRSTLANE_B32 %vgpr
671       // =>
672       // %sgpr = S_MOV_B32 imm
673       if (FoldingImmLike) {
674         if (execMayBeModifiedBeforeUse(*MRI,
675                                        UseMI->getOperand(UseOpIdx).getReg(),
676                                        *OpToFold.getParent(),
677                                        *UseMI))
678           return;
679 
680         UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
681 
682         // FIXME: ChangeToImmediate should clear subreg
683         UseMI->getOperand(1).setSubReg(0);
684         if (OpToFold.isImm())
685           UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
686         else
687           UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex());
688         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
689         return;
690       }
691 
692       if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
693         if (execMayBeModifiedBeforeUse(*MRI,
694                                        UseMI->getOperand(UseOpIdx).getReg(),
695                                        *OpToFold.getParent(),
696                                        *UseMI))
697           return;
698 
699         // %vgpr = COPY %sgpr0
700         // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
701         // =>
702         // %sgpr1 = COPY %sgpr0
703         UseMI->setDesc(TII->get(AMDGPU::COPY));
704         UseMI->getOperand(1).setReg(OpToFold.getReg());
705         UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
706         UseMI->getOperand(1).setIsKill(false);
707         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
708         return;
709       }
710     }
711 
712     const MCInstrDesc &UseDesc = UseMI->getDesc();
713 
714     // Don't fold into target independent nodes.  Target independent opcodes
715     // don't have defined register classes.
716     if (UseDesc.isVariadic() ||
717         UseOp.isImplicit() ||
718         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
719       return;
720   }
721 
722   if (!FoldingImmLike) {
723     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
724 
725     // FIXME: We could try to change the instruction from 64-bit to 32-bit
726     // to enable more folding opportunites.  The shrink operands pass
727     // already does this.
728     return;
729   }
730 
731 
732   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
733   const TargetRegisterClass *FoldRC =
734     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
735 
736   // Split 64-bit constants into 32-bits for folding.
737   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
738     Register UseReg = UseOp.getReg();
739     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
740 
741     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
742       return;
743 
744     APInt Imm(64, OpToFold.getImm());
745     if (UseOp.getSubReg() == AMDGPU::sub0) {
746       Imm = Imm.getLoBits(32);
747     } else {
748       assert(UseOp.getSubReg() == AMDGPU::sub1);
749       Imm = Imm.getHiBits(32);
750     }
751 
752     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
753     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
754     return;
755   }
756 
757 
758 
759   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
760 }
761 
762 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
763                                   uint32_t LHS, uint32_t RHS) {
764   switch (Opcode) {
765   case AMDGPU::V_AND_B32_e64:
766   case AMDGPU::V_AND_B32_e32:
767   case AMDGPU::S_AND_B32:
768     Result = LHS & RHS;
769     return true;
770   case AMDGPU::V_OR_B32_e64:
771   case AMDGPU::V_OR_B32_e32:
772   case AMDGPU::S_OR_B32:
773     Result = LHS | RHS;
774     return true;
775   case AMDGPU::V_XOR_B32_e64:
776   case AMDGPU::V_XOR_B32_e32:
777   case AMDGPU::S_XOR_B32:
778     Result = LHS ^ RHS;
779     return true;
780   case AMDGPU::V_LSHL_B32_e64:
781   case AMDGPU::V_LSHL_B32_e32:
782   case AMDGPU::S_LSHL_B32:
783     // The instruction ignores the high bits for out of bounds shifts.
784     Result = LHS << (RHS & 31);
785     return true;
786   case AMDGPU::V_LSHLREV_B32_e64:
787   case AMDGPU::V_LSHLREV_B32_e32:
788     Result = RHS << (LHS & 31);
789     return true;
790   case AMDGPU::V_LSHR_B32_e64:
791   case AMDGPU::V_LSHR_B32_e32:
792   case AMDGPU::S_LSHR_B32:
793     Result = LHS >> (RHS & 31);
794     return true;
795   case AMDGPU::V_LSHRREV_B32_e64:
796   case AMDGPU::V_LSHRREV_B32_e32:
797     Result = RHS >> (LHS & 31);
798     return true;
799   case AMDGPU::V_ASHR_I32_e64:
800   case AMDGPU::V_ASHR_I32_e32:
801   case AMDGPU::S_ASHR_I32:
802     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
803     return true;
804   case AMDGPU::V_ASHRREV_I32_e64:
805   case AMDGPU::V_ASHRREV_I32_e32:
806     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
807     return true;
808   default:
809     return false;
810   }
811 }
812 
813 static unsigned getMovOpc(bool IsScalar) {
814   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
815 }
816 
817 /// Remove any leftover implicit operands from mutating the instruction. e.g.
818 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
819 /// anymore.
820 static void stripExtraCopyOperands(MachineInstr &MI) {
821   const MCInstrDesc &Desc = MI.getDesc();
822   unsigned NumOps = Desc.getNumOperands() +
823                     Desc.getNumImplicitUses() +
824                     Desc.getNumImplicitDefs();
825 
826   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
827     MI.RemoveOperand(I);
828 }
829 
830 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
831   MI.setDesc(NewDesc);
832   stripExtraCopyOperands(MI);
833 }
834 
835 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
836                                                MachineOperand &Op) {
837   if (Op.isReg()) {
838     // If this has a subregister, it obviously is a register source.
839     if (Op.getSubReg() != AMDGPU::NoSubRegister ||
840         !Register::isVirtualRegister(Op.getReg()))
841       return &Op;
842 
843     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
844     if (Def && Def->isMoveImmediate()) {
845       MachineOperand &ImmSrc = Def->getOperand(1);
846       if (ImmSrc.isImm())
847         return &ImmSrc;
848     }
849   }
850 
851   return &Op;
852 }
853 
854 // Try to simplify operations with a constant that may appear after instruction
855 // selection.
856 // TODO: See if a frame index with a fixed offset can fold.
857 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
858                               const SIInstrInfo *TII,
859                               MachineInstr *MI,
860                               MachineOperand *ImmOp) {
861   unsigned Opc = MI->getOpcode();
862   if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
863       Opc == AMDGPU::S_NOT_B32) {
864     MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
865     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
866     return true;
867   }
868 
869   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
870   if (Src1Idx == -1)
871     return false;
872 
873   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
874   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
875   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
876 
877   if (!Src0->isImm() && !Src1->isImm())
878     return false;
879 
880   if (MI->getOpcode() == AMDGPU::V_LSHL_OR_B32) {
881     if (Src0->isImm() && Src0->getImm() == 0) {
882       // v_lshl_or_b32 0, X, Y -> copy Y
883       // v_lshl_or_b32 0, X, K -> v_mov_b32 K
884       bool UseCopy = TII->getNamedOperand(*MI, AMDGPU::OpName::src2)->isReg();
885       MI->RemoveOperand(Src1Idx);
886       MI->RemoveOperand(Src0Idx);
887 
888       MI->setDesc(TII->get(UseCopy ? AMDGPU::COPY : AMDGPU::V_MOV_B32_e32));
889       return true;
890     }
891   }
892 
893   // and k0, k1 -> v_mov_b32 (k0 & k1)
894   // or k0, k1 -> v_mov_b32 (k0 | k1)
895   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
896   if (Src0->isImm() && Src1->isImm()) {
897     int32_t NewImm;
898     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
899       return false;
900 
901     const SIRegisterInfo &TRI = TII->getRegisterInfo();
902     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
903 
904     // Be careful to change the right operand, src0 may belong to a different
905     // instruction.
906     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
907     MI->RemoveOperand(Src1Idx);
908     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
909     return true;
910   }
911 
912   if (!MI->isCommutable())
913     return false;
914 
915   if (Src0->isImm() && !Src1->isImm()) {
916     std::swap(Src0, Src1);
917     std::swap(Src0Idx, Src1Idx);
918   }
919 
920   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
921   if (Opc == AMDGPU::V_OR_B32_e64 ||
922       Opc == AMDGPU::V_OR_B32_e32 ||
923       Opc == AMDGPU::S_OR_B32) {
924     if (Src1Val == 0) {
925       // y = or x, 0 => y = copy x
926       MI->RemoveOperand(Src1Idx);
927       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
928     } else if (Src1Val == -1) {
929       // y = or x, -1 => y = v_mov_b32 -1
930       MI->RemoveOperand(Src1Idx);
931       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
932     } else
933       return false;
934 
935     return true;
936   }
937 
938   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
939       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
940       MI->getOpcode() == AMDGPU::S_AND_B32) {
941     if (Src1Val == 0) {
942       // y = and x, 0 => y = v_mov_b32 0
943       MI->RemoveOperand(Src0Idx);
944       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
945     } else if (Src1Val == -1) {
946       // y = and x, -1 => y = copy x
947       MI->RemoveOperand(Src1Idx);
948       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
949       stripExtraCopyOperands(*MI);
950     } else
951       return false;
952 
953     return true;
954   }
955 
956   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
957       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
958       MI->getOpcode() == AMDGPU::S_XOR_B32) {
959     if (Src1Val == 0) {
960       // y = xor x, 0 => y = copy x
961       MI->RemoveOperand(Src1Idx);
962       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
963       return true;
964     }
965   }
966 
967   return false;
968 }
969 
970 // Try to fold an instruction into a simpler one
971 static bool tryFoldInst(const SIInstrInfo *TII,
972                         MachineInstr *MI) {
973   unsigned Opc = MI->getOpcode();
974 
975   if (Opc == AMDGPU::V_CNDMASK_B32_e32    ||
976       Opc == AMDGPU::V_CNDMASK_B32_e64    ||
977       Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
978     const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
979     const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
980     int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
981     int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
982     if (Src1->isIdenticalTo(*Src0) &&
983         (Src1ModIdx == -1 || !MI->getOperand(Src1ModIdx).getImm()) &&
984         (Src0ModIdx == -1 || !MI->getOperand(Src0ModIdx).getImm())) {
985       LLVM_DEBUG(dbgs() << "Folded " << *MI << " into ");
986       auto &NewDesc =
987           TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
988       int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
989       if (Src2Idx != -1)
990         MI->RemoveOperand(Src2Idx);
991       MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
992       if (Src1ModIdx != -1)
993         MI->RemoveOperand(Src1ModIdx);
994       if (Src0ModIdx != -1)
995         MI->RemoveOperand(Src0ModIdx);
996       mutateCopyOp(*MI, NewDesc);
997       LLVM_DEBUG(dbgs() << *MI << '\n');
998       return true;
999     }
1000   }
1001 
1002   return false;
1003 }
1004 
1005 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
1006                                      MachineOperand &OpToFold) const {
1007   // We need mutate the operands of new mov instructions to add implicit
1008   // uses of EXEC, but adding them invalidates the use_iterator, so defer
1009   // this.
1010   SmallVector<MachineInstr *, 4> CopiesToReplace;
1011   SmallVector<FoldCandidate, 4> FoldList;
1012   MachineOperand &Dst = MI.getOperand(0);
1013 
1014   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1015   if (FoldingImm) {
1016     unsigned NumLiteralUses = 0;
1017     MachineOperand *NonInlineUse = nullptr;
1018     int NonInlineUseOpNo = -1;
1019 
1020     MachineRegisterInfo::use_iterator NextUse;
1021     for (MachineRegisterInfo::use_iterator
1022            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
1023          Use != E; Use = NextUse) {
1024       NextUse = std::next(Use);
1025       MachineInstr *UseMI = Use->getParent();
1026       unsigned OpNo = Use.getOperandNo();
1027 
1028       // Folding the immediate may reveal operations that can be constant
1029       // folded or replaced with a copy. This can happen for example after
1030       // frame indices are lowered to constants or from splitting 64-bit
1031       // constants.
1032       //
1033       // We may also encounter cases where one or both operands are
1034       // immediates materialized into a register, which would ordinarily not
1035       // be folded due to multiple uses or operand constraints.
1036 
1037       if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
1038         LLVM_DEBUG(dbgs() << "Constant folded " << *UseMI << '\n');
1039 
1040         // Some constant folding cases change the same immediate's use to a new
1041         // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
1042         // again. The same constant folded instruction could also have a second
1043         // use operand.
1044         NextUse = MRI->use_begin(Dst.getReg());
1045         FoldList.clear();
1046         continue;
1047       }
1048 
1049       // Try to fold any inline immediate uses, and then only fold other
1050       // constants if they have one use.
1051       //
1052       // The legality of the inline immediate must be checked based on the use
1053       // operand, not the defining instruction, because 32-bit instructions
1054       // with 32-bit inline immediate sources may be used to materialize
1055       // constants used in 16-bit operands.
1056       //
1057       // e.g. it is unsafe to fold:
1058       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
1059       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
1060 
1061       // Folding immediates with more than one use will increase program size.
1062       // FIXME: This will also reduce register usage, which may be better
1063       // in some cases. A better heuristic is needed.
1064       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
1065         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1066       } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) {
1067         foldOperand(OpToFold, UseMI, OpNo, FoldList,
1068                     CopiesToReplace);
1069       } else {
1070         if (++NumLiteralUses == 1) {
1071           NonInlineUse = &*Use;
1072           NonInlineUseOpNo = OpNo;
1073         }
1074       }
1075     }
1076 
1077     if (NumLiteralUses == 1) {
1078       MachineInstr *UseMI = NonInlineUse->getParent();
1079       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
1080     }
1081   } else {
1082     // Folding register.
1083     SmallVector <MachineRegisterInfo::use_iterator, 4> UsesToProcess;
1084     for (MachineRegisterInfo::use_iterator
1085            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
1086          Use != E; ++Use) {
1087       UsesToProcess.push_back(Use);
1088     }
1089     for (auto U : UsesToProcess) {
1090       MachineInstr *UseMI = U->getParent();
1091 
1092       foldOperand(OpToFold, UseMI, U.getOperandNo(),
1093         FoldList, CopiesToReplace);
1094     }
1095   }
1096 
1097   MachineFunction *MF = MI.getParent()->getParent();
1098   // Make sure we add EXEC uses to any new v_mov instructions created.
1099   for (MachineInstr *Copy : CopiesToReplace)
1100     Copy->addImplicitDefUseOperands(*MF);
1101 
1102   for (FoldCandidate &Fold : FoldList) {
1103     if (Fold.isReg() && Register::isVirtualRegister(Fold.OpToFold->getReg())) {
1104       Register Reg = Fold.OpToFold->getReg();
1105       MachineInstr *DefMI = Fold.OpToFold->getParent();
1106       if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1107           execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1108         continue;
1109     }
1110     if (updateOperand(Fold, *TII, *TRI, *ST)) {
1111       // Clear kill flags.
1112       if (Fold.isReg()) {
1113         assert(Fold.OpToFold && Fold.OpToFold->isReg());
1114         // FIXME: Probably shouldn't bother trying to fold if not an
1115         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1116         // copies.
1117         MRI->clearKillFlags(Fold.OpToFold->getReg());
1118       }
1119       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1120                         << static_cast<int>(Fold.UseOpNo) << " of "
1121                         << *Fold.UseMI << '\n');
1122       tryFoldInst(TII, Fold.UseMI);
1123     } else if (Fold.isCommuted()) {
1124       // Restoring instruction's original operand order if fold has failed.
1125       TII->commuteInstruction(*Fold.UseMI, false);
1126     }
1127   }
1128 }
1129 
1130 // Clamp patterns are canonically selected to v_max_* instructions, so only
1131 // handle them.
1132 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
1133   unsigned Op = MI.getOpcode();
1134   switch (Op) {
1135   case AMDGPU::V_MAX_F32_e64:
1136   case AMDGPU::V_MAX_F16_e64:
1137   case AMDGPU::V_MAX_F64:
1138   case AMDGPU::V_PK_MAX_F16: {
1139     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1140       return nullptr;
1141 
1142     // Make sure sources are identical.
1143     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1144     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1145     if (!Src0->isReg() || !Src1->isReg() ||
1146         Src0->getReg() != Src1->getReg() ||
1147         Src0->getSubReg() != Src1->getSubReg() ||
1148         Src0->getSubReg() != AMDGPU::NoSubRegister)
1149       return nullptr;
1150 
1151     // Can't fold up if we have modifiers.
1152     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1153       return nullptr;
1154 
1155     unsigned Src0Mods
1156       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1157     unsigned Src1Mods
1158       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1159 
1160     // Having a 0 op_sel_hi would require swizzling the output in the source
1161     // instruction, which we can't do.
1162     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1163                                                       : 0u;
1164     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1165       return nullptr;
1166     return Src0;
1167   }
1168   default:
1169     return nullptr;
1170   }
1171 }
1172 
1173 // We obviously have multiple uses in a clamp since the register is used twice
1174 // in the same instruction.
1175 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
1176   int Count = 0;
1177   for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
1178        I != E; ++I) {
1179     if (++Count > 1)
1180       return false;
1181   }
1182 
1183   return true;
1184 }
1185 
1186 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1187 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1188   const MachineOperand *ClampSrc = isClamp(MI);
1189   if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
1190     return false;
1191 
1192   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1193 
1194   // The type of clamp must be compatible.
1195   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1196     return false;
1197 
1198   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1199   if (!DefClamp)
1200     return false;
1201 
1202   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def
1203                     << '\n');
1204 
1205   // Clamp is applied after omod, so it is OK if omod is set.
1206   DefClamp->setImm(1);
1207   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1208   MI.eraseFromParent();
1209   return true;
1210 }
1211 
1212 static int getOModValue(unsigned Opc, int64_t Val) {
1213   switch (Opc) {
1214   case AMDGPU::V_MUL_F32_e64: {
1215     switch (static_cast<uint32_t>(Val)) {
1216     case 0x3f000000: // 0.5
1217       return SIOutMods::DIV2;
1218     case 0x40000000: // 2.0
1219       return SIOutMods::MUL2;
1220     case 0x40800000: // 4.0
1221       return SIOutMods::MUL4;
1222     default:
1223       return SIOutMods::NONE;
1224     }
1225   }
1226   case AMDGPU::V_MUL_F16_e64: {
1227     switch (static_cast<uint16_t>(Val)) {
1228     case 0x3800: // 0.5
1229       return SIOutMods::DIV2;
1230     case 0x4000: // 2.0
1231       return SIOutMods::MUL2;
1232     case 0x4400: // 4.0
1233       return SIOutMods::MUL4;
1234     default:
1235       return SIOutMods::NONE;
1236     }
1237   }
1238   default:
1239     llvm_unreachable("invalid mul opcode");
1240   }
1241 }
1242 
1243 // FIXME: Does this really not support denormals with f16?
1244 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1245 // handled, so will anything other than that break?
1246 std::pair<const MachineOperand *, int>
1247 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1248   unsigned Op = MI.getOpcode();
1249   switch (Op) {
1250   case AMDGPU::V_MUL_F32_e64:
1251   case AMDGPU::V_MUL_F16_e64: {
1252     // If output denormals are enabled, omod is ignored.
1253     if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
1254         (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
1255       return std::make_pair(nullptr, SIOutMods::NONE);
1256 
1257     const MachineOperand *RegOp = nullptr;
1258     const MachineOperand *ImmOp = nullptr;
1259     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1260     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1261     if (Src0->isImm()) {
1262       ImmOp = Src0;
1263       RegOp = Src1;
1264     } else if (Src1->isImm()) {
1265       ImmOp = Src1;
1266       RegOp = Src0;
1267     } else
1268       return std::make_pair(nullptr, SIOutMods::NONE);
1269 
1270     int OMod = getOModValue(Op, ImmOp->getImm());
1271     if (OMod == SIOutMods::NONE ||
1272         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1273         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1274         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1275         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1276       return std::make_pair(nullptr, SIOutMods::NONE);
1277 
1278     return std::make_pair(RegOp, OMod);
1279   }
1280   case AMDGPU::V_ADD_F32_e64:
1281   case AMDGPU::V_ADD_F16_e64: {
1282     // If output denormals are enabled, omod is ignored.
1283     if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
1284         (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
1285       return std::make_pair(nullptr, SIOutMods::NONE);
1286 
1287     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1288     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1289     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1290 
1291     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1292         Src0->getSubReg() == Src1->getSubReg() &&
1293         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1294         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1295         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1296         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1297       return std::make_pair(Src0, SIOutMods::MUL2);
1298 
1299     return std::make_pair(nullptr, SIOutMods::NONE);
1300   }
1301   default:
1302     return std::make_pair(nullptr, SIOutMods::NONE);
1303   }
1304 }
1305 
1306 // FIXME: Does this need to check IEEE bit on function?
1307 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1308   const MachineOperand *RegOp;
1309   int OMod;
1310   std::tie(RegOp, OMod) = isOMod(MI);
1311   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1312       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1313       !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
1314     return false;
1315 
1316   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1317   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1318   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1319     return false;
1320 
1321   // Clamp is applied after omod. If the source already has clamp set, don't
1322   // fold it.
1323   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1324     return false;
1325 
1326   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
1327 
1328   DefOMod->setImm(OMod);
1329   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1330   MI.eraseFromParent();
1331   return true;
1332 }
1333 
1334 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1335   if (skipFunction(MF.getFunction()))
1336     return false;
1337 
1338   MRI = &MF.getRegInfo();
1339   ST = &MF.getSubtarget<GCNSubtarget>();
1340   TII = ST->getInstrInfo();
1341   TRI = &TII->getRegisterInfo();
1342   MFI = MF.getInfo<SIMachineFunctionInfo>();
1343 
1344   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1345   // correctly handle signed zeros.
1346   //
1347   // FIXME: Also need to check strictfp
1348   bool IsIEEEMode = MFI->getMode().IEEE;
1349   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1350 
1351   for (MachineBasicBlock *MBB : depth_first(&MF)) {
1352     MachineBasicBlock::iterator I, Next;
1353 
1354     MachineOperand *CurrentKnownM0Val = nullptr;
1355     for (I = MBB->begin(); I != MBB->end(); I = Next) {
1356       Next = std::next(I);
1357       MachineInstr &MI = *I;
1358 
1359       tryFoldInst(TII, &MI);
1360 
1361       if (!TII->isFoldableCopy(MI)) {
1362         // TODO: Omod might be OK if there is NSZ only on the source
1363         // instruction, and not the omod multiply.
1364         if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1365             !tryFoldOMod(MI))
1366           tryFoldClamp(MI);
1367 
1368         // Saw an unknown clobber of m0, so we no longer know what it is.
1369         if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
1370           CurrentKnownM0Val = nullptr;
1371         continue;
1372       }
1373 
1374       // Specially track simple redefs of m0 to the same value in a block, so we
1375       // can erase the later ones.
1376       if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1377         MachineOperand &NewM0Val = MI.getOperand(1);
1378         if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1379           MI.eraseFromParent();
1380           continue;
1381         }
1382 
1383         // We aren't tracking other physical registers
1384         CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical()) ?
1385           nullptr : &NewM0Val;
1386         continue;
1387       }
1388 
1389       MachineOperand &OpToFold = MI.getOperand(1);
1390       bool FoldingImm =
1391           OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1392 
1393       // FIXME: We could also be folding things like TargetIndexes.
1394       if (!FoldingImm && !OpToFold.isReg())
1395         continue;
1396 
1397       if (OpToFold.isReg() && !Register::isVirtualRegister(OpToFold.getReg()))
1398         continue;
1399 
1400       // Prevent folding operands backwards in the function. For example,
1401       // the COPY opcode must not be replaced by 1 in this example:
1402       //
1403       //    %3 = COPY %vgpr0; VGPR_32:%3
1404       //    ...
1405       //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1406       MachineOperand &Dst = MI.getOperand(0);
1407       if (Dst.isReg() && !Register::isVirtualRegister(Dst.getReg()))
1408         continue;
1409 
1410       foldInstOperand(MI, OpToFold);
1411     }
1412   }
1413   return true;
1414 }
1415