Skip to content

Commit 2dc32f6

Browse files
committed
[TailRecursionElim] Adjust function entry count
1 parent d659046 commit 2dc32f6

File tree

4 files changed

+184
-11
lines changed

4 files changed

+184
-11
lines changed

llvm/include/llvm/Transforms/Scalar/TailRecursionElimination.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,12 @@ namespace llvm {
5858

5959
class Function;
6060

61-
struct TailCallElimPass : PassInfoMixin<TailCallElimPass> {
61+
class TailCallElimPass : public PassInfoMixin<TailCallElimPass> {
62+
const bool UpdateFunctionEntryCount;
63+
64+
public:
65+
TailCallElimPass(bool UpdateFunctionEntryCount = true)
66+
: UpdateFunctionEntryCount(UpdateFunctionEntryCount) {}
6267
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
6368
};
6469
}

llvm/lib/Passes/PassBuilderPipelines.cpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,10 @@ PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
628628
!Level.isOptimizingForSize())
629629
FPM.addPass(PGOMemOPSizeOpt());
630630

631-
FPM.addPass(TailCallElimPass());
631+
FPM.addPass(
632+
TailCallElimPass(/*UpdateFunctionEntryCount=*/(
633+
PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
634+
!UseCtxProfile.empty()));
632635
FPM.addPass(
633636
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
634637

@@ -1581,7 +1584,10 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
15811584
OptimizePM.addPass(DivRemPairsPass());
15821585

15831586
// Try to annotate calls that were created during optimization.
1584-
OptimizePM.addPass(TailCallElimPass());
1587+
OptimizePM.addPass(
1588+
TailCallElimPass(/*UpdateFunctionEntryCount=*/(
1589+
PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
1590+
!UseCtxProfile.empty()));
15851591

15861592
// LoopSink (and other loop passes since the last simplifyCFG) might have
15871593
// resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
@@ -2069,7 +2075,10 @@ PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
20692075

20702076
// LTO provides additional opportunities for tailcall elimination due to
20712077
// link-time inlining, and visibility of nocapture attribute.
2072-
FPM.addPass(TailCallElimPass());
2078+
FPM.addPass(
2079+
TailCallElimPass(/*UpdateFunctionEntryCount=*/(
2080+
PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2081+
!UseCtxProfile.empty()));
20732082

20742083
// Run a few AA driver optimizations here and now to cleanup the code.
20752084
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),

llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
#include "llvm/ADT/STLExtras.h"
5454
#include "llvm/ADT/SmallPtrSet.h"
5555
#include "llvm/ADT/Statistic.h"
56+
#include "llvm/Analysis/BlockFrequencyInfo.h"
5657
#include "llvm/Analysis/DomTreeUpdater.h"
5758
#include "llvm/Analysis/GlobalsModRef.h"
5859
#include "llvm/Analysis/InstructionSimplify.h"
@@ -75,6 +76,7 @@
7576
#include "llvm/IR/Module.h"
7677
#include "llvm/InitializePasses.h"
7778
#include "llvm/Pass.h"
79+
#include "llvm/Support/CommandLine.h"
7880
#include "llvm/Support/Debug.h"
7981
#include "llvm/Support/raw_ostream.h"
8082
#include "llvm/Transforms/Scalar.h"
@@ -87,6 +89,11 @@ STATISTIC(NumEliminated, "Number of tail calls removed");
8789
STATISTIC(NumRetDuped, "Number of return duplicated");
8890
STATISTIC(NumAccumAdded, "Number of accumulators introduced");
8991

92+
static cl::opt<bool> ForceDisableBFI(
93+
"tre-disable-entrycount-recompute", cl::init(false), cl::Hidden,
94+
cl::desc("Force disabling recomputing of function entry count, on "
95+
"successful tail recursion elimination."));
96+
9097
/// Scan the specified function for alloca instructions.
9198
/// If it contains any dynamic allocas, returns false.
9299
static bool canTRE(Function &F) {
@@ -409,6 +416,8 @@ class TailRecursionEliminator {
409416
AliasAnalysis *AA;
410417
OptimizationRemarkEmitter *ORE;
411418
DomTreeUpdater &DTU;
419+
const uint64_t OrigEntryBBFreq;
420+
DenseMap<const BasicBlock *, uint64_t> OriginalBBFreqs;
412421

413422
// The below are shared state we want to have available when eliminating any
414423
// calls in the function. There values should be populated by
@@ -438,8 +447,21 @@ class TailRecursionEliminator {
438447

439448
TailRecursionEliminator(Function &F, const TargetTransformInfo *TTI,
440449
AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
441-
DomTreeUpdater &DTU)
442-
: F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU) {}
450+
DomTreeUpdater &DTU, BlockFrequencyInfo *BFI)
451+
: F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU),
452+
OrigEntryBBFreq(
453+
BFI ? BFI->getBlockFreq(&F.getEntryBlock()).getFrequency() : 0U) {
454+
if (BFI) {
455+
assert(
456+
(F.getEntryCount()->getCount() != 0 == OrigEntryBBFreq != 0) &&
457+
"If the function has an entry count, its entry basic block should "
458+
"have a non-zero frequency. Pass a nullptr BFI if the function has "
459+
"no entry count");
460+
461+
for (const auto &BB : F)
462+
OriginalBBFreqs.insert({&BB, BFI->getBlockFreq(&BB).getFrequency()});
463+
}
464+
}
443465

444466
CallInst *findTRECandidate(BasicBlock *BB);
445467

@@ -460,7 +482,7 @@ class TailRecursionEliminator {
460482
public:
461483
static bool eliminate(Function &F, const TargetTransformInfo *TTI,
462484
AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
463-
DomTreeUpdater &DTU);
485+
DomTreeUpdater &DTU, BlockFrequencyInfo *BFI);
464486
};
465487
} // namespace
466488

@@ -746,6 +768,17 @@ bool TailRecursionEliminator::eliminateCall(CallInst *CI) {
746768
CI->eraseFromParent(); // Remove call.
747769
DTU.applyUpdates({{DominatorTree::Insert, BB, HeaderBB}});
748770
++NumEliminated;
771+
if (OrigEntryBBFreq) {
772+
assert(F.getEntryCount().has_value());
773+
auto It = OriginalBBFreqs.find(BB);
774+
assert(It != OriginalBBFreqs.end());
775+
auto RelativeBBFreq =
776+
static_cast<double>(It->second) / static_cast<double>(OrigEntryBBFreq);
777+
auto OldEntryCount = F.getEntryCount()->getCount();
778+
auto ToSubtract = static_cast<uint64_t>(RelativeBBFreq * OldEntryCount);
779+
assert(OldEntryCount > ToSubtract);
780+
F.setEntryCount(OldEntryCount - ToSubtract, F.getEntryCount()->getType());
781+
}
749782
return true;
750783
}
751784

@@ -872,7 +905,8 @@ bool TailRecursionEliminator::eliminate(Function &F,
872905
const TargetTransformInfo *TTI,
873906
AliasAnalysis *AA,
874907
OptimizationRemarkEmitter *ORE,
875-
DomTreeUpdater &DTU) {
908+
DomTreeUpdater &DTU,
909+
BlockFrequencyInfo *BFI) {
876910
if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
877911
return false;
878912

@@ -888,7 +922,7 @@ bool TailRecursionEliminator::eliminate(Function &F,
888922
return MadeChange;
889923

890924
// Change any tail recursive calls to loops.
891-
TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU);
925+
TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU, BFI);
892926

893927
for (BasicBlock &BB : F)
894928
MadeChange |= TRE.processBlock(BB);
@@ -930,7 +964,8 @@ struct TailCallElim : public FunctionPass {
930964
return TailRecursionEliminator::eliminate(
931965
F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
932966
&getAnalysis<AAResultsWrapperPass>().getAAResults(),
933-
&getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU);
967+
&getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU,
968+
nullptr);
934969
}
935970
};
936971
}
@@ -953,14 +988,22 @@ PreservedAnalyses TailCallElimPass::run(Function &F,
953988

954989
TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
955990
AliasAnalysis &AA = AM.getResult<AAManager>(F);
991+
// This must come first. It needs the 2 analyses, meaning, if it came after
992+
// the lines asking for the cached result, should they be nullptr (which, in
993+
// the case of the PDT, is likely), updates to the trees would be missed.
994+
auto *BFI = (!ForceDisableBFI && UpdateFunctionEntryCount &&
995+
F.getEntryCount().has_value())
996+
? &AM.getResult<BlockFrequencyAnalysis>(F)
997+
: nullptr;
956998
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
957999
auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
9581000
auto *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(F);
9591001
// There is no noticable performance difference here between Lazy and Eager
9601002
// UpdateStrategy based on some test results. It is feasible to switch the
9611003
// UpdateStrategy to Lazy if we find it profitable later.
9621004
DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
963-
bool Changed = TailRecursionEliminator::eliminate(F, &TTI, &AA, &ORE, DTU);
1005+
bool Changed =
1006+
TailRecursionEliminator::eliminate(F, &TTI, &AA, &ORE, DTU, BFI);
9641007

9651008
if (!Changed)
9661009
return PreservedAnalyses::all();
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --check-globals
2+
; RUN: opt -passes=tailcallelim -S %s -o - | FileCheck %s
3+
4+
; Test that tail call elimination correctly adjusts function entry counts
5+
; when eliminating tail recursive calls.
6+
7+
; Basic test: eliminate a tail call and adjust entry count
8+
define i32 @test_basic_entry_count_adjustment(i32 %n) !prof !0 {
9+
; CHECK-LABEL: @test_basic_entry_count_adjustment(
10+
; CHECK-NEXT: entry:
11+
; CHECK-NEXT: br label [[TAILRECURSE:%.*]]
12+
; CHECK: tailrecurse:
13+
; CHECK-NEXT: [[N_TR:%.*]] = phi i32 [ [[N:%.*]], [[ENTRY:%.*]] ], [ [[SUB:%.*]], [[IF_THEN:%.*]] ]
14+
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[N_TR]], 0
15+
; CHECK-NEXT: br i1 [[CMP]], label [[IF_THEN]], label [[IF_ELSE:%.*]], !prof [[PROF1:![0-9]+]]
16+
; CHECK: if.then:
17+
; CHECK-NEXT: [[SUB]] = sub i32 [[N_TR]], 1
18+
; CHECK-NEXT: br label [[TAILRECURSE]]
19+
; CHECK: if.else:
20+
; CHECK-NEXT: ret i32 0
21+
;
22+
entry:
23+
%cmp = icmp sgt i32 %n, 0
24+
br i1 %cmp, label %if.then, label %if.else, !prof !1
25+
26+
if.then: ; preds = %entry
27+
%sub = sub i32 %n, 1
28+
%call = tail call i32 @test_basic_entry_count_adjustment(i32 %sub)
29+
ret i32 %call
30+
31+
if.else: ; preds = %entry
32+
ret i32 0
33+
}
34+
35+
; Test multiple tail calls in different blocks with different frequencies
36+
define i32 @test_multiple_blocks_entry_count(i32 %n, i32 %flag) !prof !2 {
37+
; CHECK-LABEL: @test_multiple_blocks_entry_count(
38+
; CHECK-NEXT: entry:
39+
; CHECK-NEXT: br label [[TAILRECURSE:%.*]]
40+
; CHECK: tailrecurse:
41+
; CHECK-NEXT: [[N_TR:%.*]] = phi i32 [ [[N:%.*]], [[ENTRY:%.*]] ], [ [[SUB1:%.*]], [[BLOCK1:%.*]] ], [ [[SUB2:%.*]], [[BLOCK2:%.*]] ]
42+
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[N_TR]], 0
43+
; CHECK-NEXT: br i1 [[CMP]], label [[CHECK_FLAG:%.*]], label [[BASE_CASE:%.*]]
44+
; CHECK: check.flag:
45+
; CHECK-NEXT: [[CMP_FLAG:%.*]] = icmp eq i32 [[FLAG:%.*]], 1
46+
; CHECK-NEXT: br i1 [[CMP_FLAG]], label [[BLOCK1]], label [[BLOCK2]], !prof [[PROF3:![0-9]+]]
47+
; CHECK: block1:
48+
; CHECK-NEXT: [[SUB1]] = sub i32 [[N_TR]], 1
49+
; CHECK-NEXT: br label [[TAILRECURSE]]
50+
; CHECK: block2:
51+
; CHECK-NEXT: [[SUB2]] = sub i32 [[N_TR]], 2
52+
; CHECK-NEXT: br label [[TAILRECURSE]]
53+
; CHECK: base.case:
54+
; CHECK-NEXT: ret i32 1
55+
;
56+
entry:
57+
%cmp = icmp sgt i32 %n, 0
58+
br i1 %cmp, label %check.flag, label %base.case
59+
60+
check.flag:
61+
%cmp.flag = icmp eq i32 %flag, 1
62+
br i1 %cmp.flag, label %block1, label %block2, !prof !3
63+
64+
block1: ; preds = %check.flag
65+
%sub1 = sub i32 %n, 1
66+
%call1 = tail call i32 @test_multiple_blocks_entry_count(i32 %sub1, i32 %flag)
67+
ret i32 %call1
68+
69+
block2: ; preds = %check.flag
70+
%sub2 = sub i32 %n, 2
71+
%call2 = tail call i32 @test_multiple_blocks_entry_count(i32 %sub2, i32 %flag)
72+
ret i32 %call2
73+
74+
base.case: ; preds = %entry
75+
ret i32 1
76+
}
77+
78+
; Test function without entry count (should not crash)
79+
define i32 @test_no_entry_count(i32 %n) {
80+
; CHECK-LABEL: @test_no_entry_count(
81+
; CHECK-NEXT: entry:
82+
; CHECK-NEXT: br label [[TAILRECURSE:%.*]]
83+
; CHECK: tailrecurse:
84+
; CHECK-NEXT: [[N_TR:%.*]] = phi i32 [ [[N:%.*]], [[ENTRY:%.*]] ], [ [[SUB:%.*]], [[IF_THEN:%.*]] ]
85+
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[N_TR]], 0
86+
; CHECK-NEXT: br i1 [[CMP]], label [[IF_THEN]], label [[IF_ELSE:%.*]]
87+
; CHECK: if.then:
88+
; CHECK-NEXT: [[SUB]] = sub i32 [[N_TR]], 1
89+
; CHECK-NEXT: br label [[TAILRECURSE]]
90+
; CHECK: if.else:
91+
; CHECK-NEXT: ret i32 0
92+
;
93+
entry:
94+
%cmp = icmp sgt i32 %n, 0
95+
br i1 %cmp, label %if.then, label %if.else
96+
97+
if.then: ; preds = %entry
98+
%sub = sub i32 %n, 1
99+
%call = tail call i32 @test_no_entry_count(i32 %sub)
100+
ret i32 %call
101+
102+
if.else: ; preds = %entry
103+
ret i32 0
104+
}
105+
106+
; Function entry count metadata
107+
!0 = !{!"function_entry_count", i64 1000}
108+
!1 = !{!"branch_weights", i32 800, i32 200}
109+
!2 = !{!"function_entry_count", i64 2000}
110+
!3 = !{!"branch_weights", i32 100, i32 500}
111+
;.
112+
; CHECK: [[META0:![0-9]+]] = !{!"function_entry_count", i64 201}
113+
; CHECK: [[PROF1]] = !{!"branch_weights", i32 800, i32 200}
114+
; CHECK: [[META2:![0-9]+]] = !{!"function_entry_count", i64 859}
115+
; CHECK: [[PROF3]] = !{!"branch_weights", i32 100, i32 500}
116+
;.

0 commit comments

Comments
 (0)