1 //===-- SIShrinkInstructions.cpp - Shrink Instructions --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 /// The pass tries to use the 32-bit encoding for instructions when possible.
9 //===----------------------------------------------------------------------===//
10 //
11 
12 #include "AMDGPU.h"
13 #include "AMDGPUMCInstLower.h"
14 #include "AMDGPUSubtarget.h"
15 #include "SIInstrInfo.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetMachine.h"
26 
27 #define DEBUG_TYPE "si-shrink-instructions"
28 
29 STATISTIC(NumInstructionsShrunk,
30           "Number of 64-bit instruction reduced to 32-bit.");
31 STATISTIC(NumLiteralConstantsFolded,
32           "Number of literal constants folded into 32-bit instructions.");
33 
34 using namespace llvm;
35 
36 namespace {
37 
38 class SIShrinkInstructions : public MachineFunctionPass {
39 public:
40   static char ID;
41 
42 public:
43   SIShrinkInstructions() : MachineFunctionPass(ID) {
44   }
45 
46   bool runOnMachineFunction(MachineFunction &MF) override;
47 
48   StringRef getPassName() const override { return "SI Shrink Instructions"; }
49 
50   void getAnalysisUsage(AnalysisUsage &AU) const override {
51     AU.setPreservesCFG();
52     MachineFunctionPass::getAnalysisUsage(AU);
53   }
54 };
55 
56 } // End anonymous namespace.
57 
58 INITIALIZE_PASS(SIShrinkInstructions, DEBUG_TYPE,
59                 "SI Shrink Instructions", false, false)
60 
61 char SIShrinkInstructions::ID = 0;
62 
63 FunctionPass *llvm::createSIShrinkInstructionsPass() {
64   return new SIShrinkInstructions();
65 }
66 
67 static bool isVGPR(const MachineOperand *MO, const SIRegisterInfo &TRI,
68                    const MachineRegisterInfo &MRI) {
69   if (!MO->isReg())
70     return false;
71 
72   if (TargetRegisterInfo::isVirtualRegister(MO->getReg()))
73     return TRI.hasVGPRs(MRI.getRegClass(MO->getReg()));
74 
75   return TRI.hasVGPRs(TRI.getPhysRegClass(MO->getReg()));
76 }
77 
78 static bool canShrink(MachineInstr &MI, const SIInstrInfo *TII,
79                       const SIRegisterInfo &TRI,
80                       const MachineRegisterInfo &MRI) {
81 
82   const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
83   // Can't shrink instruction with three operands.
84   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
85   // a special case for it.  It can only be shrunk if the third operand
86   // is vcc.  We should handle this the same way we handle vopc, by addding
87   // a register allocation hint pre-regalloc and then do the shrinking
88   // post-regalloc.
89   if (Src2) {
90     switch (MI.getOpcode()) {
91       default: return false;
92 
93       case AMDGPU::V_ADDC_U32_e64:
94       case AMDGPU::V_SUBB_U32_e64:
95         if (TII->getNamedOperand(MI, AMDGPU::OpName::src1)->isImm())
96           return false;
97         // Additional verification is needed for sdst/src2.
98         return true;
99 
100       case AMDGPU::V_MAC_F32_e64:
101       case AMDGPU::V_MAC_F16_e64:
102         if (!isVGPR(Src2, TRI, MRI) ||
103             TII->hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
104           return false;
105         break;
106 
107       case AMDGPU::V_CNDMASK_B32_e64:
108         break;
109     }
110   }
111 
112   const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
113   if (Src1 && (!isVGPR(Src1, TRI, MRI) ||
114                TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
115     return false;
116 
117   // We don't need to check src0, all input types are legal, so just make sure
118   // src0 isn't using any modifiers.
119   if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
120     return false;
121 
122   // Check output modifiers
123   return !TII->hasModifiersSet(MI, AMDGPU::OpName::omod) &&
124          !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp);
125 }
126 
127 /// \brief This function checks \p MI for operands defined by a move immediate
128 /// instruction and then folds the literal constant into the instruction if it
129 /// can.  This function assumes that \p MI is a VOP1, VOP2, or VOPC instruction
130 /// and will only fold literal constants if we are still in SSA.
131 static void foldImmediates(MachineInstr &MI, const SIInstrInfo *TII,
132                            MachineRegisterInfo &MRI, bool TryToCommute = true) {
133 
134   if (!MRI.isSSA())
135     return;
136 
137   assert(TII->isVOP1(MI) || TII->isVOP2(MI) || TII->isVOPC(MI));
138 
139   int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
140 
141   // Only one literal constant is allowed per instruction, so if src0 is a
142   // literal constant then we can't do any folding.
143   if (TII->isLiteralConstant(MI, Src0Idx))
144     return;
145 
146   // Try to fold Src0
147   MachineOperand &Src0 = MI.getOperand(Src0Idx);
148   if (Src0.isReg() && MRI.hasOneUse(Src0.getReg())) {
149     unsigned Reg = Src0.getReg();
150     MachineInstr *Def = MRI.getUniqueVRegDef(Reg);
151     if (Def && Def->isMoveImmediate()) {
152       MachineOperand &MovSrc = Def->getOperand(1);
153       bool ConstantFolded = false;
154 
155       if (MovSrc.isImm() && (isInt<32>(MovSrc.getImm()) ||
156                              isUInt<32>(MovSrc.getImm()))) {
157         Src0.ChangeToImmediate(MovSrc.getImm());
158         ConstantFolded = true;
159       }
160       if (ConstantFolded) {
161         if (MRI.use_empty(Reg))
162           Def->eraseFromParent();
163         ++NumLiteralConstantsFolded;
164         return;
165       }
166     }
167   }
168 
169   // We have failed to fold src0, so commute the instruction and try again.
170   if (TryToCommute && MI.isCommutable() && TII->commuteInstruction(MI))
171     foldImmediates(MI, TII, MRI, false);
172 
173 }
174 
175 // Copy MachineOperand with all flags except setting it as implicit.
176 static void copyFlagsToImplicitVCC(MachineInstr &MI,
177                                    const MachineOperand &Orig) {
178 
179   for (MachineOperand &Use : MI.implicit_operands()) {
180     if (Use.isUse() && Use.getReg() == AMDGPU::VCC) {
181       Use.setIsUndef(Orig.isUndef());
182       Use.setIsKill(Orig.isKill());
183       return;
184     }
185   }
186 }
187 
188 static bool isKImmOperand(const SIInstrInfo *TII, const MachineOperand &Src) {
189   return isInt<16>(Src.getImm()) &&
190     !TII->isInlineConstant(*Src.getParent(),
191                            Src.getParent()->getOperandNo(&Src));
192 }
193 
194 static bool isKUImmOperand(const SIInstrInfo *TII, const MachineOperand &Src) {
195   return isUInt<16>(Src.getImm()) &&
196     !TII->isInlineConstant(*Src.getParent(),
197                            Src.getParent()->getOperandNo(&Src));
198 }
199 
200 static bool isKImmOrKUImmOperand(const SIInstrInfo *TII,
201                                  const MachineOperand &Src,
202                                  bool &IsUnsigned) {
203   if (isInt<16>(Src.getImm())) {
204     IsUnsigned = false;
205     return !TII->isInlineConstant(Src);
206   }
207 
208   if (isUInt<16>(Src.getImm())) {
209     IsUnsigned = true;
210     return !TII->isInlineConstant(Src);
211   }
212 
213   return false;
214 }
215 
216 /// \returns true if the constant in \p Src should be replaced with a bitreverse
217 /// of an inline immediate.
218 static bool isReverseInlineImm(const SIInstrInfo *TII,
219                                const MachineOperand &Src,
220                                int32_t &ReverseImm) {
221   if (!isInt<32>(Src.getImm()) || TII->isInlineConstant(Src))
222     return false;
223 
224   ReverseImm = reverseBits<int32_t>(static_cast<int32_t>(Src.getImm()));
225   return ReverseImm >= -16 && ReverseImm <= 64;
226 }
227 
228 /// Copy implicit register operands from specified instruction to this
229 /// instruction that are not part of the instruction definition.
230 static void copyExtraImplicitOps(MachineInstr &NewMI, MachineFunction &MF,
231                                  const MachineInstr &MI) {
232   for (unsigned i = MI.getDesc().getNumOperands() +
233          MI.getDesc().getNumImplicitUses() +
234          MI.getDesc().getNumImplicitDefs(), e = MI.getNumOperands();
235        i != e; ++i) {
236     const MachineOperand &MO = MI.getOperand(i);
237     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
238       NewMI.addOperand(MF, MO);
239   }
240 }
241 
242 static void shrinkScalarCompare(const SIInstrInfo *TII, MachineInstr &MI) {
243   // cmpk instructions do scc = dst <cc op> imm16, so commute the instruction to
244   // get constants on the RHS.
245   if (!MI.getOperand(0).isReg())
246     TII->commuteInstruction(MI, false, 0, 1);
247 
248   const MachineOperand &Src1 = MI.getOperand(1);
249   if (!Src1.isImm())
250     return;
251 
252   int SOPKOpc = AMDGPU::getSOPKOp(MI.getOpcode());
253   if (SOPKOpc == -1)
254     return;
255 
256   // eq/ne is special because the imm16 can be treated as signed or unsigned,
257   // and initially selectd to the unsigned versions.
258   if (SOPKOpc == AMDGPU::S_CMPK_EQ_U32 || SOPKOpc == AMDGPU::S_CMPK_LG_U32) {
259     bool HasUImm;
260     if (isKImmOrKUImmOperand(TII, Src1, HasUImm)) {
261       if (!HasUImm) {
262         SOPKOpc = (SOPKOpc == AMDGPU::S_CMPK_EQ_U32) ?
263           AMDGPU::S_CMPK_EQ_I32 : AMDGPU::S_CMPK_LG_I32;
264       }
265 
266       MI.setDesc(TII->get(SOPKOpc));
267     }
268 
269     return;
270   }
271 
272   const MCInstrDesc &NewDesc = TII->get(SOPKOpc);
273 
274   if ((TII->sopkIsZext(SOPKOpc) && isKUImmOperand(TII, Src1)) ||
275       (!TII->sopkIsZext(SOPKOpc) && isKImmOperand(TII, Src1))) {
276     MI.setDesc(NewDesc);
277   }
278 }
279 
280 bool SIShrinkInstructions::runOnMachineFunction(MachineFunction &MF) {
281   if (skipFunction(*MF.getFunction()))
282     return false;
283 
284   MachineRegisterInfo &MRI = MF.getRegInfo();
285   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
286   const SIInstrInfo *TII = ST.getInstrInfo();
287   const SIRegisterInfo &TRI = TII->getRegisterInfo();
288 
289   std::vector<unsigned> I1Defs;
290 
291   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
292                                                   BI != BE; ++BI) {
293 
294     MachineBasicBlock &MBB = *BI;
295     MachineBasicBlock::iterator I, Next;
296     for (I = MBB.begin(); I != MBB.end(); I = Next) {
297       Next = std::next(I);
298       MachineInstr &MI = *I;
299 
300       if (MI.getOpcode() == AMDGPU::V_MOV_B32_e32) {
301         // If this has a literal constant source that is the same as the
302         // reversed bits of an inline immediate, replace with a bitreverse of
303         // that constant. This saves 4 bytes in the common case of materializing
304         // sign bits.
305 
306         // Test if we are after regalloc. We only want to do this after any
307         // optimizations happen because this will confuse them.
308         // XXX - not exactly a check for post-regalloc run.
309         MachineOperand &Src = MI.getOperand(1);
310         if (Src.isImm() &&
311             TargetRegisterInfo::isPhysicalRegister(MI.getOperand(0).getReg())) {
312           int32_t ReverseImm;
313           if (isReverseInlineImm(TII, Src, ReverseImm)) {
314             MI.setDesc(TII->get(AMDGPU::V_BFREV_B32_e32));
315             Src.setImm(ReverseImm);
316             continue;
317           }
318         }
319       }
320 
321       // Combine adjacent s_nops to use the immediate operand encoding how long
322       // to wait.
323       //
324       // s_nop N
325       // s_nop M
326       //  =>
327       // s_nop (N + M)
328       if (MI.getOpcode() == AMDGPU::S_NOP &&
329           Next != MBB.end() &&
330           (*Next).getOpcode() == AMDGPU::S_NOP) {
331 
332         MachineInstr &NextMI = *Next;
333         // The instruction encodes the amount to wait with an offset of 1,
334         // i.e. 0 is wait 1 cycle. Convert both to cycles and then convert back
335         // after adding.
336         uint8_t Nop0 = MI.getOperand(0).getImm() + 1;
337         uint8_t Nop1 = NextMI.getOperand(0).getImm() + 1;
338 
339         // Make sure we don't overflow the bounds.
340         if (Nop0 + Nop1 <= 8) {
341           NextMI.getOperand(0).setImm(Nop0 + Nop1 - 1);
342           MI.eraseFromParent();
343         }
344 
345         continue;
346       }
347 
348       // FIXME: We also need to consider movs of constant operands since
349       // immediate operands are not folded if they have more than one use, and
350       // the operand folding pass is unaware if the immediate will be free since
351       // it won't know if the src == dest constraint will end up being
352       // satisfied.
353       if (MI.getOpcode() == AMDGPU::S_ADD_I32 ||
354           MI.getOpcode() == AMDGPU::S_MUL_I32) {
355         const MachineOperand *Dest = &MI.getOperand(0);
356         MachineOperand *Src0 = &MI.getOperand(1);
357         MachineOperand *Src1 = &MI.getOperand(2);
358 
359         if (!Src0->isReg() && Src1->isReg()) {
360           if (TII->commuteInstruction(MI, false, 1, 2))
361             std::swap(Src0, Src1);
362         }
363 
364         // FIXME: This could work better if hints worked with subregisters. If
365         // we have a vector add of a constant, we usually don't get the correct
366         // allocation due to the subregister usage.
367         if (TargetRegisterInfo::isVirtualRegister(Dest->getReg()) &&
368             Src0->isReg()) {
369           MRI.setRegAllocationHint(Dest->getReg(), 0, Src0->getReg());
370           MRI.setRegAllocationHint(Src0->getReg(), 0, Dest->getReg());
371           continue;
372         }
373 
374         if (Src0->isReg() && Src0->getReg() == Dest->getReg()) {
375           if (Src1->isImm() && isKImmOperand(TII, *Src1)) {
376             unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_I32) ?
377               AMDGPU::S_ADDK_I32 : AMDGPU::S_MULK_I32;
378 
379             MI.setDesc(TII->get(Opc));
380             MI.tieOperands(0, 1);
381           }
382         }
383       }
384 
385       // Try to use s_cmpk_*
386       if (MI.isCompare() && TII->isSOPC(MI)) {
387         shrinkScalarCompare(TII, MI);
388         continue;
389       }
390 
391       // Try to use S_MOVK_I32, which will save 4 bytes for small immediates.
392       if (MI.getOpcode() == AMDGPU::S_MOV_B32) {
393         const MachineOperand &Dst = MI.getOperand(0);
394         MachineOperand &Src = MI.getOperand(1);
395 
396         if (Src.isImm() &&
397             TargetRegisterInfo::isPhysicalRegister(Dst.getReg())) {
398           int32_t ReverseImm;
399           if (isKImmOperand(TII, Src))
400             MI.setDesc(TII->get(AMDGPU::S_MOVK_I32));
401           else if (isReverseInlineImm(TII, Src, ReverseImm)) {
402             MI.setDesc(TII->get(AMDGPU::S_BREV_B32));
403             Src.setImm(ReverseImm);
404           }
405         }
406 
407         continue;
408       }
409 
410       if (!TII->hasVALU32BitEncoding(MI.getOpcode()))
411         continue;
412 
413       if (!canShrink(MI, TII, TRI, MRI)) {
414         // Try commuting the instruction and see if that enables us to shrink
415         // it.
416         if (!MI.isCommutable() || !TII->commuteInstruction(MI) ||
417             !canShrink(MI, TII, TRI, MRI))
418           continue;
419       }
420 
421       // getVOPe32 could be -1 here if we started with an instruction that had
422       // a 32-bit encoding and then commuted it to an instruction that did not.
423       if (!TII->hasVALU32BitEncoding(MI.getOpcode()))
424         continue;
425 
426       int Op32 = AMDGPU::getVOPe32(MI.getOpcode());
427 
428       if (TII->isVOPC(Op32)) {
429         unsigned DstReg = MI.getOperand(0).getReg();
430         if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
431           // VOPC instructions can only write to the VCC register. We can't
432           // force them to use VCC here, because this is only one register and
433           // cannot deal with sequences which would require multiple copies of
434           // VCC, e.g. S_AND_B64 (vcc = V_CMP_...), (vcc = V_CMP_...)
435           //
436           // So, instead of forcing the instruction to write to VCC, we provide
437           // a hint to the register allocator to use VCC and then we we will run
438           // this pass again after RA and shrink it if it outputs to VCC.
439           MRI.setRegAllocationHint(MI.getOperand(0).getReg(), 0, AMDGPU::VCC);
440           continue;
441         }
442         if (DstReg != AMDGPU::VCC)
443           continue;
444       }
445 
446       if (Op32 == AMDGPU::V_CNDMASK_B32_e32) {
447         // We shrink V_CNDMASK_B32_e64 using regalloc hints like we do for VOPC
448         // instructions.
449         const MachineOperand *Src2 =
450             TII->getNamedOperand(MI, AMDGPU::OpName::src2);
451         if (!Src2->isReg())
452           continue;
453         unsigned SReg = Src2->getReg();
454         if (TargetRegisterInfo::isVirtualRegister(SReg)) {
455           MRI.setRegAllocationHint(SReg, 0, AMDGPU::VCC);
456           continue;
457         }
458         if (SReg != AMDGPU::VCC)
459           continue;
460       }
461 
462       // Check for the bool flag output for instructions like V_ADD_I32_e64.
463       const MachineOperand *SDst = TII->getNamedOperand(MI,
464                                                         AMDGPU::OpName::sdst);
465 
466       // Check the carry-in operand for v_addc_u32_e64.
467       const MachineOperand *Src2 = TII->getNamedOperand(MI,
468                                                         AMDGPU::OpName::src2);
469 
470       if (SDst) {
471         if (SDst->getReg() != AMDGPU::VCC) {
472           if (TargetRegisterInfo::isVirtualRegister(SDst->getReg()))
473             MRI.setRegAllocationHint(SDst->getReg(), 0, AMDGPU::VCC);
474           continue;
475         }
476 
477         // All of the instructions with carry outs also have an SGPR input in
478         // src2.
479         if (Src2 && Src2->getReg() != AMDGPU::VCC) {
480           if (TargetRegisterInfo::isVirtualRegister(Src2->getReg()))
481             MRI.setRegAllocationHint(Src2->getReg(), 0, AMDGPU::VCC);
482 
483           continue;
484         }
485       }
486 
487       // We can shrink this instruction
488       DEBUG(dbgs() << "Shrinking " << MI);
489 
490       MachineInstrBuilder Inst32 =
491           BuildMI(MBB, I, MI.getDebugLoc(), TII->get(Op32));
492 
493       // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
494       // For VOPC instructions, this is replaced by an implicit def of vcc.
495       int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
496       if (Op32DstIdx != -1) {
497         // dst
498         Inst32.add(MI.getOperand(0));
499       } else {
500         assert(MI.getOperand(0).getReg() == AMDGPU::VCC &&
501                "Unexpected case");
502       }
503 
504 
505       Inst32.add(*TII->getNamedOperand(MI, AMDGPU::OpName::src0));
506 
507       const MachineOperand *Src1 =
508           TII->getNamedOperand(MI, AMDGPU::OpName::src1);
509       if (Src1)
510         Inst32.add(*Src1);
511 
512       if (Src2) {
513         int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
514         if (Op32Src2Idx != -1) {
515           Inst32.add(*Src2);
516         } else {
517           // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
518           // replaced with an implicit read of vcc. This was already added
519           // during the initial BuildMI, so find it to preserve the flags.
520           copyFlagsToImplicitVCC(*Inst32, *Src2);
521         }
522       }
523 
524       ++NumInstructionsShrunk;
525 
526       // Copy extra operands not present in the instruction definition.
527       copyExtraImplicitOps(*Inst32, MF, MI);
528 
529       MI.eraseFromParent();
530       foldImmediates(*Inst32, TII, MRI);
531 
532       DEBUG(dbgs() << "e32 MI = " << *Inst32 << '\n');
533 
534 
535     }
536   }
537   return false;
538 }
539