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