[llvm] [CGP] Sink and duplicate call for tail position when duplicating return (PR #172882)
Antonio Frighetto via llvm-commits
llvm-commits at lists.llvm.org
Tue Jan 20 03:30:35 PST 2026
================
@@ -3084,24 +3084,87 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
}
bool Changed = false;
- for (auto const &TailCallBB : TailCallBBs) {
+ BasicBlock *BBToSinkCall = nullptr;
+
+ // If we haven't found any tail call opportunity yet, but we know the return
+ // value of function call is being returned, then in triangle-like if/then it
+ // may be profitable to sink the call in one branch and duplicate it in the
+ // current return block, so that the duplicated call is in tail position.
+ if (auto *CI = dyn_cast_or_null<CallInst>(V);
+ CI && RetToDuplicateBBs.empty() && pred_size(BB) == 2) {
+ if (!CI->hasOneUse() || CI->cannotDuplicate() || CI->isConvergent() ||
+ !mayBePermittedAsTailCall(CI))
+ return Changed;
+
+ auto It = std::next(CI->getIterator());
+ while (isa<PseudoProbeInst>(It) || isLifetimeEndOrBitCastFor(&*It) ||
+ isFakeUse(&*It))
+ It = std::next(It);
+
+ // No instructions in between.
+ auto *CIBBTerm = CI->getParent()->getTerminator();
+ if (&*It != CIBBTerm)
+ return Changed;
+
+ auto *BI = dyn_cast<BranchInst>(CIBBTerm);
+ if (!BI || !BI->isConditional())
+ return Changed;
+
+ if (BI->getSuccessor(0) == BB)
+ BBToSinkCall = BI->getSuccessor(1);
+ else if (BI->getSuccessor(1) == BB)
+ BBToSinkCall = BI->getSuccessor(0);
+ else
+ return Changed;
+
+ // Maybe found a candidate block to sink the call into.
+ RetToDuplicateBBs.emplace_back(BBToSinkCall);
+ }
+
+ for (const auto &RetToDupBB : RetToDuplicateBBs) {
// Make sure the call instruction is followed by an unconditional branch to
// the return block.
- BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
+ BranchInst *BI = dyn_cast<BranchInst>(RetToDupBB->getTerminator());
if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
continue;
- // Duplicate the return into TailCallBB.
- (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
+ // Duplicate the return into RetToDupBB.
+ (void)FoldReturnIntoUncondBranch(RetI, BB, RetToDupBB);
assert(!VerifyBFIUpdates ||
- BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
+ BFI->getBlockFreq(BB) >= BFI->getBlockFreq(RetToDupBB));
BFI->setBlockFreq(BB,
- (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
+ (BFI->getBlockFreq(BB) - BFI->getBlockFreq(RetToDupBB)));
ModifiedDT = ModifyDT::ModifyBBDT;
Changed = true;
++NumRetsDup;
}
+ if (Changed && BBToSinkCall) {
----------------
antoniofrighetto wrote:
Added, thanks.
https://github.com/llvm/llvm-project/pull/172882
More information about the llvm-commits
mailing list