1 //===- X86VZeroUpper.cpp - AVX vzeroupper instruction inserter ------------===//
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 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the pass which inserts x86 AVX vzeroupper instructions
11 // before calls to SSE encoded functions. This avoids transition latency
12 // penalty when transferring control between AVX encoded instructions and old
13 // SSE encoding mode.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "X86.h"
18 #include "X86InstrInfo.h"
19 #include "X86Subtarget.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DebugLoc.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include <cassert>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "x86-vzeroupper"
42 
43 STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
44 
45 namespace {
46 
47   class VZeroUpperInserter : public MachineFunctionPass {
48   public:
49     VZeroUpperInserter() : MachineFunctionPass(ID) {}
50 
51     bool runOnMachineFunction(MachineFunction &MF) override;
52 
53     MachineFunctionProperties getRequiredProperties() const override {
54       return MachineFunctionProperties().set(
55           MachineFunctionProperties::Property::NoVRegs);
56     }
57 
58     StringRef getPassName() const override { return "X86 vzeroupper inserter"; }
59 
60   private:
61     void processBasicBlock(MachineBasicBlock &MBB);
62     void insertVZeroUpper(MachineBasicBlock::iterator I,
63                           MachineBasicBlock &MBB);
64     void addDirtySuccessor(MachineBasicBlock &MBB);
65 
66     using BlockExitState = enum { PASS_THROUGH, EXITS_CLEAN, EXITS_DIRTY };
67 
68     static const char* getBlockExitStateName(BlockExitState ST);
69 
70     // Core algorithm state:
71     // BlockState - Each block is either:
72     //   - PASS_THROUGH: There are neither YMM/ZMM dirtying instructions nor
73     //                   vzeroupper instructions in this block.
74     //   - EXITS_CLEAN: There is (or will be) a vzeroupper instruction in this
75     //                  block that will ensure that YMM/ZMM is clean on exit.
76     //   - EXITS_DIRTY: An instruction in the block dirties YMM/ZMM and no
77     //                  subsequent vzeroupper in the block clears it.
78     //
79     // AddedToDirtySuccessors - This flag is raised when a block is added to the
80     //                          DirtySuccessors list to ensure that it's not
81     //                          added multiple times.
82     //
83     // FirstUnguardedCall - Records the location of the first unguarded call in
84     //                      each basic block that may need to be guarded by a
85     //                      vzeroupper. We won't know whether it actually needs
86     //                      to be guarded until we discover a predecessor that
87     //                      is DIRTY_OUT.
88     struct BlockState {
89       BlockExitState ExitState = PASS_THROUGH;
90       bool AddedToDirtySuccessors = false;
91       MachineBasicBlock::iterator FirstUnguardedCall;
92 
93       BlockState() = default;
94     };
95 
96     using BlockStateMap = SmallVector<BlockState, 8>;
97     using DirtySuccessorsWorkList = SmallVector<MachineBasicBlock *, 8>;
98 
99     BlockStateMap BlockStates;
100     DirtySuccessorsWorkList DirtySuccessors;
101     bool EverMadeChange;
102     bool IsX86INTR;
103     const TargetInstrInfo *TII;
104 
105     static char ID;
106   };
107 
108 } // end anonymous namespace
109 
110 char VZeroUpperInserter::ID = 0;
111 
112 FunctionPass *llvm::createX86IssueVZeroUpperPass() {
113   return new VZeroUpperInserter();
114 }
115 
116 #ifndef NDEBUG
117 const char* VZeroUpperInserter::getBlockExitStateName(BlockExitState ST) {
118   switch (ST) {
119     case PASS_THROUGH: return "Pass-through";
120     case EXITS_DIRTY: return "Exits-dirty";
121     case EXITS_CLEAN: return "Exits-clean";
122   }
123   llvm_unreachable("Invalid block exit state.");
124 }
125 #endif
126 
127 /// VZEROUPPER cleans state that is related to Y/ZMM0-15 only.
128 /// Thus, there is no need to check for Y/ZMM16 and above.
129 static bool isYmmOrZmmReg(unsigned Reg) {
130   return (Reg >= X86::YMM0 && Reg <= X86::YMM15) ||
131          (Reg >= X86::ZMM0 && Reg <= X86::ZMM15);
132 }
133 
134 static bool checkFnHasLiveInYmmOrZmm(MachineRegisterInfo &MRI) {
135   for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
136        E = MRI.livein_end(); I != E; ++I)
137     if (isYmmOrZmmReg(I->first))
138       return true;
139 
140   return false;
141 }
142 
143 static bool clobbersAllYmmAndZmmRegs(const MachineOperand &MO) {
144   for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
145     if (!MO.clobbersPhysReg(reg))
146       return false;
147   }
148   for (unsigned reg = X86::ZMM0; reg <= X86::ZMM15; ++reg) {
149     if (!MO.clobbersPhysReg(reg))
150       return false;
151   }
152   return true;
153 }
154 
155 static bool hasYmmOrZmmReg(MachineInstr &MI) {
156   for (const MachineOperand &MO : MI.operands()) {
157     if (MI.isCall() && MO.isRegMask() && !clobbersAllYmmAndZmmRegs(MO))
158       return true;
159     if (!MO.isReg())
160       continue;
161     if (MO.isDebug())
162       continue;
163     if (isYmmOrZmmReg(MO.getReg()))
164       return true;
165   }
166   return false;
167 }
168 
169 /// Check if given call instruction has a RegMask operand.
170 static bool callHasRegMask(MachineInstr &MI) {
171   assert(MI.isCall() && "Can only be called on call instructions.");
172   for (const MachineOperand &MO : MI.operands()) {
173     if (MO.isRegMask())
174       return true;
175   }
176   return false;
177 }
178 
179 /// Insert a vzeroupper instruction before I.
180 void VZeroUpperInserter::insertVZeroUpper(MachineBasicBlock::iterator I,
181                                           MachineBasicBlock &MBB) {
182   DebugLoc dl = I->getDebugLoc();
183   BuildMI(MBB, I, dl, TII->get(X86::VZEROUPPER));
184   ++NumVZU;
185   EverMadeChange = true;
186 }
187 
188 /// Add MBB to the DirtySuccessors list if it hasn't already been added.
189 void VZeroUpperInserter::addDirtySuccessor(MachineBasicBlock &MBB) {
190   if (!BlockStates[MBB.getNumber()].AddedToDirtySuccessors) {
191     DirtySuccessors.push_back(&MBB);
192     BlockStates[MBB.getNumber()].AddedToDirtySuccessors = true;
193   }
194 }
195 
196 /// Loop over all of the instructions in the basic block, inserting vzeroupper
197 /// instructions before function calls.
198 void VZeroUpperInserter::processBasicBlock(MachineBasicBlock &MBB) {
199   // Start by assuming that the block is PASS_THROUGH which implies no unguarded
200   // calls.
201   BlockExitState CurState = PASS_THROUGH;
202   BlockStates[MBB.getNumber()].FirstUnguardedCall = MBB.end();
203 
204   for (MachineInstr &MI : MBB) {
205     bool IsCall = MI.isCall();
206     bool IsReturn = MI.isReturn();
207     bool IsControlFlow = IsCall || IsReturn;
208 
209     // No need for vzeroupper before iret in interrupt handler function,
210     // epilogue will restore YMM/ZMM registers if needed.
211     if (IsX86INTR && IsReturn)
212       continue;
213 
214     // An existing VZERO* instruction resets the state.
215     if (MI.getOpcode() == X86::VZEROALL || MI.getOpcode() == X86::VZEROUPPER) {
216       CurState = EXITS_CLEAN;
217       continue;
218     }
219 
220     // Shortcut: don't need to check regular instructions in dirty state.
221     if (!IsControlFlow && CurState == EXITS_DIRTY)
222       continue;
223 
224     if (hasYmmOrZmmReg(MI)) {
225       // We found a ymm/zmm-using instruction; this could be an AVX/AVX512
226       // instruction, or it could be control flow.
227       CurState = EXITS_DIRTY;
228       continue;
229     }
230 
231     // Check for control-flow out of the current function (which might
232     // indirectly execute SSE instructions).
233     if (!IsControlFlow)
234       continue;
235 
236     // If the call has no RegMask, skip it as well. It usually happens on
237     // helper function calls (such as '_chkstk', '_ftol2') where standard
238     // calling convention is not used (RegMask is not used to mark register
239     // clobbered and register usage (def/imp-def/use) is well-defined and
240     // explicitly specified.
241     if (IsCall && !callHasRegMask(MI))
242       continue;
243 
244     // The VZEROUPPER instruction resets the upper 128 bits of YMM0-YMM15
245     // registers. In addition, the processor changes back to Clean state, after
246     // which execution of SSE instructions or AVX instructions has no transition
247     // penalty. Add the VZEROUPPER instruction before any function call/return
248     // that might execute SSE code.
249     // FIXME: In some cases, we may want to move the VZEROUPPER into a
250     // predecessor block.
251     if (CurState == EXITS_DIRTY) {
252       // After the inserted VZEROUPPER the state becomes clean again, but
253       // other YMM/ZMM may appear before other subsequent calls or even before
254       // the end of the BB.
255       insertVZeroUpper(MI, MBB);
256       CurState = EXITS_CLEAN;
257     } else if (CurState == PASS_THROUGH) {
258       // If this block is currently in pass-through state and we encounter a
259       // call then whether we need a vzeroupper or not depends on whether this
260       // block has successors that exit dirty. Record the location of the call,
261       // and set the state to EXITS_CLEAN, but do not insert the vzeroupper yet.
262       // It will be inserted later if necessary.
263       BlockStates[MBB.getNumber()].FirstUnguardedCall = MI;
264       CurState = EXITS_CLEAN;
265     }
266   }
267 
268   DEBUG(dbgs() << "MBB #" << MBB.getNumber() << " exit state: "
269                << getBlockExitStateName(CurState) << '\n');
270 
271   if (CurState == EXITS_DIRTY)
272     for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
273                                           SE = MBB.succ_end();
274          SI != SE; ++SI)
275       addDirtySuccessor(**SI);
276 
277   BlockStates[MBB.getNumber()].ExitState = CurState;
278 }
279 
280 /// Loop over all of the basic blocks, inserting vzeroupper instructions before
281 /// function calls.
282 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
283   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
284   if (!ST.hasAVX() || ST.hasFastPartialYMMorZMMWrite())
285     return false;
286   TII = ST.getInstrInfo();
287   MachineRegisterInfo &MRI = MF.getRegInfo();
288   EverMadeChange = false;
289   IsX86INTR = MF.getFunction()->getCallingConv() == CallingConv::X86_INTR;
290 
291   bool FnHasLiveInYmmOrZmm = checkFnHasLiveInYmmOrZmm(MRI);
292 
293   // Fast check: if the function doesn't use any ymm/zmm registers, we don't
294   // need to insert any VZEROUPPER instructions.  This is constant-time, so it
295   // is cheap in the common case of no ymm/zmm use.
296   bool YmmOrZmmUsed = FnHasLiveInYmmOrZmm;
297   const TargetRegisterClass *RCs[2] = {&X86::VR256RegClass, &X86::VR512RegClass};
298   for (auto *RC : RCs) {
299     if (!YmmOrZmmUsed) {
300       for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end(); i != e;
301            i++) {
302         if (!MRI.reg_nodbg_empty(*i)) {
303           YmmOrZmmUsed = true;
304           break;
305         }
306       }
307     }
308   }
309   if (!YmmOrZmmUsed) {
310     return false;
311   }
312 
313   assert(BlockStates.empty() && DirtySuccessors.empty() &&
314          "X86VZeroUpper state should be clear");
315   BlockStates.resize(MF.getNumBlockIDs());
316 
317   // Process all blocks. This will compute block exit states, record the first
318   // unguarded call in each block, and add successors of dirty blocks to the
319   // DirtySuccessors list.
320   for (MachineBasicBlock &MBB : MF)
321     processBasicBlock(MBB);
322 
323   // If any YMM/ZMM regs are live-in to this function, add the entry block to
324   // the DirtySuccessors list
325   if (FnHasLiveInYmmOrZmm)
326     addDirtySuccessor(MF.front());
327 
328   // Re-visit all blocks that are successors of EXITS_DIRTY blocks. Add
329   // vzeroupper instructions to unguarded calls, and propagate EXITS_DIRTY
330   // through PASS_THROUGH blocks.
331   while (!DirtySuccessors.empty()) {
332     MachineBasicBlock &MBB = *DirtySuccessors.back();
333     DirtySuccessors.pop_back();
334     BlockState &BBState = BlockStates[MBB.getNumber()];
335 
336     // MBB is a successor of a dirty block, so its first call needs to be
337     // guarded.
338     if (BBState.FirstUnguardedCall != MBB.end())
339       insertVZeroUpper(BBState.FirstUnguardedCall, MBB);
340 
341     // If this successor was a pass-through block, then it is now dirty. Its
342     // successors need to be added to the worklist (if they haven't been
343     // already).
344     if (BBState.ExitState == PASS_THROUGH) {
345       DEBUG(dbgs() << "MBB #" << MBB.getNumber()
346                    << " was Pass-through, is now Dirty-out.\n");
347       for (MachineBasicBlock *Succ : MBB.successors())
348         addDirtySuccessor(*Succ);
349     }
350   }
351 
352   BlockStates.clear();
353   return EverMadeChange;
354 }
355