blob: 6925b272b4a5bae8f80c7b3174a24bd770b22a25 [file] [log] [blame]
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +00001//===-- 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
Andrea Di Biagio4f8bdcb2015-02-07 13:56:20 +000012// penalty when transferring control between AVX encoded instructions and old
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000013// SSE encoding mode.
14//
15//===----------------------------------------------------------------------===//
16
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000017#include "X86.h"
18#include "X86InstrInfo.h"
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +000019#include "X86Subtarget.h"
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000020#include "llvm/ADT/Statistic.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Eli Friedman8f249602011-11-04 23:46:11 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000024#include "llvm/CodeGen/Passes.h"
Eli Friedman8f249602011-11-04 23:46:11 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/raw_ostream.h"
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000027#include "llvm/Target/TargetInstrInfo.h"
28using namespace llvm;
29
Chandler Carruth84e68b22014-04-22 02:41:26 +000030#define DEBUG_TYPE "x86-vzeroupper"
31
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000032STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
33
34namespace {
Lang Hames7c8189c2014-03-17 01:22:54 +000035
36 class VZeroUpperInserter : public MachineFunctionPass {
37 public:
38
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000039 VZeroUpperInserter() : MachineFunctionPass(ID) {}
Craig Topper2d9361e2014-03-09 07:44:38 +000040 bool runOnMachineFunction(MachineFunction &MF) override;
Craig Topper2d9361e2014-03-09 07:44:38 +000041 const char *getPassName() const override {return "X86 vzeroupper inserter";}
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000042
43 private:
Eli Friedman8f249602011-11-04 23:46:11 +000044
Lang Hames7c8189c2014-03-17 01:22:54 +000045 void processBasicBlock(MachineBasicBlock &MBB);
46 void insertVZeroUpper(MachineBasicBlock::iterator I,
47 MachineBasicBlock &MBB);
48 void addDirtySuccessor(MachineBasicBlock &MBB);
Eli Friedman8f249602011-11-04 23:46:11 +000049
Lang Hames7c8189c2014-03-17 01:22:54 +000050 typedef enum { PASS_THROUGH, EXITS_CLEAN, EXITS_DIRTY } BlockExitState;
51 static const char* getBlockExitStateName(BlockExitState ST);
Eli Friedman8f249602011-11-04 23:46:11 +000052
Lang Hames7c8189c2014-03-17 01:22:54 +000053 // Core algorithm state:
54 // BlockState - Each block is either:
55 // - PASS_THROUGH: There are neither YMM dirtying instructions nor
56 // vzeroupper instructions in this block.
57 // - EXITS_CLEAN: There is (or will be) a vzeroupper instruction in this
58 // block that will ensure that YMM is clean on exit.
59 // - EXITS_DIRTY: An instruction in the block dirties YMM and no
60 // subsequent vzeroupper in the block clears it.
Eli Friedman8f249602011-11-04 23:46:11 +000061 //
Lang Hames7c8189c2014-03-17 01:22:54 +000062 // AddedToDirtySuccessors - This flag is raised when a block is added to the
63 // DirtySuccessors list to ensure that it's not
64 // added multiple times.
Eli Friedman8f249602011-11-04 23:46:11 +000065 //
Lang Hames7c8189c2014-03-17 01:22:54 +000066 // FirstUnguardedCall - Records the location of the first unguarded call in
67 // each basic block that may need to be guarded by a
68 // vzeroupper. We won't know whether it actually needs
69 // to be guarded until we discover a predecessor that
70 // is DIRTY_OUT.
71 struct BlockState {
72 BlockState() : ExitState(PASS_THROUGH), AddedToDirtySuccessors(false) {}
73 BlockExitState ExitState;
74 bool AddedToDirtySuccessors;
75 MachineBasicBlock::iterator FirstUnguardedCall;
Eli Friedman8f249602011-11-04 23:46:11 +000076 };
Lang Hames7c8189c2014-03-17 01:22:54 +000077 typedef SmallVector<BlockState, 8> BlockStateMap;
78 typedef SmallVector<MachineBasicBlock*, 8> DirtySuccessorsWorkList;
Eli Friedman8f249602011-11-04 23:46:11 +000079
Lang Hames7c8189c2014-03-17 01:22:54 +000080 BlockStateMap BlockStates;
81 DirtySuccessorsWorkList DirtySuccessors;
82 bool EverMadeChange;
83 const TargetInstrInfo *TII;
Eli Friedman8f249602011-11-04 23:46:11 +000084
Lang Hames7c8189c2014-03-17 01:22:54 +000085 static char ID;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000086 };
Lang Hames7c8189c2014-03-17 01:22:54 +000087
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000088 char VZeroUpperInserter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +000089}
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000090
91FunctionPass *llvm::createX86IssueVZeroUpperPass() {
92 return new VZeroUpperInserter();
93}
94
Lang Hames7c8189c2014-03-17 01:22:54 +000095const char* VZeroUpperInserter::getBlockExitStateName(BlockExitState ST) {
96 switch (ST) {
97 case PASS_THROUGH: return "Pass-through";
98 case EXITS_DIRTY: return "Exits-dirty";
99 case EXITS_CLEAN: return "Exits-clean";
100 }
101 llvm_unreachable("Invalid block exit state.");
102}
103
Eli Friedman8f249602011-11-04 23:46:11 +0000104static bool isYmmReg(unsigned Reg) {
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000105 return (Reg >= X86::YMM0 && Reg <= X86::YMM15);
Eli Friedman8f249602011-11-04 23:46:11 +0000106}
107
108static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
109 for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
110 E = MRI.livein_end(); I != E; ++I)
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000111 if (isYmmReg(I->first))
Eli Friedman8f249602011-11-04 23:46:11 +0000112 return true;
113
114 return false;
115}
116
Elena Demikhovsky9e0df7c2013-02-13 08:02:04 +0000117static bool clobbersAllYmmRegs(const MachineOperand &MO) {
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000118 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
Elena Demikhovsky9e0df7c2013-02-13 08:02:04 +0000119 if (!MO.clobbersPhysReg(reg))
120 return false;
121 }
122 return true;
123}
124
Eli Friedman8f249602011-11-04 23:46:11 +0000125static bool hasYmmReg(MachineInstr *MI) {
Craig Topper056dfcc2012-08-22 05:59:59 +0000126 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Eli Friedman8f249602011-11-04 23:46:11 +0000127 const MachineOperand &MO = MI->getOperand(i);
Elena Demikhovsky9e0df7c2013-02-13 08:02:04 +0000128 if (MI->isCall() && MO.isRegMask() && !clobbersAllYmmRegs(MO))
129 return true;
Eli Friedman8f249602011-11-04 23:46:11 +0000130 if (!MO.isReg())
131 continue;
132 if (MO.isDebug())
133 continue;
134 if (isYmmReg(MO.getReg()))
135 return true;
136 }
137 return false;
138}
139
Michael Liao14b02842013-12-03 09:17:32 +0000140/// clobbersAnyYmmReg() - Check if any YMM register will be clobbered by this
141/// instruction.
Lang Hames7c8189c2014-03-17 01:22:54 +0000142static bool callClobbersAnyYmmReg(MachineInstr *MI) {
143 assert(MI->isCall() && "Can only be called on call instructions.");
Michael Liao14b02842013-12-03 09:17:32 +0000144 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
145 const MachineOperand &MO = MI->getOperand(i);
146 if (!MO.isRegMask())
147 continue;
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000148 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
Michael Liao14b02842013-12-03 09:17:32 +0000149 if (MO.clobbersPhysReg(reg))
150 return true;
151 }
152 }
153 return false;
154}
155
Lang Hames7c8189c2014-03-17 01:22:54 +0000156// Insert a vzeroupper instruction before I.
157void VZeroUpperInserter::insertVZeroUpper(MachineBasicBlock::iterator I,
158 MachineBasicBlock &MBB) {
159 DebugLoc dl = I->getDebugLoc();
160 BuildMI(MBB, I, dl, TII->get(X86::VZEROUPPER));
161 ++NumVZU;
162 EverMadeChange = true;
163}
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000164
Lang Hames7c8189c2014-03-17 01:22:54 +0000165// Add MBB to the DirtySuccessors list if it hasn't already been added.
166void VZeroUpperInserter::addDirtySuccessor(MachineBasicBlock &MBB) {
167 if (!BlockStates[MBB.getNumber()].AddedToDirtySuccessors) {
168 DirtySuccessors.push_back(&MBB);
169 BlockStates[MBB.getNumber()].AddedToDirtySuccessors = true;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000170 }
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000171}
172
173/// processBasicBlock - Loop over all of the instructions in the basic block,
Andrea Di Biagio4f8bdcb2015-02-07 13:56:20 +0000174/// inserting vzeroupper instructions before function calls.
Lang Hames7c8189c2014-03-17 01:22:54 +0000175void VZeroUpperInserter::processBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000176
Lang Hames7c8189c2014-03-17 01:22:54 +0000177 // Start by assuming that the block PASS_THROUGH, which implies no unguarded
178 // calls.
179 BlockExitState CurState = PASS_THROUGH;
180 BlockStates[MBB.getNumber()].FirstUnguardedCall = MBB.end();
Eli Friedman8f249602011-11-04 23:46:11 +0000181
Lang Hames7c8189c2014-03-17 01:22:54 +0000182 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
Michael Liaoc7bf44d2013-10-23 18:32:43 +0000183 MachineInstr *MI = I;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000184 bool isControlFlow = MI->isCall() || MI->isReturn();
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000185
Chad Rosier24c19d22012-08-01 18:39:17 +0000186 // Shortcut: don't need to check regular instructions in dirty state.
Lang Hames7c8189c2014-03-17 01:22:54 +0000187 if (!isControlFlow && CurState == EXITS_DIRTY)
Eli Friedman8f249602011-11-04 23:46:11 +0000188 continue;
189
190 if (hasYmmReg(MI)) {
191 // We found a ymm-using instruction; this could be an AVX instruction,
192 // or it could be control flow.
Lang Hames7c8189c2014-03-17 01:22:54 +0000193 CurState = EXITS_DIRTY;
Eli Friedman8f249602011-11-04 23:46:11 +0000194 continue;
195 }
196
197 // Check for control-flow out of the current function (which might
198 // indirectly execute SSE instructions).
199 if (!isControlFlow)
200 continue;
201
Michael Liao14b02842013-12-03 09:17:32 +0000202 // If the call won't clobber any YMM register, skip it as well. It usually
203 // happens on helper function calls (such as '_chkstk', '_ftol2') where
204 // standard calling convention is not used (RegMask is not used to mark
Andrea Di Biagio4f8bdcb2015-02-07 13:56:20 +0000205 // register clobbered and register usage (def/imp-def/use) is well-defined
Michael Liao14b02842013-12-03 09:17:32 +0000206 // and explicitly specified.
Lang Hames7c8189c2014-03-17 01:22:54 +0000207 if (MI->isCall() && !callClobbersAnyYmmReg(MI))
Michael Liao14b02842013-12-03 09:17:32 +0000208 continue;
209
Eli Friedman8f249602011-11-04 23:46:11 +0000210 // The VZEROUPPER instruction resets the upper 128 bits of all Intel AVX
211 // registers. This instruction has zero latency. In addition, the processor
212 // changes back to Clean state, after which execution of Intel SSE
213 // instructions or Intel AVX instructions has no transition penalty. Add
214 // the VZEROUPPER instruction before any function call/return that might
215 // execute SSE code.
216 // FIXME: In some cases, we may want to move the VZEROUPPER into a
217 // predecessor block.
Lang Hames7c8189c2014-03-17 01:22:54 +0000218 if (CurState == EXITS_DIRTY) {
Eli Friedman8f249602011-11-04 23:46:11 +0000219 // After the inserted VZEROUPPER the state becomes clean again, but
220 // other YMM may appear before other subsequent calls or even before
221 // the end of the BB.
Lang Hames7c8189c2014-03-17 01:22:54 +0000222 insertVZeroUpper(I, MBB);
223 CurState = EXITS_CLEAN;
224 } else if (CurState == PASS_THROUGH) {
225 // If this block is currently in pass-through state and we encounter a
226 // call then whether we need a vzeroupper or not depends on whether this
227 // block has successors that exit dirty. Record the location of the call,
228 // and set the state to EXITS_CLEAN, but do not insert the vzeroupper yet.
229 // It will be inserted later if necessary.
230 BlockStates[MBB.getNumber()].FirstUnguardedCall = I;
231 CurState = EXITS_CLEAN;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000232 }
233 }
234
Lang Hames7c8189c2014-03-17 01:22:54 +0000235 DEBUG(dbgs() << "MBB #" << MBB.getNumber() << " exit state: "
236 << getBlockExitStateName(CurState) << '\n');
Eli Friedman8f249602011-11-04 23:46:11 +0000237
Lang Hames7c8189c2014-03-17 01:22:54 +0000238 if (CurState == EXITS_DIRTY)
239 for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
240 SE = MBB.succ_end();
241 SI != SE; ++SI)
242 addDirtySuccessor(**SI);
Eli Friedman8f249602011-11-04 23:46:11 +0000243
Lang Hames7c8189c2014-03-17 01:22:54 +0000244 BlockStates[MBB.getNumber()].ExitState = CurState;
245}
Eli Friedman8f249602011-11-04 23:46:11 +0000246
Lang Hames7c8189c2014-03-17 01:22:54 +0000247/// runOnMachineFunction - Loop over all of the basic blocks, inserting
Andrea Di Biagio4f8bdcb2015-02-07 13:56:20 +0000248/// vzeroupper instructions before function calls.
Lang Hames7c8189c2014-03-17 01:22:54 +0000249bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
Eric Christopher05b81972015-02-02 17:38:43 +0000250 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
Eric Christopher0d5c99e2014-05-22 01:46:02 +0000251 if (!ST.hasAVX() || ST.hasAVX512())
Lang Hames7c8189c2014-03-17 01:22:54 +0000252 return false;
Eric Christopher05b81972015-02-02 17:38:43 +0000253 TII = ST.getInstrInfo();
Lang Hames7c8189c2014-03-17 01:22:54 +0000254 MachineRegisterInfo &MRI = MF.getRegInfo();
255 EverMadeChange = false;
256
Matthias Braunada0adf2015-01-08 00:33:48 +0000257 bool FnHasLiveInYmm = checkFnHasLiveInYmm(MRI);
258
Lang Hames7c8189c2014-03-17 01:22:54 +0000259 // Fast check: if the function doesn't use any ymm registers, we don't need
260 // to insert any VZEROUPPER instructions. This is constant-time, so it is
261 // cheap in the common case of no ymm use.
Matthias Braunada0adf2015-01-08 00:33:48 +0000262 bool YMMUsed = FnHasLiveInYmm;
263 if (!YMMUsed) {
264 const TargetRegisterClass *RC = &X86::VR256RegClass;
265 for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end(); i != e;
266 i++) {
267 if (!MRI.reg_nodbg_empty(*i)) {
268 YMMUsed = true;
269 break;
270 }
Lang Hames7c8189c2014-03-17 01:22:54 +0000271 }
272 }
273 if (!YMMUsed) {
274 return false;
275 }
276
277 assert(BlockStates.empty() && DirtySuccessors.empty() &&
278 "X86VZeroUpper state should be clear");
279 BlockStates.resize(MF.getNumBlockIDs());
280
281 // Process all blocks. This will compute block exit states, record the first
282 // unguarded call in each block, and add successors of dirty blocks to the
283 // DirtySuccessors list.
Sanjay Patelfbca70d2015-05-05 21:20:52 +0000284 for (MachineBasicBlock &MBB : MF)
285 processBasicBlock(MBB);
Lang Hames7c8189c2014-03-17 01:22:54 +0000286
287 // If any YMM regs are live in to this function, add the entry block to the
288 // DirtySuccessors list
Matthias Braunada0adf2015-01-08 00:33:48 +0000289 if (FnHasLiveInYmm)
Lang Hames7c8189c2014-03-17 01:22:54 +0000290 addDirtySuccessor(MF.front());
291
292 // Re-visit all blocks that are successors of EXITS_DIRTY bsocks. Add
293 // vzeroupper instructions to unguarded calls, and propagate EXITS_DIRTY
294 // through PASS_THROUGH blocks.
295 while (!DirtySuccessors.empty()) {
296 MachineBasicBlock &MBB = *DirtySuccessors.back();
297 DirtySuccessors.pop_back();
298 BlockState &BBState = BlockStates[MBB.getNumber()];
299
300 // MBB is a successor of a dirty block, so its first call needs to be
301 // guarded.
302 if (BBState.FirstUnguardedCall != MBB.end())
303 insertVZeroUpper(BBState.FirstUnguardedCall, MBB);
304
305 // If this successor was a pass-through block then it is now dirty, and its
306 // successors need to be added to the worklist (if they haven't been
307 // already).
308 if (BBState.ExitState == PASS_THROUGH) {
309 DEBUG(dbgs() << "MBB #" << MBB.getNumber()
310 << " was Pass-through, is now Dirty-out.\n");
311 for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
312 SE = MBB.succ_end();
313 SI != SE; ++SI)
314 addDirtySuccessor(**SI);
315 }
316 }
317
318 BlockStates.clear();
319 return EverMadeChange;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000320}