41 #define DEBUG_TYPE "wasm-reg-stackify" 46 return "WebAssembly Register Stackify";
72 "Reorder instructions to use the WebAssembly value stack",
76 return new WebAssemblyRegStackify();
106 if (RegClass == &WebAssembly::I32RegClass) {
107 MI->
setDesc(TII->
get(WebAssembly::CONST_I32));
109 }
else if (RegClass == &WebAssembly::I64RegClass) {
110 MI->
setDesc(TII->
get(WebAssembly::CONST_I64));
112 }
else if (RegClass == &WebAssembly::F32RegClass) {
113 MI->
setDesc(TII->
get(WebAssembly::CONST_F32));
117 }
else if (RegClass == &WebAssembly::F64RegClass) {
118 MI->
setDesc(TII->
get(WebAssembly::CONST_F64));
122 }
else if (RegClass == &WebAssembly::V128RegClass) {
124 MI->
setDesc(TII->
get(WebAssembly::SPLAT_v4i32));
127 TII->
get(WebAssembly::CONST_I32), TempReg)
139 bool &Write,
bool &Effects,
bool &StackPointer) {
146 if (
const auto *GA = dyn_cast<GlobalAlias>(GV))
147 if (!GA->isInterposable())
148 GV = GA->getAliasee();
150 if (
const auto *
F = dyn_cast<Function>(GV)) {
151 if (!
F->doesNotThrow())
153 if (
F->doesNotAccessMemory())
155 if (
F->onlyReadsMemory()) {
171 bool &Write,
bool &Effects,
bool &StackPointer) {
186 case WebAssembly::DIV_S_I32:
187 case WebAssembly::DIV_S_I64:
188 case WebAssembly::REM_S_I32:
189 case WebAssembly::REM_S_I64:
190 case WebAssembly::DIV_U_I32:
191 case WebAssembly::DIV_U_I64:
192 case WebAssembly::REM_U_I32:
193 case WebAssembly::REM_U_I64:
194 case WebAssembly::I32_TRUNC_S_F32:
195 case WebAssembly::I64_TRUNC_S_F32:
196 case WebAssembly::I32_TRUNC_S_F64:
197 case WebAssembly::I64_TRUNC_S_F64:
198 case WebAssembly::I32_TRUNC_U_F32:
199 case WebAssembly::I64_TRUNC_U_F32:
200 case WebAssembly::I32_TRUNC_U_F64:
201 case WebAssembly::I64_TRUNC_U_F64:
221 case WebAssembly::DIV_S_I32:
222 case WebAssembly::DIV_S_I64:
223 case WebAssembly::REM_S_I32:
224 case WebAssembly::REM_S_I64:
225 case WebAssembly::DIV_U_I32:
226 case WebAssembly::DIV_U_I64:
227 case WebAssembly::REM_U_I32:
228 case WebAssembly::REM_U_I64:
229 case WebAssembly::I32_TRUNC_S_F32:
230 case WebAssembly::I64_TRUNC_S_F32:
231 case WebAssembly::I32_TRUNC_S_F64:
232 case WebAssembly::I64_TRUNC_S_F64:
233 case WebAssembly::I32_TRUNC_U_F32:
234 case WebAssembly::I64_TRUNC_U_F32:
235 case WebAssembly::I32_TRUNC_U_F64:
236 case WebAssembly::I64_TRUNC_U_F64:
249 if (MI.
getOpcode() == WebAssembly::GLOBAL_SET_I32 &&
256 queryCallee(MI, CalleeOpNo, Read, Write, Effects, StackPointer);
263 return Def.
isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
300 if (Result.valueIn() == DefVNI) {
301 if (!Result.isKill())
322 if (Def->
getOpcode() == WebAssembly::CATCH ||
323 Def->
getOpcode() == WebAssembly::EXTRACT_EXCEPTION_I32) {
326 for (
auto E = MBB->
end(); NextI !=
E && NextI->isDebugInstr(); ++NextI)
335 if (!MO.isReg() || MO.isUndef())
347 if (Reg == WebAssembly::ARGUMENTS)
363 bool Read =
false, Write =
false, Effects =
false, StackPointer =
false;
364 query(*Def, AA, Read, Write, Effects, StackPointer);
368 bool HasMutableRegisters = !MutableRegisters.
empty();
369 if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
374 for (--I; I !=
D; --
I) {
375 bool InterveningRead =
false;
376 bool InterveningWrite =
false;
377 bool InterveningEffects =
false;
378 bool InterveningStackPointer =
false;
379 query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
380 InterveningStackPointer);
381 if (Effects && InterveningEffects)
383 if (Read && InterveningWrite)
385 if (Write && (InterveningRead || InterveningWrite))
387 if (StackPointer && InterveningStackPointer)
390 for (
unsigned Reg : MutableRegisters)
392 if (MO.isReg() && MO.isDef() && MO.getReg() ==
Reg)
418 if (UseVNI != OneUseVNI)
421 if (UseInst == OneUseInst) {
428 while (!MDT.
dominates(OneUseInst, UseInst)) {
446 if (NewUseInst == OneUseInst) {
447 if (&OneUse > &NewUse)
451 UseInst = NewUseInst;
460 if (RC == &WebAssembly::I32RegClass)
461 return WebAssembly::TEE_I32;
462 if (RC == &WebAssembly::I64RegClass)
463 return WebAssembly::TEE_I64;
464 if (RC == &WebAssembly::F32RegClass)
465 return WebAssembly::TEE_F32;
466 if (RC == &WebAssembly::F64RegClass)
467 return WebAssembly::TEE_F64;
468 if (RC == &WebAssembly::V128RegClass)
469 return WebAssembly::TEE_V128;
491 MBB.
splice(Insert, &MBB, Def);
517 DefDIs.updateReg(NewReg);
539 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
567 DefDIs.move(&*Insert);
568 DefDIs.updateReg(NewReg);
570 DefDIs.clone(&*Insert, NewReg);
605 MBB.
splice(Insert, &MBB, Def);
640 DefDIs.clone(Tee, DefReg);
641 DefDIs.clone(Insert, TeeReg);
651 class TreeWalkerState {
653 using mop_reverse_iterator = std::reverse_iterator<mop_iterator>;
664 bool done()
const {
return Worklist.
empty(); }
667 RangeTy &Range = Worklist.
back();
670 if (Range.begin() == Range.end())
673 Worklist.
back().begin() != Worklist.
back().end()) &&
674 "Empty ranges shouldn't remain in the worklist");
681 if (Range.begin() != Range.end())
688 assert(hasRemainingOperands(Instr) &&
689 "Reseting operands should only be done when the instruction has " 690 "an operand still on the stack");
696 bool hasRemainingOperands(
const MachineInstr *Instr)
const {
697 if (Worklist.
empty())
699 const RangeTy &Range = Worklist.
back();
700 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
709 bool isOnStack(
unsigned Reg)
const {
710 for (
const RangeTy &Range : Worklist)
712 if (MO.isReg() && MO.getReg() ==
Reg)
720 class CommutingState {
726 bool TentativelyCommuting =
false;
727 bool Declined =
false;
731 unsigned Operand0, Operand1;
737 void maybeCommute(
MachineInstr *Insert, TreeWalkerState &TreeWalker,
739 if (TentativelyCommuting) {
741 "Don't decline commuting until you've finished trying it");
743 TII->commuteInstruction(*Insert,
false, Operand0, Operand1);
744 TentativelyCommuting =
false;
746 }
else if (!Declined && TreeWalker.hasRemainingOperands(Insert)) {
749 if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
751 TII->commuteInstruction(*Insert,
false, Operand0, Operand1);
752 TreeWalker.resetTopOperands(Insert);
753 TentativelyCommuting =
true;
762 TentativelyCommuting =
false;
768 bool WebAssemblyRegStackify::runOnMachineFunction(
MachineFunction &MF) {
769 LLVM_DEBUG(
dbgs() <<
"********** Register Stackifying **********\n" 770 "********** Function: " 773 bool Changed =
false;
778 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
779 auto &MDT = getAnalysis<MachineDominatorTree>();
780 auto &LIS = getAnalysis<LiveIntervals>();
788 for (
auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
801 CommutingState Commuting;
802 TreeWalkerState TreeWalker(Insert);
803 while (!TreeWalker.done()) {
811 assert(Op.
isUse() &&
"explicit_uses() should only iterate over uses");
813 "explicit_uses() should only iterate over explicit operands");
847 if (Def->
getOpcode() == WebAssembly::CATCH)
856 bool SameBlock = Def->
getParent() == &MBB;
857 bool CanMove = SameBlock &&
isSafeToMove(Def, Insert, AA, MRI) &&
858 !TreeWalker.isOnStack(Reg);
859 if (CanMove &&
hasOneUse(Reg, Def, MRI, MDT, LIS)) {
865 }
else if (CanMove &&
872 if (!CanMove && SameBlock)
873 Commuting.maybeCommute(Insert, TreeWalker, TII);
881 if (Insert->
getOpcode() == TargetOpcode::IMPLICIT_DEF)
887 TreeWalker.pushOperands(Insert);
892 if (Insert != &*MII) {
903 MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
905 MBB.addLiveIn(WebAssembly::VALUE_STACK);
913 if (
MI.isDebugInstr())
925 "Register stack pop should be paired with a push");
932 "Register stack pushes and pops should be balanced");
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
static void convertImplicitDefToConstZero(MachineInstr *MI, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineFunction &MF, LiveIntervals &LIS)
auto drop_begin(T &&RangeOrContainer, size_t N) -> iterator_range< decltype(adl_begin(RangeOrContainer))>
Return a range covering RangeOrContainer with the first N elements excluded.
static Type * getDoubleTy(LLVMContext &C)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isCall(QueryType Type=AnyInBundle) const
bool isArgument(unsigned Opc)
SlotIndex def
The index of the defining instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
This class represents lattice values for constants.
void removePhysRegDefAt(unsigned Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Segments::iterator iterator
bool isPhysRegModified(unsigned PhysReg, bool SkipNoReturnDef=false) const
Return true if the specified register is modified in this function.
void push_back(const T &Elt)
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
unsigned const TargetRegisterInfo * TRI
bool hasOneDef(unsigned RegNo) const
Return true if there is exactly one operand defining the specified register.
VNInfo - Value Number Information.
iterator_range< mop_iterator > operands()
use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static void query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
FunctionPass * createWebAssemblyRegStackify()
AnalysisUsage & addRequired()
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
static Type * getFloatTy(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse, const MachineBasicBlock &MBB, const MachineRegisterInfo &MRI, const MachineDominatorTree &MDT, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI)
Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const char * getSymbolName() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
unsigned getCalleeOpNo(unsigned Opc)
Returns the operand number of a callee, assuming the argument is a call instruction.
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
AnalysisUsage & addPreservedID(const void *ID)
void setReg(Register Reg)
Change the register this operand corresponds to.
bool isVRegStackified(unsigned VReg) const
static bool isSafeToMove(const MachineInstr *Def, const MachineInstr *Insert, AliasAnalysis &AA, const MachineRegisterInfo &MRI)
static bool shouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA, const WebAssemblyInstrInfo *TII)
unsigned getUndefRegState(bool B)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
TargetInstrInfo - Interface to description of machine instruction set.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
This file contains the declaration of the WebAssembly-specific utility functions. ...
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
static const unsigned CommuteAnyOperandIndex
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
MachineInstrBundleIterator< MachineInstr > iterator
static unsigned getTeeOpcode(const TargetRegisterClass *RC)
Get the appropriate tee opcode for the given register class.
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void removeInterval(unsigned Reg)
Interval removal.
bool liveAt(SlotIndex index) const
static MachineOperand CreateFPImm(const ConstantFP *CFP)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval *> &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
const GlobalValue * getGlobal() const
This file provides WebAssembly-specific target descriptions.
static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS)
Represent the analysis usage information of a pass.
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr *> *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses...
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr fully defines the specified register.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
FunctionPass class - This class is used to implement most global optimizations.
self_iterator getIterator()
LiveInterval & getInterval(Register Reg)
static void imposeStackOrdering(MachineInstr *MI)
void stackifyVReg(unsigned VReg)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
bool isDebugInstr() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static MachineInstr * getVRegDef(unsigned Reg, const MachineInstr *Insert, const MachineRegisterInfo &MRI, const LiveIntervals &LIS)
iterator_range< mop_iterator > explicit_uses()
void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified segment from this range.
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
This file declares the WebAssembly-specific subclass of TargetSubtarget.
Iterator for intrusive lists based on ilist_node.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
bool isDereferenceableInvariantLoad(AAResults *AA) const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
LLVM_NODISCARD T pop_back_val()
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
A range adaptor for a pair of iterators.
bool use_empty(unsigned RegNo) const
use_empty - Return true if there are no instructions using the specified register.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE, "Reorder instructions to use the WebAssembly value stack", false, false) FunctionPass *llvm
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
bool hasOneUse(unsigned RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
static MachineOperand CreateImm(int64_t Val)
static void queryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
This file declares WebAssembly-specific per-machine-function information.
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
This file contains the declaration of the WebAssembly-specific manager for DebugValues associated wit...
static MachineInstr * rematerializeCheapDef(unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI)
A trivially cloneable instruction; clone it and nest the new copy with the current instruction...
static MachineInstr * moveAndTeeForMultiUse(unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII)
A multiple-use def in the same block with no intervening memory or register dependencies; move the de...
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
StringRef - Represent a constant reference to a string, i.e.
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
Register getReg() const
getReg - Returns the register number.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const MachineOperand & getOperand(unsigned i) const
SlotIndex - An opaque wrapper around machine indexes.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool isAsCheapAsAMove(QueryType Type=AllInBundle) const
Returns true if this instruction has the same cost (or less) than a move instruction.
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block...
Wrapper class representing virtual and physical registers.
static MachineInstr * moveForSingleUse(unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI)
A single-use def in the same block with no intervening memory or register dependencies; move the def ...