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 #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 118 static bool checkFnHasLiveInYmmOrZmm(MachineRegisterInfo &MRI) { 119 for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(), 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 139 static bool hasYmmOrZmmReg(MachineInstr &MI) { 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. 154 static bool callHasRegMask(MachineInstr &MI) { 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(); 271 MachineRegisterInfo &MRI = MF.getRegInfo(); 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 } 339