45#define DEBUG_TYPE "riscv-opt-w-instrs"
46#define RISCV_OPT_W_INSTRS_NAME "RISC-V Optimize W Instructions"
48STATISTIC(NumRemovedSExtW,
"Number of removed sign-extensions");
50 "Number of instructions transformed to W-ops");
52 "Number of instructions transformed to non-W-ops");
55 cl::desc(
"Disable removal of sext.w"),
69 bool runOnMachineFunction(MachineFunction &MF)
override;
70 bool removeSExtWInstrs(MachineFunction &MF,
const RISCVInstrInfo &
TII,
71 const RISCVSubtarget &ST, MachineRegisterInfo &MRI);
72 bool canonicalizeWSuffixes(MachineFunction &MF,
const RISCVInstrInfo &
TII,
73 const RISCVSubtarget &ST,
74 MachineRegisterInfo &MRI);
76 void getAnalysisUsage(AnalysisUsage &AU)
const override {
86char RISCVOptWInstrs::ID = 0;
91 return new RISCVOptWInstrs();
112 auto NumDemandedBits =
114 return NumDemandedBits && Bits >= *NumDemandedBits;
129 while (!Worklist.
empty()) {
132 unsigned Bits =
P.second;
138 if (
MI->getNumExplicitDefs() != 1)
141 Register DestReg =
MI->getOperand(0).getReg();
147 unsigned OpIdx = UserOp.getOperandNo();
178 case RISCV::FCVT_H_W:
179 case RISCV::FCVT_H_W_INX:
180 case RISCV::FCVT_H_WU:
181 case RISCV::FCVT_H_WU_INX:
182 case RISCV::FCVT_S_W:
183 case RISCV::FCVT_S_W_INX:
184 case RISCV::FCVT_S_WU:
185 case RISCV::FCVT_S_WU_INX:
186 case RISCV::FCVT_D_W:
187 case RISCV::FCVT_D_W_INX:
188 case RISCV::FCVT_D_WU:
189 case RISCV::FCVT_D_WU_INX:
201 case RISCV::ZEXT_H_RV32:
202 case RISCV::ZEXT_H_RV64:
209 if (Bits >= (ST.getXLen() / 2))
229 if (Bits >= (ST.getXLen() - ShAmt))
236 if (Bits >= 32 - ShAmt)
263 if (Bits >=
Log2_32(ST.getXLen()))
280 case RISCV::SH1ADD_UW:
281 case RISCV::SH2ADD_UW:
282 case RISCV::SH3ADD_UW:
284 if (
OpIdx == 1 && Bits >= 32)
296 if (
OpIdx == 0 && Bits >= 8)
301 if (
OpIdx == 0 && Bits >= 16)
306 if (
OpIdx == 0 && Bits >= 32)
343 case RISCV::PseudoCCMOVGPR:
344 case RISCV::PseudoCCMOVGPRNoX0:
353 case RISCV::CZERO_EQZ:
354 case RISCV::CZERO_NEZ:
355 case RISCV::VT_MASKC:
356 case RISCV::VT_MASKCN:
366 if (Msb >= Lsb && Bits > Msb)
391 switch (
MI.getOpcode()) {
394 return MI.getOperand(2).getImm() >= 32;
396 return MI.getOperand(2).getImm() > 32;
399 return MI.getOperand(1).isReg() &&
MI.getOperand(1).getReg() == RISCV::X0;
408 return MI.getOperand(2).getImm() < 31 &&
409 MI.getOperand(1).getReg() == RISCV::X0;
412 return MI.getOperand(1).getReg() == RISCV::X0;
414 case RISCV::PseudoAtomicLoadNand32:
416 case RISCV::PseudoVMV_X_S: {
418 int64_t Log2SEW =
MI.getOperand(2).getImm();
419 assert(Log2SEW >= 3 && Log2SEW <= 6 &&
"Unexpected Log2SEW");
422 case RISCV::TH_EXT: {
423 unsigned Msb =
MI.getOperand(2).getImm();
424 unsigned Lsb =
MI.getOperand(3).getImm();
425 return Msb >= Lsb && (Msb - Lsb + 1) <= 32;
427 case RISCV::TH_EXTU: {
428 unsigned Msb =
MI.getOperand(2).getImm();
429 unsigned Lsb =
MI.getOperand(3).getImm();
430 return Msb >= Lsb && (Msb - Lsb + 1) < 32;
432 case RISCV::SATI_RV64:
435 return MI.getOperand(2).getImm() <= 32;
436 case RISCV::USATI_RV64:
439 return MI.getOperand(2).getImm() < 32;
451 auto AddRegToWorkList = [&](
Register SrcReg) {
458 if (!AddRegToWorkList(SrcReg))
461 while (!Worklist.
empty()) {
472 int OpNo =
MI->findRegisterDefOperandIdx(
Reg,
nullptr);
473 assert(OpNo != -1 &&
"Couldn't find register");
480 switch (
MI->getOpcode()) {
491 if (
MI->getParent() == &MF->
front()) {
497 Register CopySrcReg =
MI->getOperand(1).getReg();
498 if (CopySrcReg == RISCV::X10) {
508 auto II =
MI->getIterator();
509 if (
II ==
MBB->instr_begin() ||
510 (--
II)->getOpcode() != RISCV::ADJCALLSTACKUP)
526 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
527 unsigned BitWidth = IntTy->getBitWidth();
528 if ((
BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
529 (
BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
533 if (!AddRegToWorkList(CopySrcReg))
543 if (
MI->getOperand(2).getImm() >= 31)
555 if (!AddRegToWorkList(
MI->getOperand(1).getReg()))
559 case RISCV::PseudoCCADDW:
560 case RISCV::PseudoCCADDIW:
561 case RISCV::PseudoCCSUBW:
562 case RISCV::PseudoCCSLLW:
563 case RISCV::PseudoCCSRLW:
564 case RISCV::PseudoCCSRAW:
565 case RISCV::PseudoCCSLLIW:
566 case RISCV::PseudoCCSRLIW:
567 case RISCV::PseudoCCSRAIW:
570 if (!AddRegToWorkList(
MI->getOperand(1).getReg()))
584 case RISCV::PseudoCCMOVGPR:
585 case RISCV::PseudoCCMOVGPRNoX0:
586 case RISCV::PseudoCCAND:
587 case RISCV::PseudoCCOR:
588 case RISCV::PseudoCCXOR:
589 case RISCV::PseudoCCANDN:
590 case RISCV::PseudoCCORN:
591 case RISCV::PseudoCCXNOR:
604 unsigned B = 1,
E = 3,
D = 1;
605 switch (
MI->getOpcode()) {
607 E =
MI->getNumOperands();
610 case RISCV::PseudoCCMOVGPR:
611 case RISCV::PseudoCCMOVGPRNoX0:
615 case RISCV::PseudoCCAND:
616 case RISCV::PseudoCCOR:
617 case RISCV::PseudoCCXOR:
618 case RISCV::PseudoCCANDN:
619 case RISCV::PseudoCCORN:
620 case RISCV::PseudoCCXNOR:
632 for (
unsigned I =
B;
I !=
E;
I +=
D) {
633 if (!
MI->getOperand(
I).isReg())
636 if (!AddRegToWorkList(
MI->getOperand(
I).getReg()))
643 case RISCV::CZERO_EQZ:
644 case RISCV::CZERO_NEZ:
645 case RISCV::VT_MASKC:
646 case RISCV::VT_MASKCN:
649 if (!AddRegToWorkList(
MI->getOperand(1).getReg()))
654 if (
MI->getOperand(1).isReg() &&
MI->getOperand(1).getReg().isVirtual()) {
656 if (SrcMI->getOpcode() == RISCV::LUI &&
657 SrcMI->getOperand(1).isImm()) {
658 uint64_t Imm = SrcMI->getOperand(1).getImm();
678 if (
MI->getOperand(2).getImm() >= 32)
726 bool MadeChange =
false;
727 for (MachineBasicBlock &
MBB : MF) {
730 if (!RISCVInstrInfo::isSEXT_W(
MI))
735 SmallPtrSet<MachineInstr *, 4> FixableDefs;
749 for (MachineInstr *Fixable : FixableDefs) {
751 Fixable->setDesc(
TII.get(
getWOp(Fixable->getOpcode())));
752 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
753 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
754 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
756 ++NumTransformedToWInstrs;
762 MI.eraseFromParent();
773bool RISCVOptWInstrs::canonicalizeWSuffixes(MachineFunction &MF,
774 const RISCVInstrInfo &
TII,
775 const RISCVSubtarget &ST,
776 MachineRegisterInfo &MRI) {
778 bool ShouldPreferW =
ST.preferWInst();
779 bool MadeChange =
false;
781 for (MachineBasicBlock &
MBB : MF) {
782 for (MachineInstr &
MI :
MBB) {
783 std::optional<unsigned> WOpc;
784 std::optional<unsigned> NonWOpc;
785 unsigned OrigOpc =
MI.getOpcode();
790 NonWOpc = RISCV::ADD;
793 NonWOpc = RISCV::ADDI;
796 NonWOpc = RISCV::MUL;
799 NonWOpc = RISCV::SLLI;
802 NonWOpc = RISCV::SUB;
818 if (
MI.getOperand(2).getImm() >= 32)
828 if (ShouldStripW && NonWOpc.has_value() &&
hasAllWUsers(
MI, ST, MRI)) {
830 MI.setDesc(
TII.get(NonWOpc.value()));
832 ++NumTransformedToNonWInstrs;
838 if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
841 MI.setDesc(
TII.get(WOpc.value()));
842 MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
843 MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
844 MI.clearFlag(MachineInstr::MIFlag::IsExact);
846 ++NumTransformedToWInstrs;
855bool RISCVOptWInstrs::runOnMachineFunction(MachineFunction &MF) {
861 const RISCVInstrInfo &
TII = *
ST.getInstrInfo();
866 bool MadeChange =
false;
867 MadeChange |= removeSExtWInstrs(MF,
TII, ST, MRI);
868 MadeChange |= canonicalizeWSuffixes(MF,
TII, ST, MRI);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
static cl::opt< bool > DisableSExtWRemoval("loongarch-disable-sextw-removal", cl::desc("Disable removal of sign-extend insn"), cl::init(false), cl::Hidden)
static bool hasAllWUsers(const MachineInstr &OrigMI, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendedW(Register SrcReg, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static unsigned getWOp(unsigned Opcode)
Promote Memory to Register
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo)
static cl::opt< bool > DisableStripWSuffix("riscv-disable-strip-w-suffix", cl::desc("Disable strip W suffix"), cl::init(false), cl::Hidden)
static bool hasAllNBitUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
#define RISCV_OPT_W_INSTRS_NAME
static bool vectorPseudoHasAllNBitUsers(const MachineOperand &UserOp, unsigned Bits)
static cl::opt< bool > DisableSExtWRemoval("riscv-disable-sextw-removal", cl::desc("Disable removal of sext.w"), cl::init(false), cl::Hidden)
static unsigned getWOp(unsigned Opcode)
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
This class holds the attributes for a particular argument, parameter, function, or return value.
FunctionPass class - This class is used to implement most global optimizations.
Describe properties that are true of each instruction in the target description file.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
const GlobalValue * getGlobal() const
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
LLVM_ABI bool isLiveIn(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
bool isSExt32Register(Register Reg) const
Wrapper class representing virtual and physical registers.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool hasVLOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool hasSEWOp(uint64_t TSFlags)
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
std::optional< unsigned > getVectorLowDemandedScalarBits(unsigned Opcode, unsigned Log2SEW)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
FunctionPass * createRISCVOptWInstrsPass()
constexpr unsigned BitWidth
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.