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"
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");
8789STATISTIC (NumRetDuped, " Number of return duplicated" );
8890STATISTIC (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.
9299static 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 {
460482public:
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 ();
0 commit comments