1 //===-- SIShrinkInstructions.cpp - Shrink Instructions --------------------===//
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 /// The pass tries to use the 32-bit encoding for instructions when possible.
8 //===----------------------------------------------------------------------===//
9 //
10 
11 #include "AMDGPU.h"
12 #include "AMDGPUSubtarget.h"
13 #include "llvm/ADT/Statistic.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 
16 #define DEBUG_TYPE "si-shrink-instructions"
17 
18 STATISTIC(NumInstructionsShrunk,
19           "Number of 64-bit instruction reduced to 32-bit.");
20 STATISTIC(NumLiteralConstantsFolded,
21           "Number of literal constants folded into 32-bit instructions.");
22 
23 using namespace llvm;
24 
25 namespace {
26 
27 class SIShrinkInstructions : public MachineFunctionPass {
28 public:
29   static char ID;
30 
31   void shrinkMIMG(MachineInstr &MI);
32 
33 public:
34   SIShrinkInstructions() : MachineFunctionPass(ID) {
35   }
36 
37   bool runOnMachineFunction(MachineFunction &MF) override;
38 
39   StringRef getPassName() const override { return "SI Shrink Instructions"; }
40 
41   void getAnalysisUsage(AnalysisUsage &AU) const override {
42     AU.setPreservesCFG();
43     MachineFunctionPass::getAnalysisUsage(AU);
44   }
45 };
46 
47 } // End anonymous namespace.
48 
49 INITIALIZE_PASS(SIShrinkInstructions, DEBUG_TYPE,
50                 "SI Shrink Instructions", false, false)
51 
52 char SIShrinkInstructions::ID = 0;
53 
54 FunctionPass *llvm::createSIShrinkInstructionsPass() {
55   return new SIShrinkInstructions();
56 }
57 
58 /// This function checks \p MI for operands defined by a move immediate
59 /// instruction and then folds the literal constant into the instruction if it
60 /// can. This function assumes that \p MI is a VOP1, VOP2, or VOPC instructions.
61 static bool foldImmediates(MachineInstr &MI, const SIInstrInfo *TII,
62                            MachineRegisterInfo &MRI, bool TryToCommute = true) {
63   assert(TII->isVOP1(MI) || TII->isVOP2(MI) || TII->isVOPC(MI));
64 
65   int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
66 
67   // Try to fold Src0
68   MachineOperand &Src0 = MI.getOperand(Src0Idx);
69   if (Src0.isReg()) {
70     Register Reg = Src0.getReg();
71     if (Reg.isVirtual() && MRI.hasOneUse(Reg)) {
72       MachineInstr *Def = MRI.getUniqueVRegDef(Reg);
73       if (Def && Def->isMoveImmediate()) {
74         MachineOperand &MovSrc = Def->getOperand(1);
75         bool ConstantFolded = false;
76 
77         if (MovSrc.isImm() && (isInt<32>(MovSrc.getImm()) ||
78                                isUInt<32>(MovSrc.getImm()))) {
79           Src0.ChangeToImmediate(MovSrc.getImm());
80           ConstantFolded = true;
81         } else if (MovSrc.isFI()) {
82           Src0.ChangeToFrameIndex(MovSrc.getIndex());
83           ConstantFolded = true;
84         } else if (MovSrc.isGlobal()) {
85           Src0.ChangeToGA(MovSrc.getGlobal(), MovSrc.getOffset(),
86                           MovSrc.getTargetFlags());
87           ConstantFolded = true;
88         }
89 
90         if (ConstantFolded) {
91           assert(MRI.use_empty(Reg));
92           Def->eraseFromParent();
93           ++NumLiteralConstantsFolded;
94           return true;
95         }
96       }
97     }
98   }
99 
100   // We have failed to fold src0, so commute the instruction and try again.
101   if (TryToCommute && MI.isCommutable()) {
102     if (TII->commuteInstruction(MI)) {
103       if (foldImmediates(MI, TII, MRI, false))
104         return true;
105 
106       // Commute back.
107       TII->commuteInstruction(MI);
108     }
109   }
110 
111   return false;
112 }
113 
114 static bool isKImmOperand(const SIInstrInfo *TII, const MachineOperand &Src) {
115   return isInt<16>(Src.getImm()) &&
116     !TII->isInlineConstant(*Src.getParent(),
117                            Src.getParent()->getOperandNo(&Src));
118 }
119 
120 static bool isKUImmOperand(const SIInstrInfo *TII, const MachineOperand &Src) {
121   return isUInt<16>(Src.getImm()) &&
122     !TII->isInlineConstant(*Src.getParent(),
123                            Src.getParent()->getOperandNo(&Src));
124 }
125 
126 static bool isKImmOrKUImmOperand(const SIInstrInfo *TII,
127                                  const MachineOperand &Src,
128                                  bool &IsUnsigned) {
129   if (isInt<16>(Src.getImm())) {
130     IsUnsigned = false;
131     return !TII->isInlineConstant(Src);
132   }
133 
134   if (isUInt<16>(Src.getImm())) {
135     IsUnsigned = true;
136     return !TII->isInlineConstant(Src);
137   }
138 
139   return false;
140 }
141 
142 /// \returns true if the constant in \p Src should be replaced with a bitreverse
143 /// of an inline immediate.
144 static bool isReverseInlineImm(const SIInstrInfo *TII,
145                                const MachineOperand &Src,
146                                int32_t &ReverseImm) {
147   if (!isInt<32>(Src.getImm()) || TII->isInlineConstant(Src))
148     return false;
149 
150   ReverseImm = reverseBits<int32_t>(static_cast<int32_t>(Src.getImm()));
151   return ReverseImm >= -16 && ReverseImm <= 64;
152 }
153 
154 /// Copy implicit register operands from specified instruction to this
155 /// instruction that are not part of the instruction definition.
156 static void copyExtraImplicitOps(MachineInstr &NewMI, MachineFunction &MF,
157                                  const MachineInstr &MI) {
158   for (unsigned i = MI.getDesc().getNumOperands() +
159          MI.getDesc().getNumImplicitUses() +
160          MI.getDesc().getNumImplicitDefs(), e = MI.getNumOperands();
161        i != e; ++i) {
162     const MachineOperand &MO = MI.getOperand(i);
163     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
164       NewMI.addOperand(MF, MO);
165   }
166 }
167 
168 static void shrinkScalarCompare(const SIInstrInfo *TII, MachineInstr &MI) {
169   // cmpk instructions do scc = dst <cc op> imm16, so commute the instruction to
170   // get constants on the RHS.
171   if (!MI.getOperand(0).isReg())
172     TII->commuteInstruction(MI, false, 0, 1);
173 
174   // cmpk requires src0 to be a register
175   const MachineOperand &Src0 = MI.getOperand(0);
176   if (!Src0.isReg())
177     return;
178 
179   const MachineOperand &Src1 = MI.getOperand(1);
180   if (!Src1.isImm())
181     return;
182 
183   int SOPKOpc = AMDGPU::getSOPKOp(MI.getOpcode());
184   if (SOPKOpc == -1)
185     return;
186 
187   // eq/ne is special because the imm16 can be treated as signed or unsigned,
188   // and initially selectd to the unsigned versions.
189   if (SOPKOpc == AMDGPU::S_CMPK_EQ_U32 || SOPKOpc == AMDGPU::S_CMPK_LG_U32) {
190     bool HasUImm;
191     if (isKImmOrKUImmOperand(TII, Src1, HasUImm)) {
192       if (!HasUImm) {
193         SOPKOpc = (SOPKOpc == AMDGPU::S_CMPK_EQ_U32) ?
194           AMDGPU::S_CMPK_EQ_I32 : AMDGPU::S_CMPK_LG_I32;
195       }
196 
197       MI.setDesc(TII->get(SOPKOpc));
198     }
199 
200     return;
201   }
202 
203   const MCInstrDesc &NewDesc = TII->get(SOPKOpc);
204 
205   if ((TII->sopkIsZext(SOPKOpc) && isKUImmOperand(TII, Src1)) ||
206       (!TII->sopkIsZext(SOPKOpc) && isKImmOperand(TII, Src1))) {
207     MI.setDesc(NewDesc);
208   }
209 }
210 
211 // Shrink NSA encoded instructions with contiguous VGPRs to non-NSA encoding.
212 void SIShrinkInstructions::shrinkMIMG(MachineInstr &MI) {
213   const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
214   if (!Info || Info->MIMGEncoding != AMDGPU::MIMGEncGfx10NSA)
215     return;
216 
217   MachineFunction *MF = MI.getParent()->getParent();
218   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
219   const SIInstrInfo *TII = ST.getInstrInfo();
220   const SIRegisterInfo &TRI = TII->getRegisterInfo();
221   int VAddr0Idx =
222       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vaddr0);
223   unsigned NewAddrDwords = Info->VAddrDwords;
224   const TargetRegisterClass *RC;
225 
226   if (Info->VAddrDwords == 2) {
227     RC = &AMDGPU::VReg_64RegClass;
228   } else if (Info->VAddrDwords == 3) {
229     RC = &AMDGPU::VReg_96RegClass;
230   } else if (Info->VAddrDwords == 4) {
231     RC = &AMDGPU::VReg_128RegClass;
232   } else if (Info->VAddrDwords <= 8) {
233     RC = &AMDGPU::VReg_256RegClass;
234     NewAddrDwords = 8;
235   } else {
236     RC = &AMDGPU::VReg_512RegClass;
237     NewAddrDwords = 16;
238   }
239 
240   unsigned VgprBase = 0;
241   bool IsUndef = true;
242   bool IsKill = NewAddrDwords == Info->VAddrDwords;
243   for (unsigned i = 0; i < Info->VAddrDwords; ++i) {
244     const MachineOperand &Op = MI.getOperand(VAddr0Idx + i);
245     unsigned Vgpr = TRI.getHWRegIndex(Op.getReg());
246 
247     if (i == 0) {
248       VgprBase = Vgpr;
249     } else if (VgprBase + i != Vgpr)
250       return;
251 
252     if (!Op.isUndef())
253       IsUndef = false;
254     if (!Op.isKill())
255       IsKill = false;
256   }
257 
258   if (VgprBase + NewAddrDwords > 256)
259     return;
260 
261   // Further check for implicit tied operands - this may be present if TFE is
262   // enabled
263   int TFEIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::tfe);
264   int LWEIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::lwe);
265   unsigned TFEVal = (TFEIdx == -1) ? 0 : MI.getOperand(TFEIdx).getImm();
266   unsigned LWEVal = (LWEIdx == -1) ? 0 : MI.getOperand(LWEIdx).getImm();
267   int ToUntie = -1;
268   if (TFEVal || LWEVal) {
269     // TFE/LWE is enabled so we need to deal with an implicit tied operand
270     for (unsigned i = LWEIdx + 1, e = MI.getNumOperands(); i != e; ++i) {
271       if (MI.getOperand(i).isReg() && MI.getOperand(i).isTied() &&
272           MI.getOperand(i).isImplicit()) {
273         // This is the tied operand
274         assert(
275             ToUntie == -1 &&
276             "found more than one tied implicit operand when expecting only 1");
277         ToUntie = i;
278         MI.untieRegOperand(ToUntie);
279       }
280     }
281   }
282 
283   unsigned NewOpcode =
284       AMDGPU::getMIMGOpcode(Info->BaseOpcode, AMDGPU::MIMGEncGfx10Default,
285                             Info->VDataDwords, NewAddrDwords);
286   MI.setDesc(TII->get(NewOpcode));
287   MI.getOperand(VAddr0Idx).setReg(RC->getRegister(VgprBase));
288   MI.getOperand(VAddr0Idx).setIsUndef(IsUndef);
289   MI.getOperand(VAddr0Idx).setIsKill(IsKill);
290 
291   for (unsigned i = 1; i < Info->VAddrDwords; ++i)
292     MI.RemoveOperand(VAddr0Idx + 1);
293 
294   if (ToUntie >= 0) {
295     MI.tieOperands(
296         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata),
297         ToUntie - (Info->VAddrDwords - 1));
298   }
299 }
300 
301 /// Attempt to shink AND/OR/XOR operations requiring non-inlineable literals.
302 /// For AND or OR, try using S_BITSET{0,1} to clear or set bits.
303 /// If the inverse of the immediate is legal, use ANDN2, ORN2 or
304 /// XNOR (as a ^ b == ~(a ^ ~b)).
305 /// \returns true if the caller should continue the machine function iterator
306 static bool shrinkScalarLogicOp(const GCNSubtarget &ST,
307                                 MachineRegisterInfo &MRI,
308                                 const SIInstrInfo *TII,
309                                 MachineInstr &MI) {
310   unsigned Opc = MI.getOpcode();
311   const MachineOperand *Dest = &MI.getOperand(0);
312   MachineOperand *Src0 = &MI.getOperand(1);
313   MachineOperand *Src1 = &MI.getOperand(2);
314   MachineOperand *SrcReg = Src0;
315   MachineOperand *SrcImm = Src1;
316 
317   if (!SrcImm->isImm() ||
318       AMDGPU::isInlinableLiteral32(SrcImm->getImm(), ST.hasInv2PiInlineImm()))
319     return false;
320 
321   uint32_t Imm = static_cast<uint32_t>(SrcImm->getImm());
322   uint32_t NewImm = 0;
323 
324   if (Opc == AMDGPU::S_AND_B32) {
325     if (isPowerOf2_32(~Imm)) {
326       NewImm = countTrailingOnes(Imm);
327       Opc = AMDGPU::S_BITSET0_B32;
328     } else if (AMDGPU::isInlinableLiteral32(~Imm, ST.hasInv2PiInlineImm())) {
329       NewImm = ~Imm;
330       Opc = AMDGPU::S_ANDN2_B32;
331     }
332   } else if (Opc == AMDGPU::S_OR_B32) {
333     if (isPowerOf2_32(Imm)) {
334       NewImm = countTrailingZeros(Imm);
335       Opc = AMDGPU::S_BITSET1_B32;
336     } else if (AMDGPU::isInlinableLiteral32(~Imm, ST.hasInv2PiInlineImm())) {
337       NewImm = ~Imm;
338       Opc = AMDGPU::S_ORN2_B32;
339     }
340   } else if (Opc == AMDGPU::S_XOR_B32) {
341     if (AMDGPU::isInlinableLiteral32(~Imm, ST.hasInv2PiInlineImm())) {
342       NewImm = ~Imm;
343       Opc = AMDGPU::S_XNOR_B32;
344     }
345   } else {
346     llvm_unreachable("unexpected opcode");
347   }
348 
349   if ((Opc == AMDGPU::S_ANDN2_B32 || Opc == AMDGPU::S_ORN2_B32) &&
350       SrcImm == Src0) {
351     if (!TII->commuteInstruction(MI, false, 1, 2))
352       NewImm = 0;
353   }
354 
355   if (NewImm != 0) {
356     if (Dest->getReg().isVirtual() && SrcReg->isReg()) {
357       MRI.setRegAllocationHint(Dest->getReg(), 0, SrcReg->getReg());
358       MRI.setRegAllocationHint(SrcReg->getReg(), 0, Dest->getReg());
359       return true;
360     }
361 
362     if (SrcReg->isReg() && SrcReg->getReg() == Dest->getReg()) {
363       const bool IsUndef = SrcReg->isUndef();
364       const bool IsKill = SrcReg->isKill();
365       MI.setDesc(TII->get(Opc));
366       if (Opc == AMDGPU::S_BITSET0_B32 ||
367           Opc == AMDGPU::S_BITSET1_B32) {
368         Src0->ChangeToImmediate(NewImm);
369         // Remove the immediate and add the tied input.
370         MI.getOperand(2).ChangeToRegister(Dest->getReg(), /*IsDef*/ false,
371                                           /*isImp*/ false, IsKill,
372                                           /*isDead*/ false, IsUndef);
373         MI.tieOperands(0, 2);
374       } else {
375         SrcImm->setImm(NewImm);
376       }
377     }
378   }
379 
380   return false;
381 }
382 
383 // This is the same as MachineInstr::readsRegister/modifiesRegister except
384 // it takes subregs into account.
385 static bool instAccessReg(iterator_range<MachineInstr::const_mop_iterator> &&R,
386                           Register Reg, unsigned SubReg,
387                           const SIRegisterInfo &TRI) {
388   for (const MachineOperand &MO : R) {
389     if (!MO.isReg())
390       continue;
391 
392     if (Reg.isPhysical() && MO.getReg().isPhysical()) {
393       if (TRI.regsOverlap(Reg, MO.getReg()))
394         return true;
395     } else if (MO.getReg() == Reg && Reg.isVirtual()) {
396       LaneBitmask Overlap = TRI.getSubRegIndexLaneMask(SubReg) &
397                             TRI.getSubRegIndexLaneMask(MO.getSubReg());
398       if (Overlap.any())
399         return true;
400     }
401   }
402   return false;
403 }
404 
405 static bool instReadsReg(const MachineInstr *MI,
406                          unsigned Reg, unsigned SubReg,
407                          const SIRegisterInfo &TRI) {
408   return instAccessReg(MI->uses(), Reg, SubReg, TRI);
409 }
410 
411 static bool instModifiesReg(const MachineInstr *MI,
412                             unsigned Reg, unsigned SubReg,
413                             const SIRegisterInfo &TRI) {
414   return instAccessReg(MI->defs(), Reg, SubReg, TRI);
415 }
416 
417 static TargetInstrInfo::RegSubRegPair
418 getSubRegForIndex(Register Reg, unsigned Sub, unsigned I,
419                   const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) {
420   if (TRI.getRegSizeInBits(Reg, MRI) != 32) {
421     if (Reg.isPhysical()) {
422       Reg = TRI.getSubReg(Reg, TRI.getSubRegFromChannel(I));
423     } else {
424       Sub = TRI.getSubRegFromChannel(I + TRI.getChannelFromSubReg(Sub));
425     }
426   }
427   return TargetInstrInfo::RegSubRegPair(Reg, Sub);
428 }
429 
430 static void dropInstructionKeepingImpDefs(MachineInstr &MI,
431                                           const SIInstrInfo *TII) {
432   for (unsigned i = MI.getDesc().getNumOperands() +
433          MI.getDesc().getNumImplicitUses() +
434          MI.getDesc().getNumImplicitDefs(), e = MI.getNumOperands();
435        i != e; ++i) {
436     const MachineOperand &Op = MI.getOperand(i);
437     if (!Op.isDef())
438       continue;
439     BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
440             TII->get(AMDGPU::IMPLICIT_DEF), Op.getReg());
441   }
442 
443   MI.eraseFromParent();
444 }
445 
446 // Match:
447 // mov t, x
448 // mov x, y
449 // mov y, t
450 //
451 // =>
452 //
453 // mov t, x (t is potentially dead and move eliminated)
454 // v_swap_b32 x, y
455 //
456 // Returns next valid instruction pointer if was able to create v_swap_b32.
457 //
458 // This shall not be done too early not to prevent possible folding which may
459 // remove matched moves, and this should prefereably be done before RA to
460 // release saved registers and also possibly after RA which can insert copies
461 // too.
462 //
463 // This is really just a generic peephole that is not a canocical shrinking,
464 // although requirements match the pass placement and it reduces code size too.
465 static MachineInstr* matchSwap(MachineInstr &MovT, MachineRegisterInfo &MRI,
466                                const SIInstrInfo *TII) {
467   assert(MovT.getOpcode() == AMDGPU::V_MOV_B32_e32 ||
468          MovT.getOpcode() == AMDGPU::COPY);
469 
470   Register T = MovT.getOperand(0).getReg();
471   unsigned Tsub = MovT.getOperand(0).getSubReg();
472   MachineOperand &Xop = MovT.getOperand(1);
473 
474   if (!Xop.isReg())
475     return nullptr;
476   Register X = Xop.getReg();
477   unsigned Xsub = Xop.getSubReg();
478 
479   unsigned Size = TII->getOpSize(MovT, 0) / 4;
480 
481   const SIRegisterInfo &TRI = TII->getRegisterInfo();
482   if (!TRI.isVGPR(MRI, X))
483     return nullptr;
484 
485   if (MovT.hasRegisterImplicitUseOperand(AMDGPU::M0))
486     return nullptr;
487 
488   const unsigned SearchLimit = 16;
489   unsigned Count = 0;
490   bool KilledT = false;
491   for (auto Iter = std::next(MovT.getIterator()),
492             E = MovT.getParent()->instr_end();
493        Iter != E && Count < SearchLimit && !KilledT; ++Iter, ++Count) {
494 
495     MachineInstr *MovY = &*Iter;
496     KilledT = MovY->killsRegister(T, &TRI);
497 
498     if ((MovY->getOpcode() != AMDGPU::V_MOV_B32_e32 &&
499          MovY->getOpcode() != AMDGPU::COPY) ||
500         !MovY->getOperand(1).isReg()        ||
501         MovY->getOperand(1).getReg() != T   ||
502         MovY->getOperand(1).getSubReg() != Tsub ||
503         MovY->hasRegisterImplicitUseOperand(AMDGPU::M0))
504       continue;
505 
506     Register Y = MovY->getOperand(0).getReg();
507     unsigned Ysub = MovY->getOperand(0).getSubReg();
508 
509     if (!TRI.isVGPR(MRI, Y))
510       continue;
511 
512     MachineInstr *MovX = nullptr;
513     for (auto IY = MovY->getIterator(), I = std::next(MovT.getIterator());
514          I != IY; ++I) {
515       if (instReadsReg(&*I, X, Xsub, TRI)    ||
516           instModifiesReg(&*I, Y, Ysub, TRI) ||
517           instModifiesReg(&*I, T, Tsub, TRI) ||
518           (MovX && instModifiesReg(&*I, X, Xsub, TRI))) {
519         MovX = nullptr;
520         break;
521       }
522       if (!instReadsReg(&*I, Y, Ysub, TRI)) {
523         if (!MovX && instModifiesReg(&*I, X, Xsub, TRI)) {
524           MovX = nullptr;
525           break;
526         }
527         continue;
528       }
529       if (MovX ||
530           (I->getOpcode() != AMDGPU::V_MOV_B32_e32 &&
531            I->getOpcode() != AMDGPU::COPY) ||
532           I->getOperand(0).getReg() != X ||
533           I->getOperand(0).getSubReg() != Xsub) {
534         MovX = nullptr;
535         break;
536       }
537       // Implicit use of M0 is an indirect move.
538       if (I->hasRegisterImplicitUseOperand(AMDGPU::M0))
539         continue;
540 
541       if (Size > 1 && (I->getNumImplicitOperands() > (I->isCopy() ? 0U : 1U)))
542         continue;
543 
544       MovX = &*I;
545     }
546 
547     if (!MovX)
548       continue;
549 
550     LLVM_DEBUG(dbgs() << "Matched v_swap_b32:\n" << MovT << *MovX << *MovY);
551 
552     for (unsigned I = 0; I < Size; ++I) {
553       TargetInstrInfo::RegSubRegPair X1, Y1;
554       X1 = getSubRegForIndex(X, Xsub, I, TRI, MRI);
555       Y1 = getSubRegForIndex(Y, Ysub, I, TRI, MRI);
556       MachineBasicBlock &MBB = *MovT.getParent();
557       auto MIB = BuildMI(MBB, MovX->getIterator(), MovT.getDebugLoc(),
558                          TII->get(AMDGPU::V_SWAP_B32))
559         .addDef(X1.Reg, 0, X1.SubReg)
560         .addDef(Y1.Reg, 0, Y1.SubReg)
561         .addReg(Y1.Reg, 0, Y1.SubReg)
562         .addReg(X1.Reg, 0, X1.SubReg).getInstr();
563       if (MovX->hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
564         // Drop implicit EXEC.
565         MIB->RemoveOperand(MIB->getNumExplicitOperands());
566         MIB->copyImplicitOps(*MBB.getParent(), *MovX);
567       }
568     }
569     MovX->eraseFromParent();
570     dropInstructionKeepingImpDefs(*MovY, TII);
571     MachineInstr *Next = &*std::next(MovT.getIterator());
572 
573     if (MRI.use_nodbg_empty(T)) {
574       dropInstructionKeepingImpDefs(MovT, TII);
575     } else {
576       Xop.setIsKill(false);
577       for (int I = MovT.getNumImplicitOperands() - 1; I >= 0; --I ) {
578         unsigned OpNo = MovT.getNumExplicitOperands() + I;
579         const MachineOperand &Op = MovT.getOperand(OpNo);
580         if (Op.isKill() && TRI.regsOverlap(X, Op.getReg()))
581           MovT.RemoveOperand(OpNo);
582       }
583     }
584 
585     return Next;
586   }
587 
588   return nullptr;
589 }
590 
591 bool SIShrinkInstructions::runOnMachineFunction(MachineFunction &MF) {
592   if (skipFunction(MF.getFunction()))
593     return false;
594 
595   MachineRegisterInfo &MRI = MF.getRegInfo();
596   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
597   const SIInstrInfo *TII = ST.getInstrInfo();
598   unsigned VCCReg = ST.isWave32() ? AMDGPU::VCC_LO : AMDGPU::VCC;
599 
600   std::vector<unsigned> I1Defs;
601 
602   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
603                                                   BI != BE; ++BI) {
604 
605     MachineBasicBlock &MBB = *BI;
606     MachineBasicBlock::iterator I, Next;
607     for (I = MBB.begin(); I != MBB.end(); I = Next) {
608       Next = std::next(I);
609       MachineInstr &MI = *I;
610 
611       if (MI.getOpcode() == AMDGPU::V_MOV_B32_e32) {
612         // If this has a literal constant source that is the same as the
613         // reversed bits of an inline immediate, replace with a bitreverse of
614         // that constant. This saves 4 bytes in the common case of materializing
615         // sign bits.
616 
617         // Test if we are after regalloc. We only want to do this after any
618         // optimizations happen because this will confuse them.
619         // XXX - not exactly a check for post-regalloc run.
620         MachineOperand &Src = MI.getOperand(1);
621         if (Src.isImm() && MI.getOperand(0).getReg().isPhysical()) {
622           int32_t ReverseImm;
623           if (isReverseInlineImm(TII, Src, ReverseImm)) {
624             MI.setDesc(TII->get(AMDGPU::V_BFREV_B32_e32));
625             Src.setImm(ReverseImm);
626             continue;
627           }
628         }
629       }
630 
631       if (ST.hasSwap() && (MI.getOpcode() == AMDGPU::V_MOV_B32_e32 ||
632                            MI.getOpcode() == AMDGPU::COPY)) {
633         if (auto *NextMI = matchSwap(MI, MRI, TII)) {
634           Next = NextMI->getIterator();
635           continue;
636         }
637       }
638 
639       // FIXME: We also need to consider movs of constant operands since
640       // immediate operands are not folded if they have more than one use, and
641       // the operand folding pass is unaware if the immediate will be free since
642       // it won't know if the src == dest constraint will end up being
643       // satisfied.
644       if (MI.getOpcode() == AMDGPU::S_ADD_I32 ||
645           MI.getOpcode() == AMDGPU::S_MUL_I32) {
646         const MachineOperand *Dest = &MI.getOperand(0);
647         MachineOperand *Src0 = &MI.getOperand(1);
648         MachineOperand *Src1 = &MI.getOperand(2);
649 
650         if (!Src0->isReg() && Src1->isReg()) {
651           if (TII->commuteInstruction(MI, false, 1, 2))
652             std::swap(Src0, Src1);
653         }
654 
655         // FIXME: This could work better if hints worked with subregisters. If
656         // we have a vector add of a constant, we usually don't get the correct
657         // allocation due to the subregister usage.
658         if (Dest->getReg().isVirtual() && Src0->isReg()) {
659           MRI.setRegAllocationHint(Dest->getReg(), 0, Src0->getReg());
660           MRI.setRegAllocationHint(Src0->getReg(), 0, Dest->getReg());
661           continue;
662         }
663 
664         if (Src0->isReg() && Src0->getReg() == Dest->getReg()) {
665           if (Src1->isImm() && isKImmOperand(TII, *Src1)) {
666             unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_I32) ?
667               AMDGPU::S_ADDK_I32 : AMDGPU::S_MULK_I32;
668 
669             MI.setDesc(TII->get(Opc));
670             MI.tieOperands(0, 1);
671           }
672         }
673       }
674 
675       // Try to use s_cmpk_*
676       if (MI.isCompare() && TII->isSOPC(MI)) {
677         shrinkScalarCompare(TII, MI);
678         continue;
679       }
680 
681       // Try to use S_MOVK_I32, which will save 4 bytes for small immediates.
682       if (MI.getOpcode() == AMDGPU::S_MOV_B32) {
683         const MachineOperand &Dst = MI.getOperand(0);
684         MachineOperand &Src = MI.getOperand(1);
685 
686         if (Src.isImm() && Dst.getReg().isPhysical()) {
687           int32_t ReverseImm;
688           if (isKImmOperand(TII, Src))
689             MI.setDesc(TII->get(AMDGPU::S_MOVK_I32));
690           else if (isReverseInlineImm(TII, Src, ReverseImm)) {
691             MI.setDesc(TII->get(AMDGPU::S_BREV_B32));
692             Src.setImm(ReverseImm);
693           }
694         }
695 
696         continue;
697       }
698 
699       // Shrink scalar logic operations.
700       if (MI.getOpcode() == AMDGPU::S_AND_B32 ||
701           MI.getOpcode() == AMDGPU::S_OR_B32 ||
702           MI.getOpcode() == AMDGPU::S_XOR_B32) {
703         if (shrinkScalarLogicOp(ST, MRI, TII, MI))
704           continue;
705       }
706 
707       if (TII->isMIMG(MI.getOpcode()) &&
708           ST.getGeneration() >= AMDGPUSubtarget::GFX10 &&
709           MF.getProperties().hasProperty(
710               MachineFunctionProperties::Property::NoVRegs)) {
711         shrinkMIMG(MI);
712         continue;
713       }
714 
715       if (!TII->hasVALU32BitEncoding(MI.getOpcode()))
716         continue;
717 
718       if (!TII->canShrink(MI, MRI)) {
719         // Try commuting the instruction and see if that enables us to shrink
720         // it.
721         if (!MI.isCommutable() || !TII->commuteInstruction(MI) ||
722             !TII->canShrink(MI, MRI))
723           continue;
724       }
725 
726       // getVOPe32 could be -1 here if we started with an instruction that had
727       // a 32-bit encoding and then commuted it to an instruction that did not.
728       if (!TII->hasVALU32BitEncoding(MI.getOpcode()))
729         continue;
730 
731       int Op32 = AMDGPU::getVOPe32(MI.getOpcode());
732 
733       if (TII->isVOPC(Op32)) {
734         Register DstReg = MI.getOperand(0).getReg();
735         if (DstReg.isVirtual()) {
736           // VOPC instructions can only write to the VCC register. We can't
737           // force them to use VCC here, because this is only one register and
738           // cannot deal with sequences which would require multiple copies of
739           // VCC, e.g. S_AND_B64 (vcc = V_CMP_...), (vcc = V_CMP_...)
740           //
741           // So, instead of forcing the instruction to write to VCC, we provide
742           // a hint to the register allocator to use VCC and then we will run
743           // this pass again after RA and shrink it if it outputs to VCC.
744           MRI.setRegAllocationHint(MI.getOperand(0).getReg(), 0, VCCReg);
745           continue;
746         }
747         if (DstReg != VCCReg)
748           continue;
749       }
750 
751       if (Op32 == AMDGPU::V_CNDMASK_B32_e32) {
752         // We shrink V_CNDMASK_B32_e64 using regalloc hints like we do for VOPC
753         // instructions.
754         const MachineOperand *Src2 =
755             TII->getNamedOperand(MI, AMDGPU::OpName::src2);
756         if (!Src2->isReg())
757           continue;
758         Register SReg = Src2->getReg();
759         if (SReg.isVirtual()) {
760           MRI.setRegAllocationHint(SReg, 0, VCCReg);
761           continue;
762         }
763         if (SReg != VCCReg)
764           continue;
765       }
766 
767       // Check for the bool flag output for instructions like V_ADD_I32_e64.
768       const MachineOperand *SDst = TII->getNamedOperand(MI,
769                                                         AMDGPU::OpName::sdst);
770 
771       // Check the carry-in operand for v_addc_u32_e64.
772       const MachineOperand *Src2 = TII->getNamedOperand(MI,
773                                                         AMDGPU::OpName::src2);
774 
775       if (SDst) {
776         bool Next = false;
777 
778         if (SDst->getReg() != VCCReg) {
779           if (SDst->getReg().isVirtual())
780             MRI.setRegAllocationHint(SDst->getReg(), 0, VCCReg);
781           Next = true;
782         }
783 
784         // All of the instructions with carry outs also have an SGPR input in
785         // src2.
786         if (Src2 && Src2->getReg() != VCCReg) {
787           if (Src2->getReg().isVirtual())
788             MRI.setRegAllocationHint(Src2->getReg(), 0, VCCReg);
789           Next = true;
790         }
791 
792         if (Next)
793           continue;
794       }
795 
796       // We can shrink this instruction
797       LLVM_DEBUG(dbgs() << "Shrinking " << MI);
798 
799       MachineInstr *Inst32 = TII->buildShrunkInst(MI, Op32);
800       ++NumInstructionsShrunk;
801 
802       // Copy extra operands not present in the instruction definition.
803       copyExtraImplicitOps(*Inst32, MF, MI);
804 
805       MI.eraseFromParent();
806       foldImmediates(*Inst32, TII, MRI);
807 
808       LLVM_DEBUG(dbgs() << "e32 MI = " << *Inst32 << '\n');
809     }
810   }
811   return false;
812 }
813