29#define DEBUG_TYPE "si-i1-copies"
48 void markAsLaneMask(
Register DstReg)
const override;
49 void getCandidatesForLowering(
51 void collectIncomingValuesFromPhi(
62 bool lowerCopiesFromI1();
63 bool lowerCopiesToI1();
64 bool cleanConstrainRegs(
bool Changed);
66 return Reg.isVirtual() &&
MRI->getRegClass(
Reg) == &AMDGPU::VReg_1RegClass;
73 : PhiLoweringHelper(MF, DT, PDT) {}
75bool Vreg1LoweringHelper::cleanConstrainRegs(
bool Changed) {
79 ConstrainRegs.clear();
101 return !
TII.hasDivergentBranch(&Latch) &&
102 all_of(Header.predecessors(),
104 return Pred == &Latch || !DT.dominates(&Header, Pred);
148 : PDT(PDT), TII(TII) {}
153 return ReachableMap.find(&
MBB)->second;
161 ReachableMap.clear();
162 Predecessors.clear();
166 ReachableMap.try_emplace(&DefBlock,
false);
170 if (
MBB == &DefBlock) {
171 ReachableMap[&DefBlock] =
true;
177 if (TII->hasDivergentBranch(
MBB) && PDT.dominates(&DefBlock,
MBB))
181 while (!Stack.empty()) {
183 if (ReachableMap.try_emplace(
MBB,
false).second)
190 ReachableMap.try_emplace(
MBB,
false);
193 for (
auto &[
MBB, IsSource] : ReachableMap) {
194 bool HaveReachablePred =
false;
200 if (Pred == &DefBlock) {
203 return MI.getOpcode() == AMDGPU::SI_ELSE;
205 "SI_ELSE block in a cycle through the def block");
208 if (ReachableMap.count(Pred)) {
209 HaveReachablePred =
true;
211 Stack.push_back(Pred);
214 if (!HaveReachablePred)
216 if (HaveReachablePred) {
219 Predecessors.push_back(UnreachablePred);
284 unsigned FoundLoopLevel = ~0u;
293 : DT(DT), PDT(PDT), TII(TII) {}
297 CommonDominators.clear();
300 VisitedPostDom =
nullptr;
301 FoundLoopLevel = ~0u;
317 while (PDNode->
getBlock() != PostDom) {
318 if (PDNode->
getBlock() == VisitedPostDom)
322 if (FoundLoopLevel == Level)
342 if (!inLoopLevel(*Dom, LoopLevel, Incomings)) {
349 if (!inLoopLevel(*Pred, LoopLevel, Incomings))
357 bool inLoopLevel(MachineBasicBlock &
MBB,
unsigned LoopLevel,
359 auto DomIt = Visited.
find(&
MBB);
360 if (DomIt != Visited.
end() && DomIt->second <= LoopLevel)
363 for (
auto &Incoming : Incomings)
364 if (Incoming.Block == &
MBB)
370 void advanceLevel() {
371 MachineBasicBlock *VisitedDom;
373 if (!VisitedPostDom) {
374 VisitedPostDom = DefBlock;
375 VisitedDom = DefBlock;
376 Stack.push_back(DefBlock);
378 VisitedPostDom = PDT.
getNode(VisitedPostDom)->getIDom()->getBlock();
379 VisitedDom = CommonDominators.
back();
381 for (
unsigned i = 0; i < NextLevel.
size();) {
382 if (PDT.
dominates(VisitedPostDom, NextLevel[i])) {
383 Stack.push_back(NextLevel[i]);
385 NextLevel[i] = NextLevel.
back();
393 unsigned Level = CommonDominators.
size();
394 while (!
Stack.empty()) {
395 MachineBasicBlock *
MBB =
Stack.pop_back_val();
406 if (Succ == DefBlock) {
407 if (
MBB == VisitedPostDom)
408 FoundLoopLevel = std::min(FoundLoopLevel, Level + 1);
410 FoundLoopLevel = std::min(FoundLoopLevel, Level);
415 if (
MBB == VisitedPostDom)
418 Stack.push_back(Succ);
432 return MRI->createVirtualRegister(LaneMaskRegAttrs);
442 BuildMI(*
MBB,
MBB->getFirstTerminator(), {},
TII->get(AMDGPU::IMPLICIT_DEF),
456bool Vreg1LoweringHelper::lowerCopiesFromI1() {
458 SmallVector<MachineInstr *, 4> DeadCopies;
460 for (MachineBasicBlock &
MBB : MF) {
461 for (MachineInstr &
MI :
MBB) {
462 if (
MI.getOpcode() != AMDGPU::COPY)
467 if (!isVreg1(SrcReg))
470 if (isLaneMaskReg(DstReg) || isVreg1(DstReg))
480 assert(!
MI.getOperand(0).getSubReg());
482 ConstrainRegs.insert(SrcReg);
492 for (MachineInstr *
MI : DeadCopies)
493 MI->eraseFromParent();
504 MRI = &
MF.getRegInfo();
506 TII =
ST->getInstrInfo();
520 return DT.getNode(LHS.Block)->getDFSNumIn() <
521 DT.getNode(RHS.Block)->getDFSNumIn();
536 unsigned FoundLoopLevel = LF.
findLoop(PostDomBound);
540 if (FoundLoopLevel) {
598 if (Vreg1Phis.
empty())
604 DT.updateDFSNumbers();
624 MI->eraseFromParent();
631bool Vreg1LoweringHelper::lowerCopiesToI1() {
640 if (
MI.getOpcode() != AMDGPU::IMPLICIT_DEF &&
641 MI.getOpcode() != AMDGPU::COPY)
645 if (!isVreg1(DstReg))
650 if (
MRI->use_empty(DstReg)) {
657 markAsLaneMask(DstReg);
658 initializeLaneMaskRegisterAttributes(DstReg);
660 if (
MI.getOpcode() == AMDGPU::IMPLICIT_DEF)
665 assert(!
MI.getOperand(1).getSubReg());
667 if (!SrcReg.
isVirtual() || (!isLaneMaskReg(SrcReg) && !isVreg1(SrcReg))) {
668 assert(
TII->getRegisterInfo().getRegSizeInBits(SrcReg, *
MRI) == 32);
673 MI.getOperand(1).setReg(TmpReg);
677 MI.getOperand(1).setIsKill(
false);
682 std::vector<MachineBasicBlock *> DomBlocks = {&
MBB};
684 DomBlocks.push_back(
Use.getParent());
686 MachineBasicBlock *PostDomBound =
688 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
689 if (FoundLoopLevel) {
690 MachineIDFSSAUpdater SSAUpdater(DT, MF, DstReg);
693 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *
MRI, LaneMaskRegAttrs);
696 buildMergeLaneMasks(
MBB,
MI,
DL, DstReg,
702 for (MachineInstr *
MI : DeadCopies)
703 MI->eraseFromParent();
713 MI =
MRI->getVRegDef(Reg);
714 if (
MI->getOpcode() == AMDGPU::IMPLICIT_DEF)
717 if (
MI->getOpcode() != AMDGPU::COPY)
720 Reg =
MI->getOperand(1).getReg();
721 if (!Reg.isVirtual())
727 if (
MI->getOpcode() !=
LMC->MovOpc)
730 if (!
MI->getOperand(1).isImm())
733 int64_t
Imm =
MI->getOperand(1).getImm();
751 if (MO.isReg() && MO.getReg() == AMDGPU::SCC) {
764 auto InsertionPt =
MBB.getFirstTerminator();
765 bool TerminatorsUseSCC =
false;
766 for (
auto I = InsertionPt,
E =
MBB.end();
I !=
E; ++
I) {
769 if (TerminatorsUseSCC || DefsSCC)
773 if (!TerminatorsUseSCC)
776 while (InsertionPt !=
MBB.begin()) {
790void Vreg1LoweringHelper::markAsLaneMask(
Register DstReg)
const {
791 MRI->setRegClass(DstReg, ST->getBoolRC());
794void Vreg1LoweringHelper::getCandidatesForLowering(
798 if (isVreg1(
MI.getOperand(0).getReg()))
804void Vreg1LoweringHelper::collectIncomingValuesFromPhi(
805 const MachineInstr *
MI,
806 SmallVectorImpl<AMDGPU::Incoming> &Incomings)
const {
807 for (
unsigned i = 1; i <
MI->getNumOperands(); i += 2) {
808 assert(i + 1 <
MI->getNumOperands());
809 Register IncomingReg =
MI->getOperand(i).getReg();
810 MachineBasicBlock *IncomingMBB =
MI->getOperand(i + 1).getMBB();
813 if (IncomingDef->
getOpcode() == AMDGPU::COPY) {
815 assert(isLaneMaskReg(IncomingReg) || isVreg1(IncomingReg));
817 }
else if (IncomingDef->
getOpcode() == AMDGPU::IMPLICIT_DEF) {
820 assert(IncomingDef->
isPHI() || PhiRegisters.count(IncomingReg));
828 MachineBasicBlock *
MBB) {
832void Vreg1LoweringHelper::buildMergeLaneMasks(MachineBasicBlock &
MBB,
837 bool PrevVal =
false;
838 bool PrevConstant = isConstantLaneMask(PrevReg, PrevVal);
840 bool CurConstant = isConstantLaneMask(CurReg, CurVal);
842 if (PrevConstant && CurConstant) {
843 if (PrevVal == CurVal) {
859 if (CurConstant && CurVal) {
860 PrevMaskedReg = PrevReg;
871 if (PrevConstant && PrevVal) {
872 CurMaskedReg = CurReg;
882 if (PrevConstant && !PrevVal) {
885 }
else if (CurConstant && !CurVal) {
888 }
else if (PrevConstant && PrevVal) {
896 .
addReg(CurMaskedReg ? CurMaskedReg : LMC->ExecReg)
901void Vreg1LoweringHelper::constrainAsLaneMask(AMDGPU::Incoming &In) {}
918 Vreg1LoweringHelper Helper(MF, MDT, MPDT);
920 Changed |= Helper.lowerCopiesFromI1();
922 Changed |= Helper.lowerCopiesToI1();
923 return Helper.cleanConstrainRegs(
Changed);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use)
static Register insertUndefLaneMask(MachineBasicBlock *MBB, MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
static bool isExecInvariantBackEdge(const MachineBasicBlock &Latch, const MachineBasicBlock &Header, const MachineDominatorTree &DT, const SIInstrInfo &TII)
Return true if Latch -> Header is the only back-edge of a loop that is left as a whole,...
static bool runFixI1Copies(MachineFunction &MF, MachineDominatorTree &MDT, MachinePostDominatorTree &MPDT)
Lower all instructions that def or use vreg_1 registers.
static bool isVRegCompatibleReg(const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI, Register Reg)
Interface definition of the PhiLoweringHelper class that implements lane mask merging algorithm for d...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
Helper class that detects loops which require us to lower an i1 COPY into bitwise manipulation.
void initialize(MachineBasicBlock &MBB)
LoopFinder(MachineDominatorTree &DT, MachinePostDominatorTree &PDT, const SIInstrInfo *TII)
unsigned findLoop(MachineBasicBlock *PostDom)
Check whether a backward edge can be reached without going through the given PostDom of the def block...
void addLoopEntries(unsigned LoopLevel, MachineIDFSSAUpdater &SSAUpdater, MachineRegisterInfo &MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs, ArrayRef< AMDGPU::Incoming > Incomings={})
Add undef values dominating the loop and the optionally given additional blocks, so that the SSA upda...
Helper class that determines the relationship between incoming values of a phi in the control flow gr...
bool isSource(MachineBasicBlock &MBB) const
Returns whether MBB is a source in the induced subgraph of reachable blocks.
ArrayRef< MachineBasicBlock * > predecessors() const
PhiIncomingAnalysis(MachinePostDominatorTree &PDT, const SIInstrInfo *TII)
void analyze(MachineBasicBlock &DefBlock, ArrayRef< AMDGPU::Incoming > Incomings)
bool isLaneMaskReg(Register Reg) const
virtual void replaceDstReg(Register NewReg, Register OldReg, MachineBasicBlock *MBB)=0
MachineBasicBlock::iterator getSaluInsertionAtEnd(MachineBasicBlock &MBB) const
Return a point at the end of the given MBB to insert SALU instructions for lane mask calculation.
bool isConstantLaneMask(Register Reg, bool &Val) const
MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs
void initializeLaneMaskRegisterAttributes(Register LaneMask)
virtual void buildMergeLaneMasks(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, Register PrevReg, Register CurReg)=0
virtual void getCandidatesForLowering(SmallVectorImpl< MachineInstr * > &Vreg1Phis) const =0
const AMDGPU::LaneMaskConstants * LMC
PhiLoweringHelper(MachineFunction &MF, MachineDominatorTree &DT, MachinePostDominatorTree &PDT)
MachineRegisterInfo * MRI
MachineDominatorTree & DT
DenseSet< Register > PhiRegisters
virtual void markAsLaneMask(Register DstReg) const =0
virtual void constrainAsLaneMask(Incoming &In)=0
virtual void collectIncomingValuesFromPhi(const MachineInstr *MI, SmallVectorImpl< Incoming > &Incomings) const =0
void mergeIncomingLaneMasks(Register DstReg, MachineBasicBlock &MBB, SmallVectorImpl< Incoming > &Incomings, MachineIDFSSAUpdater &SSAUpdater, LoopFinder &LF, PhiIncomingAnalysis &PIA)
Merge the Incomings lane masks into DstReg, the value owned by MBB.
MachinePostDominatorTree & PDT
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Represents analyses that only rely on functions' control flow.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
DomTreeNodeBase * getIDom() const
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
FunctionPass class - This class is used to implement most global optimizations.
void push_back(MachineInstr *MI)
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass(char &ID)
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.
const MachineFunctionProperties & getProperties() const
Get the function properties.
LLVM_ABI Register getValueInMiddleOfBlock(MachineBasicBlock *BB)
See SSAUpdater::GetValueInMiddleOfBlock description.
void addAvailableValue(MachineBasicBlock *BB, Register V)
Indicate that a rewritten value is available in the specified block with the specified value.
LLVM_ABI void calculate()
Calculate and insert necessary PHI nodes for SSA form.
void addUseBlock(MachineBasicBlock *BB)
Record a basic block that uses the value.
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
LLVM_ABI MachineBasicBlock * findNearestCommonDominator(ArrayRef< MachineBasicBlock * > Blocks) const
Returns the nearest common dominator of the given blocks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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_instr_nodbg_iterator > use_nodbg_instructions(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.
This class implements a map that also provides access to all stored values in a deterministic order.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Wrapper class representing virtual and physical registers.
constexpr bool isValid() const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Helper class for SSA formation on a set of values defined in multiple blocks.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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.
Represent a constant reference to a string, i.e.
A Use represents the edge between a Value definition and its users.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Register createLaneMaskReg(MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
NodeAddr< UseNode * > Use
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
ArrayRef(const T &OneElt) -> ArrayRef< T >
FunctionPass * createSILowerI1CopiesLegacyPass()
char & SILowerI1CopiesLegacyID
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Incoming for lane mask phi as machine instruction, incoming register Reg and incoming block Block are...
MachineBasicBlock * Block
All attributes(register class or bank and low-level type) a virtual register can have.