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