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");
56class RISCVOptWInstrsImpl {
72 RISCVOptWInstrsLegacy() : MachineFunctionPass(ID) {}
76 void getAnalysisUsage(AnalysisUsage &AU)
const override {
86char RISCVOptWInstrsLegacy::ID = 0;
91 return new RISCVOptWInstrsLegacy();
111 auto NumDemandedBits =
113 return NumDemandedBits && Bits >= *NumDemandedBits;
128 while (!Worklist.
empty()) {
131 unsigned Bits =
P.second;
137 if (
MI->getNumExplicitDefs() != 1)
140 Register DestReg =
MI->getOperand(0).getReg();
146 unsigned OpIdx = UserOp.getOperandNo();
177 case RISCV::FCVT_H_W:
178 case RISCV::FCVT_H_W_INX:
179 case RISCV::FCVT_H_WU:
180 case RISCV::FCVT_H_WU_INX:
181 case RISCV::FCVT_S_W:
182 case RISCV::FCVT_S_W_INX:
183 case RISCV::FCVT_S_WU:
184 case RISCV::FCVT_S_WU_INX:
185 case RISCV::FCVT_D_W:
186 case RISCV::FCVT_D_W_INX:
187 case RISCV::FCVT_D_WU:
188 case RISCV::FCVT_D_WU_INX:
200 case RISCV::ZEXT_H_RV32:
201 case RISCV::ZEXT_H_RV64:
208 if (Bits >= (ST.getXLen() / 2))
228 if (Bits >= (ST.getXLen() - ShAmt))
235 if (Bits >= 32 - ShAmt)
262 if (Bits >=
Log2_32(ST.getXLen()))
275 if (OpIdx == 2 && 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:
348 if (OpIdx != 1 && OpIdx != 2)
353 case RISCV::CZERO_EQZ:
354 case RISCV::CZERO_NEZ:
364 if (Msb >= Lsb && Bits > Msb)
389 switch (
MI.getOpcode()) {
392 return MI.getOperand(2).getImm() >= 32;
394 return MI.getOperand(2).getImm() > 32;
397 return MI.getOperand(1).isReg() &&
MI.getOperand(1).getReg() == RISCV::X0;
406 return MI.getOperand(2).getImm() < 31 &&
407 MI.getOperand(1).getReg() == RISCV::X0;
410 return MI.getOperand(1).getReg() == RISCV::X0;
412 case RISCV::PseudoAtomicLoadNand32:
414 case RISCV::PseudoVMV_X_S: {
416 int64_t Log2SEW =
MI.getOperand(2).getImm();
417 assert(Log2SEW >= 3 && Log2SEW <= 6 &&
"Unexpected Log2SEW");
420 case RISCV::TH_EXT: {
421 unsigned Msb =
MI.getOperand(2).getImm();
422 unsigned Lsb =
MI.getOperand(3).getImm();
423 return Msb >= Lsb && (Msb - Lsb + 1) <= 32;
425 case RISCV::TH_EXTU: {
426 unsigned Msb =
MI.getOperand(2).getImm();
427 unsigned Lsb =
MI.getOperand(3).getImm();
428 return Msb >= Lsb && (Msb - Lsb + 1) < 32;
430 case RISCV::SATI_RV64:
433 return MI.getOperand(2).getImm() <= 32;
434 case RISCV::USATI_RV64:
437 return MI.getOperand(2).getImm() < 32;
449 auto AddRegToWorkList = [&](
Register SrcReg) {
456 if (!AddRegToWorkList(SrcReg))
459 while (!Worklist.
empty()) {
470 int OpNo =
MI->findRegisterDefOperandIdx(
Reg,
nullptr);
471 assert(OpNo != -1 &&
"Couldn't find register");
478 switch (
MI->getOpcode()) {
489 if (
MI->getParent() == &MF->
front() &&
493 Register CopySrcReg =
MI->getOperand(1).getReg();
494 if (CopySrcReg == RISCV::X10) {
504 auto II =
MI->getIterator();
505 if (
II ==
MBB->instr_begin() ||
506 (--
II)->getOpcode() != RISCV::ADJCALLSTACKUP)
522 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
523 unsigned BitWidth = IntTy->getBitWidth();
524 if ((
BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
525 (
BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
529 if (!AddRegToWorkList(CopySrcReg))
539 if (
MI->getOperand(2).getImm() >= 31)
551 if (!AddRegToWorkList(
MI->getOperand(1).getReg()))
555 case RISCV::PseudoCCADDW:
556 case RISCV::PseudoCCADDIW:
557 case RISCV::PseudoCCSUBW:
558 case RISCV::PseudoCCSLLW:
559 case RISCV::PseudoCCSRLW:
560 case RISCV::PseudoCCSRAW:
561 case RISCV::PseudoCCSLLIW:
562 case RISCV::PseudoCCSRLIW:
563 case RISCV::PseudoCCSRAIW:
566 if (!AddRegToWorkList(
MI->getOperand(1).getReg()))
580 case RISCV::PseudoCCMOVGPR:
581 case RISCV::PseudoCCMOVGPRNoX0:
582 case RISCV::PseudoCCAND:
583 case RISCV::PseudoCCOR:
584 case RISCV::PseudoCCXOR:
585 case RISCV::PseudoCCANDN:
586 case RISCV::PseudoCCORN:
587 case RISCV::PseudoCCXNOR:
600 unsigned B = 1,
E = 3,
D = 1;
601 switch (
MI->getOpcode()) {
603 E =
MI->getNumOperands();
606 case RISCV::PseudoCCMOVGPR:
607 case RISCV::PseudoCCMOVGPRNoX0:
611 case RISCV::PseudoCCAND:
612 case RISCV::PseudoCCOR:
613 case RISCV::PseudoCCXOR:
614 case RISCV::PseudoCCANDN:
615 case RISCV::PseudoCCORN:
616 case RISCV::PseudoCCXNOR:
628 for (
unsigned I =
B;
I !=
E;
I +=
D) {
629 if (!
MI->getOperand(
I).isReg())
632 if (!AddRegToWorkList(
MI->getOperand(
I).getReg()))
639 case RISCV::CZERO_EQZ:
640 case RISCV::CZERO_NEZ:
643 if (!AddRegToWorkList(
MI->getOperand(1).getReg()))
648 if (
MI->getOperand(1).isReg() &&
MI->getOperand(1).getReg().isVirtual()) {
650 if (SrcMI->getOpcode() == RISCV::LUI &&
651 SrcMI->getOperand(1).isImm()) {
670 if (
MI->hasOneMemOperand() && !(*
MI->memoperands_begin())->isVolatile() &&
682 if (
MI->getOperand(2).getImm() >= 32)
699 if (!
MI->getOperand(2).isReg() ||
MI->getOperand(2).getReg() != RISCV::X0)
742 if (!
ST.getCLOpts().sextw_removal)
745 bool MadeChange =
false;
746 for (MachineBasicBlock &
MBB : MF) {
749 if (!RISCVInstrInfo::isSEXT_W(
MI))
754 SmallPtrSet<MachineInstr *, 4> FixableDefs;
768 for (MachineInstr *Fixable : FixableDefs) {
771 if (Fixable->getOpcode() == RISCV::ADD_UW) {
772 assert(Fixable->getOperand(2).isReg() &&
773 Fixable->getOperand(2).getReg() == RISCV::X0 &&
774 "Unexpected ADD_UW operand.");
775 Fixable->setDesc(
TII.get(RISCV::ADDIW));
776 Fixable->getOperand(2).ChangeToImmediate(0);
778 Fixable->setDesc(
TII.get(
getWOp(Fixable->getOpcode())));
780 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
781 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
782 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
784 ++NumTransformedToWInstrs;
790 MI.eraseFromParent();
802 const RISCVInstrInfo &
TII,
803 const RISCVSubtarget &ST,
804 MachineRegisterInfo &MRI) {
805 bool ShouldStripW =
ST.getCLOpts().strip_w_suffix && !
ST.preferWInst();
806 bool ShouldPreferW =
ST.preferWInst();
807 bool MadeChange =
false;
809 for (MachineBasicBlock &
MBB : MF) {
810 for (MachineInstr &
MI :
MBB) {
811 std::optional<unsigned> WOpc;
812 std::optional<unsigned> NonWOpc;
813 unsigned OrigOpc =
MI.getOpcode();
818 NonWOpc = RISCV::ADD;
821 NonWOpc = RISCV::ADDI;
824 NonWOpc = RISCV::MUL;
827 NonWOpc = RISCV::SLLI;
830 NonWOpc = RISCV::SUB;
846 if (
MI.getOperand(2).getImm() >= 32)
851 if (!
MI.hasOneMemOperand() || (*
MI.memoperands_begin())->isVolatile())
859 if (!
MI.hasOneMemOperand() || (*
MI.memoperands_begin())->isVolatile())
868 if (ShouldStripW && NonWOpc.has_value() &&
hasAllWUsers(
MI, ST, MRI)) {
870 MI.setDesc(
TII.get(NonWOpc.value()));
872 ++NumTransformedToNonWInstrs;
878 if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
881 MI.setDesc(
TII.get(WOpc.value()));
882 MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
883 MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
884 MI.clearFlag(MachineInstr::MIFlag::IsExact);
886 ++NumTransformedToWInstrs;
898 const RISCVInstrInfo &
TII = *
ST.getInstrInfo();
903 bool MadeChange =
false;
904 MadeChange |= removeSExtWInstrs(MF,
TII, ST, MRI);
905 MadeChange |= canonicalizeWSuffixes(MF,
TII, ST, MRI);
912 return RISCVOptWInstrsImpl().run(MF);
918 bool Changed = RISCVOptWInstrsImpl().run(MF);
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 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
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool vectorPseudoHasAllNBitUsers(const MachineInstr &MI, unsigned OpIdx, unsigned Bits)
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 bool hasAllNBitUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
#define RISCV_OPT_W_INSTRS_NAME
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.
Represents analyses that only rely on functions' control flow.
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
const GlobalValue * getGlobal() const
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 LLVM_READONLY 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 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.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
bool isSExt32Register(Register Reg) const
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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.
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)
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.
FunctionPass * createRISCVOptWInstrsLegacyPass()
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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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.
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.