[llvm] [CodeGenPrepare] Identify tail calls for reassembled aggregates (PR #219702)
via llvm-commits
llvm-commits at lists.llvm.org
Sat Aug 29 10:09:16 PDT 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-transforms
Author: Jinpeng Wang (jjppp)
<details>
<summary>Changes</summary>
After aggregate scalarization, a direct call-to-return sequence prevents the existing return duplication logic from recognizing tail calls.
This PR recognizes this pattern and duplicate returns for aggregate values that are reassembled from the result of a tail call.
For each matching predecessor:
- verifies that every struct field comes from the corresponding extractvalue of the same call;
- requires the insertvalue chain to fully construct the returned struct from undef or poison;
- duplicates the return into the predecessor and returns the original call result directly.
Fixes #<!-- -->219486
---
Full diff: https://github.com/llvm/llvm-project/pull/219702.diff
2 Files Affected:
- (modified) llvm/lib/CodeGen/CodeGenPrepare.cpp (+106-11)
- (added) llvm/test/Transforms/CodeGenPrepare/X86/tailcall-dup-aggregate-ret.ll (+74)
``````````diff
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 22dd55f0b040a..1bda1a8be220d 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -2935,6 +2935,67 @@ static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo,
return false;
}
+/// Check whether, on the path through predecessor \p Pred, \p FieldValues
+/// exactly reassembles the aggregate return value of a single call in
+/// \p Pred (each field is an extractvalue of the same call at the same
+/// index). Returns that call, or null if the pattern does not match.
+static CallInst *findTailCallReassembledInPred(ArrayRef<Value *> FieldValues,
+ BasicBlock *BB,
+ BasicBlock *Pred) {
+ CallInst *CallSource = nullptr;
+ for (unsigned Index = 0; Index < FieldValues.size(); ++Index) {
+ Value *V = FieldValues[Index];
+ if (auto *PN = dyn_cast<PHINode>(V)) {
+ if (PN->getParent() != BB)
+ return nullptr;
+ V = PN->getIncomingValueForBlock(Pred);
+ }
+ auto *EVI = dyn_cast<ExtractValueInst>(V);
+ if (!EVI || EVI->getParent() != Pred || !EVI->hasOneUse() ||
+ EVI->getNumIndices() != 1 || EVI->getIndices()[0] != Index)
+ return nullptr;
+ auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
+ if (!CI || CI->getParent() != Pred || (CallSource && CallSource != CI))
+ return nullptr;
+ CallSource = CI;
+ }
+ // The extractvalues found above are distinct (they use distinct indices),
+ // so requiring exactly that many uses guarantees the call has no other
+ // uses and its whole return value flows into the return. The type check
+ // rules out calls returning a larger struct with matching leading fields.
+ if (!CallSource || CallSource->getNumUses() != FieldValues.size() ||
+ CallSource->getType() != BB->getParent()->getReturnType())
+ return nullptr;
+ return CallSource;
+}
+
+/// Parse a chain of insertvalues in \p BB that fully constructs a struct
+/// starting from undef/poison. On success, FieldValues[I] holds the value
+/// inserted at field index I and \p ChainInsts holds the instructions.
+static bool
+collectInsertValueChain(Value *V, BasicBlock *BB,
+ SmallVectorImpl<Value *> &FieldValues,
+ SmallPtrSetImpl<Instruction *> &ChainInsts) {
+ StructType *Ty = dyn_cast<StructType>(V->getType());
+ if (!Ty)
+ return false;
+ unsigned NumIndices = Ty->getNumElements(), CoveredIndices = 0;
+ FieldValues.assign(NumIndices, nullptr);
+ while (auto *IVI = dyn_cast<InsertValueInst>(V)) {
+ if (IVI->getParent() != BB || !IVI->hasOneUse() ||
+ IVI->getNumIndices() != 1)
+ return false;
+ unsigned Index = IVI->getIndices()[0];
+ if (FieldValues[Index] == nullptr) {
+ FieldValues[Index] = IVI->getInsertedValueOperand();
+ CoveredIndices++;
+ }
+ ChainInsts.insert(IVI);
+ V = IVI->getAggregateOperand();
+ }
+ return isa<UndefValue>(V) && CoveredIndices == NumIndices;
+}
+
/// Look for opportunities to duplicate return instructions to the predecessor
/// to enable tail call optimizations. The case it is currently looking for is
/// the following one. Known intrinsics or library function that may be tail
@@ -2981,20 +3042,33 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
PHINode *PN = nullptr;
ExtractValueInst *EVI = nullptr;
BitCastInst *BCI = nullptr;
+ // Set if the return value is an insertvalue chain reassembling a struct,
+ // e.g. from `ret {i64, i32} %agg` where %agg is built up by insertvalues
+ // whose field values are (phis of) extractvalues of calls.
+ SmallVector<Value *, 4> FieldValues;
+ SmallPtrSet<Instruction *, 4> ChainInsts;
+ bool IsAggregateReturn = false;
Value *V = RetI->getReturnValue();
if (V) {
BCI = dyn_cast<BitCastInst>(V);
if (BCI)
V = BCI->getOperand(0);
- EVI = dyn_cast<ExtractValueInst>(V);
- if (EVI) {
- V = EVI->getOperand(0);
- if (!llvm::all_of(EVI->indices(), equal_to(0)))
- return false;
- }
+ if (isa<InsertValueInst>(V)) {
+ if (collectInsertValueChain(V, BB, FieldValues, ChainInsts))
+ IsAggregateReturn = true;
+ else
+ ChainInsts.clear();
+ } else {
+ EVI = dyn_cast<ExtractValueInst>(V);
+ if (EVI) {
+ V = EVI->getOperand(0);
+ if (!llvm::all_of(EVI->indices(), equal_to(0)))
+ return false;
+ }
- PN = dyn_cast<PHINode>(V);
+ PN = dyn_cast<PHINode>(V);
+ }
}
if (PN && PN->getParent() != BB)
@@ -3034,9 +3108,10 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
// Make sure there are no instructions between the first instruction
// and return.
BasicBlock::const_iterator BI = BB->getFirstNonPHIIt();
- // Skip over pseudo-probes and the bitcast.
+ // Skip over pseudo-probes, the bitcast and the insertvalue chain.
while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
- isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
+ isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI) ||
+ ChainInsts.contains(&*BI))
BI = std::next(BI);
if (&*BI != RetI)
return false;
@@ -3049,10 +3124,25 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
};
SmallVector<BasicBlock *, 4> TailCallBBs;
+ // For the aggregate-return case, the call whose return value is
+ // reassembled on the path through each candidate predecessor.
+ SmallDenseMap<BasicBlock *, CallInst *, 4> AggregateCalls;
// Record the call instructions so we can insert any fake uses
// that need to be preserved before them.
SmallVector<CallInst *, 4> CallInsts;
- if (PN) {
+ if (IsAggregateReturn) {
+ SmallPtrSet<BasicBlock *, 4> VisitedBBs;
+ for (BasicBlock *Pred : predecessors(BB)) {
+ if (!VisitedBBs.insert(Pred).second)
+ continue;
+ CallInst *CI = findTailCallReassembledInPred(FieldValues, BB, Pred);
+ if (CI && MayBePermittedAsTailCall(CI)) {
+ TailCallBBs.push_back(Pred);
+ AggregateCalls[Pred] = CI;
+ CallInsts.push_back(CI);
+ }
+ }
+ } else if (PN) {
for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
// Look through bitcasts.
Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
@@ -3117,7 +3207,12 @@ bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
continue;
// Duplicate the return into TailCallBB.
- (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
+ ReturnInst *NewRet = FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
+ // For the aggregate-return case, the duplicated return still refers to
+ // the insertvalue chain in BB. Return the call's result directly instead,
+ // which is equivalent on this path and enables the tail call.
+ if (IsAggregateReturn)
+ NewRet->setOperand(0, AggregateCalls.lookup(TailCallBB));
assert(!VerifyBFIUpdates ||
BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
BFI->setBlockFreq(BB,
diff --git a/llvm/test/Transforms/CodeGenPrepare/X86/tailcall-dup-aggregate-ret.ll b/llvm/test/Transforms/CodeGenPrepare/X86/tailcall-dup-aggregate-ret.ll
new file mode 100644
index 0000000000000..a93ff3818947d
--- /dev/null
+++ b/llvm/test/Transforms/CodeGenPrepare/X86/tailcall-dup-aggregate-ret.ll
@@ -0,0 +1,74 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt -passes='require<profile-summary>,function(codegenprepare)' -S -mtriple=x86_64-linux < %s | FileCheck %s
+
+define { i64, i32 } @recurse(ptr %__break.coerce, ptr nofree noundef readonly captures(address) %__root, i32 %__func.coerce) {
+; CHECK-LABEL: @recurse(
+; CHECK-NEXT: entry:
+; CHECK-NEXT: [[TMP0:%.*]] = load ptr, ptr [[__ROOT:%.*]], align 8
+; CHECK-NEXT: [[TOBOOL_NOT:%.*]] = icmp eq ptr [[TMP0]], null
+; CHECK-NEXT: br i1 [[TOBOOL_NOT]], label [[IF_END14:%.*]], label [[IF_THEN:%.*]]
+; CHECK: if.then:
+; CHECK-NEXT: [[CALL:%.*]] = tail call { i64, i32 } @recurse(ptr [[__BREAK_COERCE:%.*]], ptr noundef nonnull [[TMP0]], i32 [[__FUNC_COERCE:%.*]])
+; CHECK-NEXT: [[CALL_FCA_0_EXTRACT:%.*]] = extractvalue { i64, i32 } [[CALL]], 0
+; CHECK-NEXT: [[CALL_FCA_1_EXTRACT:%.*]] = extractvalue { i64, i32 } [[CALL]], 1
+; CHECK-NEXT: [[TOBOOL10_NOT_NOT:%.*]] = icmp eq i64 [[CALL_FCA_0_EXTRACT]], 0
+; CHECK-NEXT: br i1 [[TOBOOL10_NOT_NOT]], label [[IF_END14]], label [[RETURN:%.*]]
+; CHECK: if.end14:
+; CHECK-NEXT: [[__FUNC_SROA_0_0:%.*]] = phi i32 [ [[__FUNC_COERCE]], [[ENTRY:%.*]] ], [ [[CALL_FCA_1_EXTRACT]], [[IF_THEN]] ]
+; CHECK-NEXT: [[CMP_I:%.*]] = icmp eq ptr [[__ROOT]], [[__BREAK_COERCE]]
+; CHECK-NEXT: br i1 [[CMP_I]], label [[RETURN]], label [[IF_END18:%.*]]
+; CHECK: if.end18:
+; CHECK-NEXT: [[INC_I_I:%.*]] = add nsw i32 [[__FUNC_SROA_0_0]], 1
+; CHECK-NEXT: [[__RIGHT_:%.*]] = getelementptr inbounds nuw i8, ptr [[__ROOT]], i64 8
+; CHECK-NEXT: [[TMP1:%.*]] = load ptr, ptr [[__RIGHT_]], align 8
+; CHECK-NEXT: [[TOBOOL21_NOT:%.*]] = icmp eq ptr [[TMP1]], null
+; CHECK-NEXT: br i1 [[TOBOOL21_NOT]], label [[RETURN]], label [[IF_THEN22:%.*]]
+; CHECK: if.then22:
+; CHECK-NEXT: [[CALL29:%.*]] = tail call { i64, i32 } @recurse(ptr [[__BREAK_COERCE]], ptr noundef nonnull [[TMP1]], i32 [[INC_I_I]])
+; CHECK-NEXT: [[CALL29_FCA_0_EXTRACT:%.*]] = extractvalue { i64, i32 } [[CALL29]], 0
+; CHECK-NEXT: [[CALL29_FCA_1_EXTRACT:%.*]] = extractvalue { i64, i32 } [[CALL29]], 1
+; CHECK-NEXT: ret { i64, i32 } [[CALL29]]
+; CHECK: return:
+; CHECK-NEXT: [[RETVAL_SROA_0_1:%.*]] = phi i64 [ 1, [[IF_THEN]] ], [ 1, [[IF_END14]] ], [ 0, [[IF_END18]] ]
+; CHECK-NEXT: [[RETVAL_SROA_5_1:%.*]] = phi i32 [ [[CALL_FCA_1_EXTRACT]], [[IF_THEN]] ], [ [[__FUNC_SROA_0_0]], [[IF_END14]] ], [ [[INC_I_I]], [[IF_END18]] ]
+; CHECK-NEXT: [[DOTFCA_0_INSERT:%.*]] = insertvalue { i64, i32 } poison, i64 [[RETVAL_SROA_0_1]], 0
+; CHECK-NEXT: [[DOTFCA_1_INSERT:%.*]] = insertvalue { i64, i32 } [[DOTFCA_0_INSERT]], i32 [[RETVAL_SROA_5_1]], 1
+; CHECK-NEXT: ret { i64, i32 } [[DOTFCA_1_INSERT]]
+;
+entry:
+ %0 = load ptr, ptr %__root, align 8
+ %tobool.not = icmp eq ptr %0, null
+ br i1 %tobool.not, label %if.end14, label %if.then
+
+if.then:
+ %call = tail call { i64, i32 } @recurse(ptr %__break.coerce, ptr noundef nonnull %0, i32 %__func.coerce)
+ %call.fca.0.extract = extractvalue { i64, i32 } %call, 0
+ %call.fca.1.extract = extractvalue { i64, i32 } %call, 1
+ %tobool10.not.not = icmp eq i64 %call.fca.0.extract, 0
+ br i1 %tobool10.not.not, label %if.end14, label %return
+
+if.end14:
+ %__func.sroa.0.0 = phi i32 [ %__func.coerce, %entry ], [ %call.fca.1.extract, %if.then ]
+ %cmp.i = icmp eq ptr %__root, %__break.coerce
+ br i1 %cmp.i, label %return, label %if.end18
+
+if.end18:
+ %inc.i.i = add nsw i32 %__func.sroa.0.0, 1
+ %__right_ = getelementptr inbounds nuw i8, ptr %__root, i64 8
+ %1 = load ptr, ptr %__right_, align 8
+ %tobool21.not = icmp eq ptr %1, null
+ br i1 %tobool21.not, label %return, label %if.then22
+
+if.then22:
+ %call29 = tail call { i64, i32 } @recurse(ptr %__break.coerce, ptr noundef nonnull %1, i32 %inc.i.i)
+ %call29.fca.0.extract = extractvalue { i64, i32 } %call29, 0
+ %call29.fca.1.extract = extractvalue { i64, i32 } %call29, 1
+ br label %return
+
+return:
+ %retval.sroa.0.1 = phi i64 [ 1, %if.then ], [ 1, %if.end14 ], [ %call29.fca.0.extract, %if.then22 ], [ 0, %if.end18 ]
+ %retval.sroa.5.1 = phi i32 [ %call.fca.1.extract, %if.then ], [ %__func.sroa.0.0, %if.end14 ], [ %call29.fca.1.extract, %if.then22 ], [ %inc.i.i, %if.end18 ]
+ %.fca.0.insert = insertvalue { i64, i32 } poison, i64 %retval.sroa.0.1, 0
+ %.fca.1.insert = insertvalue { i64, i32 } %.fca.0.insert, i32 %retval.sroa.5.1, 1
+ ret { i64, i32 } %.fca.1.insert
+}
``````````
</details>
https://github.com/llvm/llvm-project/pull/219702
More information about the llvm-commits
mailing list