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" 21 #include "llvm/CodeGen/MachineFunctionPass.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/CodeGen/Passes.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include "llvm/Target/TargetInstrInfo.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 { 42 return MachineFunctionProperties().set( 43 MachineFunctionProperties::Property::NoVRegs); 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 96 FunctionPass *llvm::createX86IssueVZeroUpperPass() { 97 return new VZeroUpperInserter(); 98 } 99 100 const char* VZeroUpperInserter::getBlockExitStateName(BlockExitState ST) { 101 switch (ST) { 102 case PASS_THROUGH: return "Pass-through"; 103 case EXITS_DIRTY: return "Exits-dirty"; 104 case EXITS_CLEAN: return "Exits-clean"; 105 } 106 llvm_unreachable("Invalid block exit state."); 107 } 108 109 /// VZEROUPPER cleans state that is related to Y/ZMM0-15 only. 110 /// Thus, there is no need to check for Y/ZMM16 and above. 111 static bool isYmmOrZmmReg(unsigned Reg) { 112 return (Reg >= X86::YMM0 && Reg <= X86::YMM15) || 113 (Reg >= X86::ZMM0 && Reg <= X86::ZMM15); 114 } 115 116 static bool checkFnHasLiveInYmmOrZmm(MachineRegisterInfo &MRI) { 117 for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(), 118 E = MRI.livein_end(); I != E; ++I) 119 if (isYmmOrZmmReg(I->first)) 120 return true; 121 122 return false; 123 } 124 125 static bool clobbersAllYmmAndZmmRegs(const MachineOperand &MO) { 126 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) { 127 if (!MO.clobbersPhysReg(reg)) 128 return false; 129 } 130 for (unsigned reg = X86::ZMM0; reg <= X86::ZMM15; ++reg) { 131 if (!MO.clobbersPhysReg(reg)) 132 return false; 133 } 134 return true; 135 } 136 137 static bool hasYmmOrZmmReg(MachineInstr &MI) { 138 for (const MachineOperand &MO : MI.operands()) { 139 if (MI.isCall() && MO.isRegMask() && !clobbersAllYmmAndZmmRegs(MO)) 140 return true; 141 if (!MO.isReg()) 142 continue; 143 if (MO.isDebug()) 144 continue; 145 if (isYmmOrZmmReg(MO.getReg())) 146 return true; 147 } 148 return false; 149 } 150 151 /// Check if given call instruction has a RegMask operand. 152 static bool callHasRegMask(MachineInstr &MI) { 153 assert(MI.isCall() && "Can only be called on call instructions."); 154 for (const MachineOperand &MO : MI.operands()) { 155 if (MO.isRegMask()) 156 return true; 157 } 158 return false; 159 } 160 161 /// Insert a vzeroupper instruction before I. 162 void VZeroUpperInserter::insertVZeroUpper(MachineBasicBlock::iterator I, 163 MachineBasicBlock &MBB) { 164 DebugLoc dl = I->getDebugLoc(); 165 BuildMI(MBB, I, dl, TII->get(X86::VZEROUPPER)); 166 ++NumVZU; 167 EverMadeChange = true; 168 } 169 170 /// Add MBB to the DirtySuccessors list if it hasn't already been added. 171 void VZeroUpperInserter::addDirtySuccessor(MachineBasicBlock &MBB) { 172 if (!BlockStates[MBB.getNumber()].AddedToDirtySuccessors) { 173 DirtySuccessors.push_back(&MBB); 174 BlockStates[MBB.getNumber()].AddedToDirtySuccessors = true; 175 } 176 } 177 178 /// Loop over all of the instructions in the basic block, inserting vzeroupper 179 /// instructions before function calls. 180 void VZeroUpperInserter::processBasicBlock(MachineBasicBlock &MBB) { 181 // Start by assuming that the block is PASS_THROUGH which implies no unguarded 182 // calls. 183 BlockExitState CurState = PASS_THROUGH; 184 BlockStates[MBB.getNumber()].FirstUnguardedCall = MBB.end(); 185 186 for (MachineInstr &MI : MBB) { 187 bool IsCall = MI.isCall(); 188 bool IsReturn = MI.isReturn(); 189 bool IsControlFlow = IsCall || IsReturn; 190 191 // No need for vzeroupper before iret in interrupt handler function, 192 // epilogue will restore YMM/ZMM registers if needed. 193 if (IsX86INTR && IsReturn) 194 continue; 195 196 // An existing VZERO* instruction resets the state. 197 if (MI.getOpcode() == X86::VZEROALL || MI.getOpcode() == X86::VZEROUPPER) { 198 CurState = EXITS_CLEAN; 199 continue; 200 } 201 202 // Shortcut: don't need to check regular instructions in dirty state. 203 if (!IsControlFlow && CurState == EXITS_DIRTY) 204 continue; 205 206 if (hasYmmOrZmmReg(MI)) { 207 // We found a ymm/zmm-using instruction; this could be an AVX/AVX512 208 // instruction, or it could be control flow. 209 CurState = EXITS_DIRTY; 210 continue; 211 } 212 213 // Check for control-flow out of the current function (which might 214 // indirectly execute SSE instructions). 215 if (!IsControlFlow) 216 continue; 217 218 // If the call has no RegMask, skip it as well. It usually happens on 219 // helper function calls (such as '_chkstk', '_ftol2') where standard 220 // calling convention is not used (RegMask is not used to mark register 221 // clobbered and register usage (def/imp-def/use) is well-defined and 222 // explicitly specified. 223 if (IsCall && !callHasRegMask(MI)) 224 continue; 225 226 // The VZEROUPPER instruction resets the upper 128 bits of YMM0-YMM15 227 // registers. In addition, the processor changes back to Clean state, after 228 // which execution of SSE instructions or AVX instructions has no transition 229 // penalty. Add the VZEROUPPER instruction before any function call/return 230 // that might execute SSE code. 231 // FIXME: In some cases, we may want to move the VZEROUPPER into a 232 // predecessor block. 233 if (CurState == EXITS_DIRTY) { 234 // After the inserted VZEROUPPER the state becomes clean again, but 235 // other YMM/ZMM may appear before other subsequent calls or even before 236 // the end of the BB. 237 insertVZeroUpper(MI, MBB); 238 CurState = EXITS_CLEAN; 239 } else if (CurState == PASS_THROUGH) { 240 // If this block is currently in pass-through state and we encounter a 241 // call then whether we need a vzeroupper or not depends on whether this 242 // block has successors that exit dirty. Record the location of the call, 243 // and set the state to EXITS_CLEAN, but do not insert the vzeroupper yet. 244 // It will be inserted later if necessary. 245 BlockStates[MBB.getNumber()].FirstUnguardedCall = MI; 246 CurState = EXITS_CLEAN; 247 } 248 } 249 250 DEBUG(dbgs() << "MBB #" << MBB.getNumber() << " exit state: " 251 << getBlockExitStateName(CurState) << '\n'); 252 253 if (CurState == EXITS_DIRTY) 254 for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(), 255 SE = MBB.succ_end(); 256 SI != SE; ++SI) 257 addDirtySuccessor(**SI); 258 259 BlockStates[MBB.getNumber()].ExitState = CurState; 260 } 261 262 /// Loop over all of the basic blocks, inserting vzeroupper instructions before 263 /// function calls. 264 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) { 265 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>(); 266 if (!ST.hasAVX() || ST.hasFastPartialYMMorZMMWrite()) 267 return false; 268 TII = ST.getInstrInfo(); 269 MachineRegisterInfo &MRI = MF.getRegInfo(); 270 EverMadeChange = false; 271 IsX86INTR = MF.getFunction()->getCallingConv() == CallingConv::X86_INTR; 272 273 bool FnHasLiveInYmmOrZmm = checkFnHasLiveInYmmOrZmm(MRI); 274 275 // Fast check: if the function doesn't use any ymm/zmm registers, we don't 276 // need to insert any VZEROUPPER instructions. This is constant-time, so it 277 // is cheap in the common case of no ymm/zmm use. 278 bool YmmOrZmmUsed = FnHasLiveInYmmOrZmm; 279 const TargetRegisterClass *RCs[2] = {&X86::VR256RegClass, &X86::VR512RegClass}; 280 for (auto *RC : RCs) { 281 if (!YmmOrZmmUsed) { 282 for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end(); i != e; 283 i++) { 284 if (!MRI.reg_nodbg_empty(*i)) { 285 YmmOrZmmUsed = true; 286 break; 287 } 288 } 289 } 290 } 291 if (!YmmOrZmmUsed) { 292 return false; 293 } 294 295 assert(BlockStates.empty() && DirtySuccessors.empty() && 296 "X86VZeroUpper state should be clear"); 297 BlockStates.resize(MF.getNumBlockIDs()); 298 299 // Process all blocks. This will compute block exit states, record the first 300 // unguarded call in each block, and add successors of dirty blocks to the 301 // DirtySuccessors list. 302 for (MachineBasicBlock &MBB : MF) 303 processBasicBlock(MBB); 304 305 // If any YMM/ZMM regs are live-in to this function, add the entry block to 306 // the DirtySuccessors list 307 if (FnHasLiveInYmmOrZmm) 308 addDirtySuccessor(MF.front()); 309 310 // Re-visit all blocks that are successors of EXITS_DIRTY blocks. Add 311 // vzeroupper instructions to unguarded calls, and propagate EXITS_DIRTY 312 // through PASS_THROUGH blocks. 313 while (!DirtySuccessors.empty()) { 314 MachineBasicBlock &MBB = *DirtySuccessors.back(); 315 DirtySuccessors.pop_back(); 316 BlockState &BBState = BlockStates[MBB.getNumber()]; 317 318 // MBB is a successor of a dirty block, so its first call needs to be 319 // guarded. 320 if (BBState.FirstUnguardedCall != MBB.end()) 321 insertVZeroUpper(BBState.FirstUnguardedCall, MBB); 322 323 // If this successor was a pass-through block, then it is now dirty. Its 324 // successors need to be added to the worklist (if they haven't been 325 // already). 326 if (BBState.ExitState == PASS_THROUGH) { 327 DEBUG(dbgs() << "MBB #" << MBB.getNumber() 328 << " was Pass-through, is now Dirty-out.\n"); 329 for (MachineBasicBlock *Succ : MBB.successors()) 330 addDirtySuccessor(*Succ); 331 } 332 } 333 334 BlockStates.clear(); 335 return EverMadeChange; 336 } 337