Path: blob/main/contrib/llvm-project/llvm/lib/Target/X86/X86FixupBWInsts.cpp
35268 views
//===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7/// \file8/// This file defines the pass that looks through the machine instructions9/// late in the compilation, and finds byte or word instructions that10/// can be profitably replaced with 32 bit instructions that give equivalent11/// results for the bits of the results that are used. There are two possible12/// reasons to do this.13///14/// One reason is to avoid false-dependences on the upper portions15/// of the registers. Only instructions that have a destination register16/// which is not in any of the source registers can be affected by this.17/// Any instruction where one of the source registers is also the destination18/// register is unaffected, because it has a true dependence on the source19/// register already. So, this consideration primarily affects load20/// instructions and register-to-register moves. It would21/// seem like cmov(s) would also be affected, but because of the way cmov is22/// really implemented by most machines as reading both the destination and23/// and source registers, and then "merging" the two based on a condition,24/// it really already should be considered as having a true dependence on the25/// destination register as well.26///27/// The other reason to do this is for potential code size savings. Word28/// operations need an extra override byte compared to their 32 bit29/// versions. So this can convert many word operations to their larger30/// size, saving a byte in encoding. This could introduce partial register31/// dependences where none existed however. As an example take:32/// orw ax, $0x100033/// addw ax, $334/// now if this were to get transformed into35/// orw ax, $100036/// addl eax, $337/// because the addl encodes shorter than the addw, this would introduce38/// a use of a register that was only partially written earlier. On older39/// Intel processors this can be quite a performance penalty, so this should40/// probably only be done when it can be proven that a new partial dependence41/// wouldn't be created, or when your know a newer processor is being42/// targeted, or when optimizing for minimum code size.43///44//===----------------------------------------------------------------------===//4546#include "X86.h"47#include "X86InstrInfo.h"48#include "X86Subtarget.h"49#include "llvm/ADT/Statistic.h"50#include "llvm/Analysis/ProfileSummaryInfo.h"51#include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"52#include "llvm/CodeGen/LiveRegUnits.h"53#include "llvm/CodeGen/MachineFunctionPass.h"54#include "llvm/CodeGen/MachineInstrBuilder.h"55#include "llvm/CodeGen/MachineRegisterInfo.h"56#include "llvm/CodeGen/MachineSizeOpts.h"57#include "llvm/CodeGen/Passes.h"58#include "llvm/CodeGen/TargetInstrInfo.h"59#include "llvm/Support/Debug.h"60#include "llvm/Support/raw_ostream.h"61using namespace llvm;6263#define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"64#define FIXUPBW_NAME "x86-fixup-bw-insts"6566#define DEBUG_TYPE FIXUPBW_NAME6768// Option to allow this optimization pass to have fine-grained control.69static cl::opt<bool>70FixupBWInsts("fixup-byte-word-insts",71cl::desc("Change byte and word instructions to larger sizes"),72cl::init(true), cl::Hidden);7374namespace {75class FixupBWInstPass : public MachineFunctionPass {76/// Loop over all of the instructions in the basic block replacing applicable77/// byte or word instructions with better alternatives.78void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);7980/// This returns the 32 bit super reg of the original destination register of81/// the MachineInstr passed in, if that super register is dead just prior to82/// \p OrigMI. Otherwise it returns Register().83Register getSuperRegDestIfDead(MachineInstr *OrigMI) const;8485/// Change the MachineInstr \p MI into the equivalent extending load to 32 bit86/// register if it is safe to do so. Return the replacement instruction if87/// OK, otherwise return nullptr.88MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;8990/// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is91/// safe to do so. Return the replacement instruction if OK, otherwise return92/// nullptr.93MachineInstr *tryReplaceCopy(MachineInstr *MI) const;9495/// Change the MachineInstr \p MI into the equivalent extend to 32 bit96/// register if it is safe to do so. Return the replacement instruction if97/// OK, otherwise return nullptr.98MachineInstr *tryReplaceExtend(unsigned New32BitOpcode,99MachineInstr *MI) const;100101// Change the MachineInstr \p MI into an eqivalent 32 bit instruction if102// possible. Return the replacement instruction if OK, return nullptr103// otherwise.104MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB) const;105106public:107static char ID;108109StringRef getPassName() const override { return FIXUPBW_DESC; }110111FixupBWInstPass() : MachineFunctionPass(ID) { }112113void getAnalysisUsage(AnalysisUsage &AU) const override {114AU.addRequired<ProfileSummaryInfoWrapperPass>();115AU.addRequired<LazyMachineBlockFrequencyInfoPass>();116MachineFunctionPass::getAnalysisUsage(AU);117}118119/// Loop over all of the basic blocks, replacing byte and word instructions by120/// equivalent 32 bit instructions where performance or code size can be121/// improved.122bool runOnMachineFunction(MachineFunction &MF) override;123124MachineFunctionProperties getRequiredProperties() const override {125return MachineFunctionProperties().set(126MachineFunctionProperties::Property::NoVRegs);127}128129private:130MachineFunction *MF = nullptr;131132/// Machine instruction info used throughout the class.133const X86InstrInfo *TII = nullptr;134135const TargetRegisterInfo *TRI = nullptr;136137/// Local member for function's OptForSize attribute.138bool OptForSize = false;139140/// Register Liveness information after the current instruction.141LiveRegUnits LiveUnits;142143ProfileSummaryInfo *PSI = nullptr;144MachineBlockFrequencyInfo *MBFI = nullptr;145};146char FixupBWInstPass::ID = 0;147}148149INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)150151FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }152153bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {154if (!FixupBWInsts || skipFunction(MF.getFunction()))155return false;156157this->MF = &MF;158TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();159TRI = MF.getRegInfo().getTargetRegisterInfo();160PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();161MBFI = (PSI && PSI->hasProfileSummary()) ?162&getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :163nullptr;164LiveUnits.init(TII->getRegisterInfo());165166LLVM_DEBUG(dbgs() << "Start X86FixupBWInsts\n";);167168// Process all basic blocks.169for (auto &MBB : MF)170processBasicBlock(MF, MBB);171172LLVM_DEBUG(dbgs() << "End X86FixupBWInsts\n";);173174return true;175}176177/// Check if after \p OrigMI the only portion of super register178/// of the destination register of \p OrigMI that is alive is that179/// destination register.180///181/// If so, return that super register in \p SuperDestReg.182Register FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI) const {183const X86RegisterInfo *TRI = &TII->getRegisterInfo();184Register OrigDestReg = OrigMI->getOperand(0).getReg();185Register SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);186assert(SuperDestReg.isValid() && "Invalid Operand");187188const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);189190// Make sure that the sub-register that this instruction has as its191// destination is the lowest order sub-register of the super-register.192// If it isn't, then the register isn't really dead even if the193// super-register is considered dead.194if (SubRegIdx == X86::sub_8bit_hi)195return Register();196197// Test all regunits of the super register that are not part of the198// sub register. If none of them are live then the super register is safe to199// use.200bool SuperIsLive = false;201auto Range = TRI->regunits(OrigDestReg);202MCRegUnitIterator I = Range.begin(), E = Range.end();203for (MCRegUnit S : TRI->regunits(SuperDestReg)) {204I = std::lower_bound(I, E, S);205if ((I == E || *I > S) && LiveUnits.getBitVector().test(S)) {206SuperIsLive = true;207break;208}209}210if (!SuperIsLive)211return SuperDestReg;212213// If we get here, the super-register destination (or some part of it) is214// marked as live after the original instruction.215//216// The X86 backend does not have subregister liveness tracking enabled,217// so liveness information might be overly conservative. Specifically, the218// super register might be marked as live because it is implicitly defined219// by the instruction we are examining.220//221// However, for some specific instructions (this pass only cares about MOVs)222// we can produce more precise results by analysing that MOV's operands.223//224// Indeed, if super-register is not live before the mov it means that it225// was originally <read-undef> and so we are free to modify these226// undef upper bits. That may happen in case where the use is in another MBB227// and the vreg/physreg corresponding to the move has higher width than228// necessary (e.g. due to register coalescing with a "truncate" copy).229// So, we would like to handle patterns like this:230//231// %bb.2: derived from LLVM BB %if.then232// Live Ins: %rdi233// Predecessors according to CFG: %bb.0234// %ax<def> = MOV16rm killed %rdi, 1, %noreg, 0, %noreg, implicit-def %eax235// ; No implicit %eax236// Successors according to CFG: %bb.3(?%)237//238// %bb.3: derived from LLVM BB %if.end239// Live Ins: %eax Only %ax is actually live240// Predecessors according to CFG: %bb.2 %bb.1241// %ax = KILL %ax, implicit killed %eax242// RET 0, %ax243unsigned Opc = OrigMI->getOpcode();244// These are the opcodes currently known to work with the code below, if245// something // else will be added we need to ensure that new opcode has the246// same properties.247if (Opc != X86::MOV8rm && Opc != X86::MOV16rm && Opc != X86::MOV8rr &&248Opc != X86::MOV16rr)249return Register();250251bool IsDefined = false;252for (auto &MO: OrigMI->implicit_operands()) {253if (!MO.isReg())254continue;255256if (MO.isDef() && TRI->isSuperRegisterEq(OrigDestReg, MO.getReg()))257IsDefined = true;258259// If MO is a use of any part of the destination register but is not equal260// to OrigDestReg or one of its subregisters, we cannot use SuperDestReg.261// For example, if OrigDestReg is %al then an implicit use of %ah, %ax,262// %eax, or %rax will prevent us from using the %eax register.263if (MO.isUse() && !TRI->isSubRegisterEq(OrigDestReg, MO.getReg()) &&264TRI->regsOverlap(SuperDestReg, MO.getReg()))265return Register();266}267// Reg is not Imp-def'ed -> it's live both before/after the instruction.268if (!IsDefined)269return Register();270271// Otherwise, the Reg is not live before the MI and the MOV can't272// make it really live, so it's in fact dead even after the MI.273return SuperDestReg;274}275276MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,277MachineInstr *MI) const {278// We are going to try to rewrite this load to a larger zero-extending279// load. This is safe if all portions of the 32 bit super-register280// of the original destination register, except for the original destination281// register are dead. getSuperRegDestIfDead checks that.282Register NewDestReg = getSuperRegDestIfDead(MI);283if (!NewDestReg)284return nullptr;285286// Safe to change the instruction.287MachineInstrBuilder MIB =288BuildMI(*MF, MIMetadata(*MI), TII->get(New32BitOpcode), NewDestReg);289290unsigned NumArgs = MI->getNumOperands();291for (unsigned i = 1; i < NumArgs; ++i)292MIB.add(MI->getOperand(i));293294MIB.setMemRefs(MI->memoperands());295296// If it was debug tracked, record a substitution.297if (unsigned OldInstrNum = MI->peekDebugInstrNum()) {298unsigned Subreg = TRI->getSubRegIndex(MIB->getOperand(0).getReg(),299MI->getOperand(0).getReg());300unsigned NewInstrNum = MIB->getDebugInstrNum(*MF);301MF->makeDebugValueSubstitution({OldInstrNum, 0}, {NewInstrNum, 0}, Subreg);302}303304return MIB;305}306307MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {308assert(MI->getNumExplicitOperands() == 2);309auto &OldDest = MI->getOperand(0);310auto &OldSrc = MI->getOperand(1);311312Register NewDestReg = getSuperRegDestIfDead(MI);313if (!NewDestReg)314return nullptr;315316Register NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);317assert(NewSrcReg.isValid() && "Invalid Operand");318319// This is only correct if we access the same subregister index: otherwise,320// we could try to replace "movb %ah, %al" with "movl %eax, %eax".321const X86RegisterInfo *TRI = &TII->getRegisterInfo();322if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=323TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))324return nullptr;325326// Safe to change the instruction.327// Don't set src flags, as we don't know if we're also killing the superreg.328// However, the superregister might not be defined; make it explicit that329// we don't care about the higher bits by reading it as Undef, and adding330// an imp-use on the original subregister.331MachineInstrBuilder MIB =332BuildMI(*MF, MIMetadata(*MI), TII->get(X86::MOV32rr), NewDestReg)333.addReg(NewSrcReg, RegState::Undef)334.addReg(OldSrc.getReg(), RegState::Implicit);335336// Drop imp-defs/uses that would be redundant with the new def/use.337for (auto &Op : MI->implicit_operands())338if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))339MIB.add(Op);340341return MIB;342}343344MachineInstr *FixupBWInstPass::tryReplaceExtend(unsigned New32BitOpcode,345MachineInstr *MI) const {346Register NewDestReg = getSuperRegDestIfDead(MI);347if (!NewDestReg)348return nullptr;349350// Don't interfere with formation of CBW instructions which should be a351// shorter encoding than even the MOVSX32rr8. It's also immune to partial352// merge issues on Intel CPUs.353if (MI->getOpcode() == X86::MOVSX16rr8 &&354MI->getOperand(0).getReg() == X86::AX &&355MI->getOperand(1).getReg() == X86::AL)356return nullptr;357358// Safe to change the instruction.359MachineInstrBuilder MIB =360BuildMI(*MF, MIMetadata(*MI), TII->get(New32BitOpcode), NewDestReg);361362unsigned NumArgs = MI->getNumOperands();363for (unsigned i = 1; i < NumArgs; ++i)364MIB.add(MI->getOperand(i));365366MIB.setMemRefs(MI->memoperands());367368if (unsigned OldInstrNum = MI->peekDebugInstrNum()) {369unsigned Subreg = TRI->getSubRegIndex(MIB->getOperand(0).getReg(),370MI->getOperand(0).getReg());371unsigned NewInstrNum = MIB->getDebugInstrNum(*MF);372MF->makeDebugValueSubstitution({OldInstrNum, 0}, {NewInstrNum, 0}, Subreg);373}374375return MIB;376}377378MachineInstr *FixupBWInstPass::tryReplaceInstr(MachineInstr *MI,379MachineBasicBlock &MBB) const {380// See if this is an instruction of the type we are currently looking for.381switch (MI->getOpcode()) {382383case X86::MOV8rm:384// Replace 8-bit loads with the zero-extending version if not optimizing385// for size. The extending op is cheaper across a wide range of uarch and386// it avoids a potentially expensive partial register stall. It takes an387// extra byte to encode, however, so don't do this when optimizing for size.388if (!OptForSize)389return tryReplaceLoad(X86::MOVZX32rm8, MI);390break;391392case X86::MOV16rm:393// Always try to replace 16 bit load with 32 bit zero extending.394// Code size is the same, and there is sometimes a perf advantage395// from eliminating a false dependence on the upper portion of396// the register.397return tryReplaceLoad(X86::MOVZX32rm16, MI);398399case X86::MOV8rr:400case X86::MOV16rr:401// Always try to replace 8/16 bit copies with a 32 bit copy.402// Code size is either less (16) or equal (8), and there is sometimes a403// perf advantage from eliminating a false dependence on the upper portion404// of the register.405return tryReplaceCopy(MI);406407case X86::MOVSX16rr8:408return tryReplaceExtend(X86::MOVSX32rr8, MI);409case X86::MOVSX16rm8:410return tryReplaceExtend(X86::MOVSX32rm8, MI);411case X86::MOVZX16rr8:412return tryReplaceExtend(X86::MOVZX32rr8, MI);413case X86::MOVZX16rm8:414return tryReplaceExtend(X86::MOVZX32rm8, MI);415416default:417// nothing to do here.418break;419}420421return nullptr;422}423424void FixupBWInstPass::processBasicBlock(MachineFunction &MF,425MachineBasicBlock &MBB) {426427// This algorithm doesn't delete the instructions it is replacing428// right away. By leaving the existing instructions in place, the429// register liveness information doesn't change, and this makes the430// analysis that goes on be better than if the replaced instructions431// were immediately removed.432//433// This algorithm always creates a replacement instruction434// and notes that and the original in a data structure, until the435// whole BB has been analyzed. This keeps the replacement instructions436// from making it seem as if the larger register might be live.437SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;438439// Start computing liveness for this block. We iterate from the end to be able440// to update this for each instruction.441LiveUnits.clear();442// We run after PEI, so we need to AddPristinesAndCSRs.443LiveUnits.addLiveOuts(MBB);444445OptForSize = MF.getFunction().hasOptSize() ||446llvm::shouldOptimizeForSize(&MBB, PSI, MBFI);447448for (MachineInstr &MI : llvm::reverse(MBB)) {449if (MachineInstr *NewMI = tryReplaceInstr(&MI, MBB))450MIReplacements.push_back(std::make_pair(&MI, NewMI));451452// We're done with this instruction, update liveness for the next one.453LiveUnits.stepBackward(MI);454}455456while (!MIReplacements.empty()) {457MachineInstr *MI = MIReplacements.back().first;458MachineInstr *NewMI = MIReplacements.back().second;459MIReplacements.pop_back();460MBB.insert(MI, NewMI);461MBB.erase(MI);462}463}464465466