65#define DEBUG_TYPE "si-lower-control-flow"
69class SILowerControlFlow {
85 bool EnableOptimizeEndCf =
false;
120 while (
I !=
End && !
I->isUnconditionalBranch())
126 void optimizeEndCf();
145 return "SI Lower control flow pseudo instructions";
163char SILowerControlFlowLegacy::ID = 0;
177 setImpSCCDefDead(
MI, OrigSCCDef.
isDead());
184 DenseSet<const MachineBasicBlock*> Visited;
185 SmallVector<MachineBasicBlock *, 4> Worklist(Begin->
successors());
187 while (!Worklist.empty()) {
188 MachineBasicBlock *
MBB = Worklist.pop_back_val();
192 if (KillBlocks.contains(
MBB))
202 Register SaveExecReg =
MI.getOperand(0).getReg();
203 auto U =
MRI->use_instr_nodbg_begin(SaveExecReg);
205 if (U ==
MRI->use_instr_nodbg_end() ||
206 std::next(U) !=
MRI->use_instr_nodbg_end() ||
207 U->getOpcode() != AMDGPU::SI_END_CF)
213void SILowerControlFlow::emitIf(MachineInstr &
MI) {
217 Register SaveExecReg =
MI.getOperand(0).getReg();
218 MachineOperand&
Cond =
MI.getOperand(1);
219 assert(
Cond.getSubReg() == AMDGPU::NoSubRegister);
235 Register CopyReg = SimpleIf ? SaveExecReg
237 MachineInstr *CopyExec =
BuildMI(
MBB,
I,
DL,
TII->get(AMDGPU::COPY), CopyReg)
240 LoweredIf.
insert(CopyReg);
246 setImpSCCDefDead(*
And);
248 MachineInstr *
Xor =
nullptr;
253 copySCCDefDead(*
Xor,
MI.getOperand(4));
258 MachineInstr *SetExec =
263 I = skipToUncondBrOrEnd(
MBB,
I);
267 MachineInstr *NewBr =
BuildMI(
MBB,
I,
DL,
TII->get(AMDGPU::S_CBRANCH_EXECZ))
268 .
add(
MI.getOperand(2));
271 MI.eraseFromParent();
286 MI.eraseFromParent();
291 RecomputeRegs.insert(SaveExecReg);
297void SILowerControlFlow::emitElse(MachineInstr &
MI) {
309 MachineInstr *OrSaveExec =
311 .
add(
MI.getOperand(1));
312 setImpSCCDefDead(*OrSaveExec,
true);
314 MachineBasicBlock *DestBB =
MI.getOperand(2).getMBB();
323 setImpSCCDefDead(*
And,
true);
329 copySCCDefDead(*
Xor,
MI.getOperand(4));
333 ElsePt = skipToUncondBrOrEnd(
MBB, ElsePt);
340 MI.eraseFromParent();
345 MI.eraseFromParent();
353 RecomputeRegs.insert(SrcReg);
354 RecomputeRegs.insert(DstReg);
358void SILowerControlFlow::emitIfBreak(MachineInstr &
MI) {
361 auto Dst =
MI.getOperand(0).getReg();
367 bool SkipAnding =
false;
368 if (
MI.getOperand(1).isReg()) {
370 SkipAnding =
Def->getParent() ==
MI.getParent() &&
377 MachineInstr *
And =
nullptr, *
Or =
nullptr;
383 .
add(
MI.getOperand(1));
384 setImpSCCDefDead(*
And,
true);
387 .
add(
MI.getOperand(2));
390 .
add(
MI.getOperand(1))
391 .
add(
MI.getOperand(2));
394 copySCCDefDead(*
Or,
MI.getOperand(3));
400 RecomputeRegs.insert(
And->getOperand(2).getReg());
406 MI.eraseFromParent();
409void SILowerControlFlow::emitLoop(MachineInstr &
MI) {
413 MachineInstr *AndN2 =
416 .
add(
MI.getOperand(0));
417 copySCCDefDead(*AndN2,
MI.getOperand(3));
422 .
add(
MI.getOperand(1));
425 RecomputeRegs.insert(
MI.getOperand(0).getReg());
430 MI.eraseFromParent();
434SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
437 SmallPtrSet<const MachineBasicBlock *, 4> Visited;
438 MachineBasicBlock *
B = &
MBB;
444 for ( ; It !=
E; ++It) {
445 if (
TII->mayReadEXEC(*
MRI, *It))
452 if (
B->succ_size() != 1)
456 MachineBasicBlock *Succ = *
B->succ_begin();
463MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &
MI) {
472 bool NeedBlockSplit =
false;
476 if (
I->modifiesRegister(DataReg,
TRI)) {
477 NeedBlockSplit =
true;
482 unsigned Opcode = LMC.
OrOpc;
483 MachineBasicBlock *SplitBB = &
MBB;
484 if (NeedBlockSplit) {
486 if (SplitBB != &
MBB && (MDT || PDT)) {
489 for (MachineBasicBlock *Succ : SplitBB->
successors()) {
490 DTUpdates.
push_back({DomTreeT::Insert, SplitBB, Succ});
505 .
add(
MI.getOperand(0));
506 copySCCDefDead(*NewMI,
MI.getOperand(2));
508 LoweredEndCf.
insert(NewMI);
513 MI.eraseFromParent();
522void SILowerControlFlow::findMaskOperands(
523 MachineInstr &
MI,
unsigned OpNo,
524 SmallVectorImpl<MachineOperand *> &Src)
const {
525 MachineOperand &
Op =
MI.getOperand(OpNo);
526 if (!
Op.isReg() || !
Op.getReg().isVirtual()) {
532 if (!Def ||
Def->getParent() !=
MI.getParent() ||
533 !(
Def->isFullCopy() || (
Def->getOpcode() ==
MI.getOpcode())))
539 for (
auto I =
Def->getIterator();
I !=
MI.getIterator(); ++
I)
540 if (
I->modifiesRegister(AMDGPU::EXEC,
TRI) &&
541 !(
I->isCopy() &&
I->getOperand(0).getReg() != LMC.
ExecReg))
544 for (MachineOperand &SrcOp :
Def->explicit_operands())
545 if (SrcOp.isReg() && SrcOp.isUse() &&
546 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == LMC.
ExecReg))
547 Src.push_back(&SrcOp);
554void SILowerControlFlow::combineMasks(MachineInstr &
MI) {
555 assert(
MI.getNumExplicitOperands() == 3);
557 findMaskOperands(
MI, 1, Src1);
558 findMaskOperands(
MI, 2, Src2);
562 unsigned OpToReplace;
563 MachineOperand *Leaf, *NestedLHS, *NestedRHS;
564 if (
Src1.size() == 2 &&
Src2.size() == 1) {
569 }
else if (
Src1.size() == 1 &&
Src2.size() == 2) {
579 MachineOperand *KeepOp;
589 MI.removeOperand(OpToReplace);
590 MI.addOperand(*KeepOp);
595void SILowerControlFlow::optimizeEndCf() {
598 if (!EnableOptimizeEndCf)
601 for (MachineInstr *
MI :
reverse(LoweredEndCf)) {
604 skipIgnoreExecInstsTrivialSucc(
MBB, std::next(
MI->getIterator()));
610 =
TII->getNamedOperand(*
Next, AMDGPU::OpName::src1)->getReg();
614 if (Def && LoweredIf.
count(SavedExec)) {
618 MI->eraseFromParent();
619 removeMBBifRedundant(
MBB);
624MachineBasicBlock *SILowerControlFlow::process(MachineInstr &
MI) {
627 MachineInstr *Prev = (
I !=
MBB.
begin()) ? &*(std::prev(
I)) : nullptr;
629 MachineBasicBlock *SplitBB = &
MBB;
631 switch (
MI.getOpcode()) {
636 case AMDGPU::SI_ELSE:
640 case AMDGPU::SI_IF_BREAK:
644 case AMDGPU::SI_LOOP:
648 case AMDGPU::SI_WATERFALL_LOOP:
649 MI.setDesc(
TII->get(AMDGPU::S_CBRANCH_EXECNZ));
652 case AMDGPU::SI_END_CF:
653 SplitBB = emitEndCf(
MI);
657 assert(
false &&
"Attempt to process unsupported instruction");
664 MachineInstr &MaskMI = *
I;
666 case AMDGPU::S_AND_B64:
667 case AMDGPU::S_OR_B64:
668 case AMDGPU::S_AND_B32:
669 case AMDGPU::S_OR_B32:
671 combineMasks(MaskMI);
682bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &
MBB) {
684 if (!
I.isDebugInstr() && !
I.isUnconditionalBranch())
691 MachineBasicBlock *FallThrough =
nullptr;
698 if (
P->getFallThrough(
false) == &
MBB)
701 DTUpdates.
push_back({DomTreeT::Insert,
P, Succ});
716 RecomputeRegs.insert(
Reg);
740 MachineInstr *BranchMI =
BuildMI(*FallThrough, FallThrough->
end(),
752 TII =
ST.getInstrInfo();
754 EnableOptimizeEndCf =
ST.getCLOpts().remove_redundant_endcf &&
758 BoolRC =
TRI->getBoolRC();
761 const bool CanDemote =
763 for (
auto &
MBB : MF) {
764 bool IsKillBlock =
false;
766 if (
TII->isKillTerminator(
Term.getOpcode())) {
767 KillBlocks.insert(&
MBB);
772 if (CanDemote && !IsKillBlock) {
773 for (
auto &
MI :
MBB) {
774 if (
MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
775 KillBlocks.insert(&
MBB);
785 BI != MF.end(); BI = NextBB) {
786 NextBB = std::next(BI);
787 MachineBasicBlock *
MBB = &*BI;
793 MachineInstr &
MI = *
I;
794 MachineBasicBlock *SplitMBB =
MBB;
796 switch (
MI.getOpcode()) {
798 case AMDGPU::SI_ELSE:
799 case AMDGPU::SI_IF_BREAK:
800 case AMDGPU::SI_WATERFALL_LOOP:
801 case AMDGPU::SI_LOOP:
802 case AMDGPU::SI_END_CF:
803 SplitMBB = process(
MI);
808 if (SplitMBB !=
MBB) {
827 RecomputeRegs.clear();
828 LoweredEndCf.
clear();
835bool SILowerControlFlowLegacy::runOnMachineFunction(
MachineFunction &MF) {
838 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
839 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() :
nullptr;
840 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
841 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() :
nullptr;
843 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
844 MachinePostDominatorTree *PDT =
845 PDTWrapper ? &PDTWrapper->getPostDomTree() :
nullptr;
846 return SILowerControlFlow(ST, LIS, MDT, PDT).run(MF);
859 bool Changed = SILowerControlFlow(ST, LIS, MDT, PDT).run(MF);
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI)
static const LaneMaskConstants & get(const GCNSubtarget &ST)
const unsigned XorTermOpc
const unsigned MovTermOpc
const unsigned OrSaveExecOpc
const unsigned AndN2TermOpc
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Implements a dense probed hash-table based set.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
const HexagonRegisterInfo & getRegisterInfo() const
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndexes * getSlotIndexes() const
void RemoveMachineInstrFromMaps(MachineInstr &MI)
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
bool liveAt(SlotIndex index) const
succ_iterator succ_begin()
unsigned succ_size() const
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
pred_iterator pred_begin()
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
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...
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.
BasicBlockListType::iterator iterator
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
void clear()
Completely clear the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
LLVM_ABI void removeMBBFromMaps(MachineBasicBlock &MBB)
Inverse of insertMBBInMaps: merge MBB's slot range into its layout predecessor and drop it from the m...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
self_iterator getIterator()
NodeAddr< DefNode * > Def
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
char & SILowerControlFlowLegacyID
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
DWARFExpression::Operation Op
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
@ End
Run the machine verifier once, at the end of the pipeline.
MCRegisterClass TargetRegisterClass