Skip to content

[BranchFolding] Add an optional target hook to skip branch folding when it's unsafe #147029

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions llvm/include/llvm/CodeGen/TargetInstrInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -2335,6 +2335,12 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
llvm_unreachable("unknown number of operands necessary");
}

/// Return false if \p MBB whose any predecessor is not analyzable is not safe
/// to do \p BranchFolding.
virtual bool isMBBSafeToBranchFolding(const MachineBasicBlock &MBB) const {
return true;
}

private:
mutable std::unique_ptr<MIRFormatter> Formatter;
unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
Expand Down
16 changes: 16 additions & 0 deletions llvm/lib/CodeGen/BranchFolding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1346,6 +1346,19 @@ static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII,
copyDebugInfoToPredecessor(TII, MBB, *PredBB);
}

static bool areAllPredsAnalyzable(const llvm::TargetInstrInfo *TII,
MachineBasicBlock *MBB) {
for (auto itr = MBB->pred_begin(); itr != MBB->pred_end(); ++itr) {
MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
SmallVector<MachineOperand, 4> CurCond;
bool CantAnalyzable = TII->analyzeBranch(**itr, CurTBB, CurFBB, CurCond,
/*AllowModify*/ false);
if (CantAnalyzable)
return false;
}
return true;
}

bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
bool MadeChange = false;
MachineFunction &MF = *MBB->getParent();
Expand Down Expand Up @@ -1389,6 +1402,9 @@ bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
// TODO: Is it ever worth rewriting predecessors which don't already
// jump to a landing pad, and so can safely jump to the fallthrough?
} else if (MBB->isSuccessor(&*FallThrough)) {
if (!TII->isMBBSafeToBranchFolding(*MBB) &&
!areAllPredsAnalyzable(TII, MBB))
return MadeChange;
// Rewrite all predecessors of the old block to go to the fallthrough
// instead.
while (!MBB->pred_empty()) {
Expand Down
Loading