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   const char *getPassName() const override {
49     return "SI Shrink Instructions";
50   }
51 
52   void getAnalysisUsage(AnalysisUsage &AU) const override {
53     AU.setPreservesCFG();
54     MachineFunctionPass::getAnalysisUsage(AU);
55   }
56 };
57 
58 } // End anonymous namespace.
59 
60 INITIALIZE_PASS(SIShrinkInstructions, DEBUG_TYPE,
61                 "SI Shrink Instructions", false, false)
62 
63 char SIShrinkInstructions::ID = 0;
64 
65 FunctionPass *llvm::createSIShrinkInstructionsPass() {
66   return new SIShrinkInstructions();
67 }
68 
69 static bool isVGPR(const MachineOperand *MO, const SIRegisterInfo &TRI,
70                    const MachineRegisterInfo &MRI) {
71   if (!MO->isReg())
72     return false;
73 
74   if (TargetRegisterInfo::isVirtualRegister(MO->getReg()))
75     return TRI.hasVGPRs(MRI.getRegClass(MO->getReg()));
76 
77   return TRI.hasVGPRs(TRI.getPhysRegClass(MO->getReg()));
78 }
79 
80 static bool canShrink(MachineInstr &MI, const SIInstrInfo *TII,
81                       const SIRegisterInfo &TRI,
82                       const MachineRegisterInfo &MRI) {
83 
84   const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
85   // Can't shrink instruction with three operands.
86   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
87   // a special case for it.  It can only be shrunk if the third operand
88   // is vcc.  We should handle this the same way we handle vopc, by addding
89   // a register allocation hint pre-regalloc and then do the shrining
90   // post-regalloc.
91   if (Src2) {
92     switch (MI.getOpcode()) {
93       default: return false;
94 
95       case AMDGPU::V_MAC_F32_e64:
96         if (!isVGPR(Src2, TRI, MRI) ||
97             TII->hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
98           return false;
99         break;
100 
101       case AMDGPU::V_CNDMASK_B32_e64:
102         break;
103     }
104   }
105 
106   const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
107   const MachineOperand *Src1Mod =
108       TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
109 
110   if (Src1 && (!isVGPR(Src1, TRI, MRI) || (Src1Mod && Src1Mod->getImm() != 0)))
111     return false;
112 
113   // We don't need to check src0, all input types are legal, so just make sure
114   // src0 isn't using any modifiers.
115   if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
116     return false;
117 
118   // Check output modifiers
119   if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
120     return false;
121 
122   return !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp);
123 }
124 
125 /// \brief This function checks \p MI for operands defined by a move immediate
126 /// instruction and then folds the literal constant into the instruction if it
127 /// can.  This function assumes that \p MI is a VOP1, VOP2, or VOPC instruction
128 /// and will only fold literal constants if we are still in SSA.
129 static void foldImmediates(MachineInstr &MI, const SIInstrInfo *TII,
130                            MachineRegisterInfo &MRI, bool TryToCommute = true) {
131 
132   if (!MRI.isSSA())
133     return;
134 
135   assert(TII->isVOP1(MI) || TII->isVOP2(MI) || TII->isVOPC(MI));
136 
137   int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
138   MachineOperand &Src0 = MI.getOperand(Src0Idx);
139 
140   // Only one literal constant is allowed per instruction, so if src0 is a
141   // literal constant then we can't do any folding.
142   if (Src0.isImm() &&
143       TII->isLiteralConstant(Src0, TII->getOpSize(MI, Src0Idx)))
144     return;
145 
146   // Try to fold Src0
147   if (Src0.isReg() && MRI.hasOneUse(Src0.getReg())) {
148     unsigned Reg = Src0.getReg();
149     MachineInstr *Def = MRI.getUniqueVRegDef(Reg);
150     if (Def && Def->isMoveImmediate()) {
151       MachineOperand &MovSrc = Def->getOperand(1);
152       bool ConstantFolded = false;
153 
154       if (MovSrc.isImm() && (isInt<32>(MovSrc.getImm()) ||
155                              isUInt<32>(MovSrc.getImm()))) {
156         Src0.ChangeToImmediate(MovSrc.getImm());
157         ConstantFolded = true;
158       }
159       if (ConstantFolded) {
160         if (MRI.use_empty(Reg))
161           Def->eraseFromParent();
162         ++NumLiteralConstantsFolded;
163         return;
164       }
165     }
166   }
167 
168   // We have failed to fold src0, so commute the instruction and try again.
169   if (TryToCommute && MI.isCommutable() && TII->commuteInstruction(MI))
170     foldImmediates(MI, TII, MRI, false);
171 
172 }
173 
174 // Copy MachineOperand with all flags except setting it as implicit.
175 static void copyFlagsToImplicitVCC(MachineInstr &MI,
176                                    const MachineOperand &Orig) {
177 
178   for (MachineOperand &Use : MI.implicit_operands()) {
179     if (Use.getReg() == AMDGPU::VCC) {
180       Use.setIsUndef(Orig.isUndef());
181       Use.setIsKill(Orig.isKill());
182       return;
183     }
184   }
185 }
186 
187 static bool isKImmOperand(const SIInstrInfo *TII, const MachineOperand &Src) {
188   return isInt<16>(Src.getImm()) && !TII->isInlineConstant(Src, 4);
189 }
190 
191 /// Copy implicit register operands from specified instruction to this
192 /// instruction that are not part of the instruction definition.
193 static void copyExtraImplicitOps(MachineInstr &NewMI, MachineFunction &MF,
194                                  const MachineInstr &MI) {
195   for (unsigned i = MI.getDesc().getNumOperands() +
196          MI.getDesc().getNumImplicitUses() +
197          MI.getDesc().getNumImplicitDefs(), e = MI.getNumOperands();
198        i != e; ++i) {
199     const MachineOperand &MO = MI.getOperand(i);
200     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
201       NewMI.addOperand(MF, MO);
202   }
203 }
204 
205 bool SIShrinkInstructions::runOnMachineFunction(MachineFunction &MF) {
206   if (skipFunction(*MF.getFunction()))
207     return false;
208 
209   MachineRegisterInfo &MRI = MF.getRegInfo();
210   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
211   const SIInstrInfo *TII = ST.getInstrInfo();
212   const SIRegisterInfo &TRI = TII->getRegisterInfo();
213 
214   std::vector<unsigned> I1Defs;
215 
216   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
217                                                   BI != BE; ++BI) {
218 
219     MachineBasicBlock &MBB = *BI;
220     MachineBasicBlock::iterator I, Next;
221     for (I = MBB.begin(); I != MBB.end(); I = Next) {
222       Next = std::next(I);
223       MachineInstr &MI = *I;
224 
225       if (MI.getOpcode() == AMDGPU::V_MOV_B32_e32) {
226         // If this has a literal constant source that is the same as the
227         // reversed bits of an inline immediate, replace with a bitreverse of
228         // that constant. This saves 4 bytes in the common case of materializing
229         // sign bits.
230 
231         // Test if we are after regalloc. We only want to do this after any
232         // optimizations happen because this will confuse them.
233         // XXX - not exactly a check for post-regalloc run.
234         MachineOperand &Src = MI.getOperand(1);
235         if (Src.isImm() &&
236             TargetRegisterInfo::isPhysicalRegister(MI.getOperand(0).getReg())) {
237           int64_t Imm = Src.getImm();
238           if (isInt<32>(Imm) && !TII->isInlineConstant(Src, 4)) {
239             int32_t ReverseImm = reverseBits<int32_t>(static_cast<int32_t>(Imm));
240             if (ReverseImm >= -16 && ReverseImm <= 64) {
241               MI.setDesc(TII->get(AMDGPU::V_BFREV_B32_e32));
242               Src.setImm(ReverseImm);
243               continue;
244             }
245           }
246         }
247       }
248 
249       // Combine adjacent s_nops to use the immediate operand encoding how long
250       // to wait.
251       //
252       // s_nop N
253       // s_nop M
254       //  =>
255       // s_nop (N + M)
256       if (MI.getOpcode() == AMDGPU::S_NOP &&
257           Next != MBB.end() &&
258           (*Next).getOpcode() == AMDGPU::S_NOP) {
259 
260         MachineInstr &NextMI = *Next;
261         // The instruction encodes the amount to wait with an offset of 1,
262         // i.e. 0 is wait 1 cycle. Convert both to cycles and then convert back
263         // after adding.
264         uint8_t Nop0 = MI.getOperand(0).getImm() + 1;
265         uint8_t Nop1 = NextMI.getOperand(0).getImm() + 1;
266 
267         // Make sure we don't overflow the bounds.
268         if (Nop0 + Nop1 <= 8) {
269           NextMI.getOperand(0).setImm(Nop0 + Nop1 - 1);
270           MI.eraseFromParent();
271         }
272 
273         continue;
274       }
275 
276       // FIXME: We also need to consider movs of constant operands since
277       // immediate operands are not folded if they have more than one use, and
278       // the operand folding pass is unaware if the immediate will be free since
279       // it won't know if the src == dest constraint will end up being
280       // satisfied.
281       if (MI.getOpcode() == AMDGPU::S_ADD_I32 ||
282           MI.getOpcode() == AMDGPU::S_MUL_I32) {
283         const MachineOperand *Dest = &MI.getOperand(0);
284         MachineOperand *Src0 = &MI.getOperand(1);
285         MachineOperand *Src1 = &MI.getOperand(2);
286 
287         if (!Src0->isReg() && Src1->isReg()) {
288           if (TII->commuteInstruction(MI, false, 1, 2))
289             std::swap(Src0, Src1);
290         }
291 
292         // FIXME: This could work better if hints worked with subregisters. If
293         // we have a vector add of a constant, we usually don't get the correct
294         // allocation due to the subregister usage.
295         if (TargetRegisterInfo::isVirtualRegister(Dest->getReg()) &&
296             Src0->isReg()) {
297           MRI.setRegAllocationHint(Dest->getReg(), 0, Src0->getReg());
298           MRI.setRegAllocationHint(Src0->getReg(), 0, Dest->getReg());
299           continue;
300         }
301 
302         if (Src0->isReg() && Src0->getReg() == Dest->getReg()) {
303           if (Src1->isImm() && isKImmOperand(TII, *Src1)) {
304             unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_I32) ?
305               AMDGPU::S_ADDK_I32 : AMDGPU::S_MULK_I32;
306 
307             MI.setDesc(TII->get(Opc));
308             MI.tieOperands(0, 1);
309           }
310         }
311       }
312 
313       // Try to use S_MOVK_I32, which will save 4 bytes for small immediates.
314       if (MI.getOpcode() == AMDGPU::S_MOV_B32) {
315         const MachineOperand &Src = MI.getOperand(1);
316 
317         if (Src.isImm() && isKImmOperand(TII, Src))
318           MI.setDesc(TII->get(AMDGPU::S_MOVK_I32));
319 
320         continue;
321       }
322 
323       if (!TII->hasVALU32BitEncoding(MI.getOpcode()))
324         continue;
325 
326       if (!canShrink(MI, TII, TRI, MRI)) {
327         // Try commuting the instruction and see if that enables us to shrink
328         // it.
329         if (!MI.isCommutable() || !TII->commuteInstruction(MI) ||
330             !canShrink(MI, TII, TRI, MRI))
331           continue;
332       }
333 
334       // getVOPe32 could be -1 here if we started with an instruction that had
335       // a 32-bit encoding and then commuted it to an instruction that did not.
336       if (!TII->hasVALU32BitEncoding(MI.getOpcode()))
337         continue;
338 
339       int Op32 = AMDGPU::getVOPe32(MI.getOpcode());
340 
341       if (TII->isVOPC(Op32)) {
342         unsigned DstReg = MI.getOperand(0).getReg();
343         if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
344           // VOPC instructions can only write to the VCC register. We can't
345           // force them to use VCC here, because this is only one register and
346           // cannot deal with sequences which would require multiple copies of
347           // VCC, e.g. S_AND_B64 (vcc = V_CMP_...), (vcc = V_CMP_...)
348           //
349           // So, instead of forcing the instruction to write to VCC, we provide
350           // a hint to the register allocator to use VCC and then we we will run
351           // this pass again after RA and shrink it if it outputs to VCC.
352           MRI.setRegAllocationHint(MI.getOperand(0).getReg(), 0, AMDGPU::VCC);
353           continue;
354         }
355         if (DstReg != AMDGPU::VCC)
356           continue;
357       }
358 
359       if (Op32 == AMDGPU::V_CNDMASK_B32_e32) {
360         // We shrink V_CNDMASK_B32_e64 using regalloc hints like we do for VOPC
361         // instructions.
362         const MachineOperand *Src2 =
363             TII->getNamedOperand(MI, AMDGPU::OpName::src2);
364         if (!Src2->isReg())
365           continue;
366         unsigned SReg = Src2->getReg();
367         if (TargetRegisterInfo::isVirtualRegister(SReg)) {
368           MRI.setRegAllocationHint(SReg, 0, AMDGPU::VCC);
369           continue;
370         }
371         if (SReg != AMDGPU::VCC)
372           continue;
373       }
374 
375       // We can shrink this instruction
376       DEBUG(dbgs() << "Shrinking " << MI);
377 
378       MachineInstrBuilder Inst32 =
379           BuildMI(MBB, I, MI.getDebugLoc(), TII->get(Op32));
380 
381       // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
382       // For VOPC instructions, this is replaced by an implicit def of vcc.
383       int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
384       if (Op32DstIdx != -1) {
385         // dst
386         Inst32.addOperand(MI.getOperand(0));
387       } else {
388         assert(MI.getOperand(0).getReg() == AMDGPU::VCC &&
389                "Unexpected case");
390       }
391 
392 
393       Inst32.addOperand(*TII->getNamedOperand(MI, AMDGPU::OpName::src0));
394 
395       const MachineOperand *Src1 =
396           TII->getNamedOperand(MI, AMDGPU::OpName::src1);
397       if (Src1)
398         Inst32.addOperand(*Src1);
399 
400       const MachineOperand *Src2 =
401         TII->getNamedOperand(MI, AMDGPU::OpName::src2);
402       if (Src2) {
403         int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
404         if (Op32Src2Idx != -1) {
405           Inst32.addOperand(*Src2);
406         } else {
407           // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
408           // replaced with an implicit read of vcc. This was already added
409           // during the initial BuildMI, so find it to preserve the flags.
410           copyFlagsToImplicitVCC(*Inst32, *Src2);
411         }
412       }
413 
414       ++NumInstructionsShrunk;
415 
416       // Copy extra operands not present in the instruction definition.
417       copyExtraImplicitOps(*Inst32, MF, MI);
418 
419       MI.eraseFromParent();
420       foldImmediates(*Inst32, TII, MRI);
421 
422       DEBUG(dbgs() << "e32 MI = " << *Inst32 << '\n');
423 
424 
425     }
426   }
427   return false;
428 }
429