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