Skip to content

[PGO] Add ProfileInjector and ProfileVerifier passes #147388

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
36 changes: 36 additions & 0 deletions llvm/include/llvm/Transforms/Utils/ProfileVerify.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//===- ProfileVerify.h - Verify profile info for testing ----0-----*-C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Inject profile information, as part of tests, to verify passes don't
// accidentally drop it.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TRANSFORMS_UTILS_PROFILEVERIFY_H
#define LLVM_TRANSFORMS_UTILS_PROFILEVERIFY_H

#include "llvm/IR/Analysis.h"
#include "llvm/IR/PassManager.h"

namespace llvm {
/// Inject MD_prof metadata where it's missing. Used for testing that passes
/// don't accidentally drop this metadata.
class ProfileInjectorPass : public PassInfoMixin<ProfileInjectorPass> {
public:
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
};

/// Checks that MD_prof is present on every instruction that supports it. Used
/// in conjunction with the ProfileInjectorPass. MD_prof "unknown" is considered
/// valid (i.e. !{!"unknown"})
class ProfileVerifierPass : public PassInfoMixin<ProfileVerifierPass> {
public:
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
};

} // namespace llvm
#endif
1 change: 1 addition & 0 deletions llvm/lib/Passes/PassBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@
#include "llvm/Transforms/Utils/MoveAutoInit.h"
#include "llvm/Transforms/Utils/NameAnonGlobals.h"
#include "llvm/Transforms/Utils/PredicateInfo.h"
#include "llvm/Transforms/Utils/ProfileVerify.h"
#include "llvm/Transforms/Utils/RelLookupTableConverter.h"
#include "llvm/Transforms/Utils/StripGCRelocates.h"
#include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
Expand Down
2 changes: 2 additions & 0 deletions llvm/lib/Passes/PassRegistry.def
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,8 @@ FUNCTION_PASS("print<regions>", RegionInfoPrinterPass(errs()))
FUNCTION_PASS("print<scalar-evolution>", ScalarEvolutionPrinterPass(errs()))
FUNCTION_PASS("print<stack-safety-local>", StackSafetyPrinterPass(errs()))
FUNCTION_PASS("print<uniformity>", UniformityInfoPrinterPass(errs()))
FUNCTION_PASS("prof-inject", ProfileInjectorPass())
FUNCTION_PASS("prof-verify", ProfileVerifierPass())
FUNCTION_PASS("reassociate", ReassociatePass())
FUNCTION_PASS("redundant-dbg-inst-elim", RedundantDbgInstEliminationPass())
FUNCTION_PASS("reg2mem", RegToMemPass())
Expand Down
1 change: 1 addition & 0 deletions llvm/lib/Transforms/Utils/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ add_llvm_component_library(LLVMTransformUtils
MoveAutoInit.cpp
NameAnonGlobals.cpp
PredicateInfo.cpp
ProfileVerify.cpp
PromoteMemoryToRegister.cpp
RelLookupTableConverter.cpp
ScalarEvolutionExpander.cpp
Expand Down
113 changes: 113 additions & 0 deletions llvm/lib/Transforms/Utils/ProfileVerify.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
//===- ProfileVerify.cpp - Verify profile info for testing ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/ProfileVerify.h"
#include "llvm/ADT/DynamicAPInt.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/Analysis.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/ProfDataUtils.h"
#include "llvm/Support/BranchProbability.h"

using namespace llvm;
namespace {
class ProfileInjector {
Function &F;
FunctionAnalysisManager &FAM;

public:
static bool supportsBranchWeights(const Instruction &I) {
return isa<BranchInst>(&I) ||

isa<SwitchInst>(&I) ||

isa<IndirectBrInst>(&I) || isa<SelectInst>(&I) ||
isa<CallBrInst>(&I);
}

ProfileInjector(Function &F, FunctionAnalysisManager &FAM) : F(F), FAM(FAM) {}
bool inject();
};
} // namespace

bool ProfileInjector::inject() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can SamplePGO's weight propagation be reused here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(capturing offline chat) this would be e.g. profi, and yes, we could use it in a number of ways:

  • instead of the perhaps more naive BPI estimator currently used (implicitly) here
  • as the way the BPI estimator handles MD_prof unknown cases (I think these 2 items basically amount to the same thing - improving the BPI estimator)
  • as a numerical validation heuristic (part "2" in the RFC)

auto &BPI = FAM.getResult<BranchProbabilityAnalysis>(F);

for (auto &BB : F) {
if (succ_size(&BB) <= 1)
continue;
auto *Term = BB.getTerminator();
assert(Term);
if (Term->getMetadata(LLVMContext::MD_prof) ||
!supportsBranchWeights(*Term))
continue;
SmallVector<BranchProbability> Probs;
Probs.reserve(Term->getNumSuccessors());
for (auto I = 0U, E = Term->getNumSuccessors(); I < E; ++I)
Probs.emplace_back(BPI.getEdgeProbability(&BB, Term->getSuccessor(I)));

const auto *FirstZeroDenominator =
find_if(Probs, [](const BranchProbability &P) {
return P.getDenominator() == 0;
});
assert(FirstZeroDenominator == Probs.end());
const auto *FirstNonzeroNumerator =
find_if(Probs, [](const BranchProbability &P) {
return P.getNumerator() != 0;
});
assert(FirstNonzeroNumerator != Probs.end());
DynamicAPInt LCM(Probs[0].getDenominator());
DynamicAPInt GCD(FirstNonzeroNumerator->getNumerator());
for (const auto &Prob : drop_begin(Probs)) {
if (!Prob.getNumerator())
continue;
LCM = llvm::lcm(LCM, DynamicAPInt(Prob.getDenominator()));
GCD = llvm::lcm(GCD, DynamicAPInt(Prob.getNumerator()));
}
SmallVector<uint32_t> Weights;
Weights.reserve(Term->getNumSuccessors());
for (const auto &Prob : Probs) {
auto W = Prob.getNumerator() * LCM / GCD;
Weights.emplace_back(static_cast<int32_t>((int64_t)W));
}
setBranchWeights(*Term, Weights, false);
}
return true;
}

PreservedAnalyses ProfileInjectorPass::run(Function &F,
FunctionAnalysisManager &FAM) {
ProfileInjector PI(F, FAM);
if (!PI.inject())
return PreservedAnalyses::all();

return PreservedAnalyses::none();
}

PreservedAnalyses ProfileVerifierPass::run(Function &F,
FunctionAnalysisManager &FAM) {
bool Changed = false;
for (auto &BB : F)
if (succ_size(&BB) >= 2)
if (auto *Term = BB.getTerminator())
if (ProfileInjector::supportsBranchWeights(*Term)) {
if (!Term->getMetadata(LLVMContext::MD_prof)) {
F.getContext().emitError("Profile verification failed");
} else {
Changed = true;
}
}

return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
}
20 changes: 20 additions & 0 deletions llvm/test/Transforms/PGOProfile/prof-verify-as-needed.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
; Test that prof-inject only injects missing metadata

; RUN: opt -passes=prof-inject %s -S -o - | FileCheck %s

define void @foo(i32 %i) {
%c = icmp eq i32 %i, 0
br i1 %c, label %yes, label %no, !prof !0
yes:
br i1 %c, label %yes2, label %no
yes2:
ret void
no:
ret void
}

!0 = !{!"branch_weights", i32 1, i32 2}
; CHECK: br i1 %c, label %yes, label %no, !prof !0
; CHECK: br i1 %c, label %yes2, label %no, !prof !1
; CHECK: !0 = !{!"branch_weights", i32 1, i32 2}
; CHECK: !1 = !{!"branch_weights", i32 429496729, i32 715827882}
21 changes: 21 additions & 0 deletions llvm/test/Transforms/PGOProfile/prof-verify-existing.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
; Test that prof-verify does not modify existing metadata (incl. "unknown")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whether overriding unknown MD_prof should probably be guarded by a flag. There are cases the pass can not do a sophisticated weight propagation to infer weight for new branches, but the prof injection pass can.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The expectation is that unknown is inserted by the developer of a pass, so the injector shouldn't override it, since the injector is only here for testing purposes - i.e. its job is to make metadata "be there" for .ll tests that don't originally have it.


; RUN: opt -passes=prof-inject %s -S -o - | FileCheck %s
; RUN: opt -passes=prof-verify %s -S --disable-output

define void @foo(i32 %i) {
%c = icmp eq i32 %i, 0
br i1 %c, label %yes, label %no, !prof !0
yes:
br i1 %c, label %yes2, label %no, !prof !1
yes2:
ret void
no:
ret void
}

!0 = !{!"branch_weights", i32 1, i32 2}
!1 = !{!"unknown"}
; CHECK: br i1 %c, label %yes, label %no, !prof !0
; CHECK: !0 = !{!"branch_weights", i32 1, i32 2}
; CHECK: !1 = !{!"unknown"}
19 changes: 19 additions & 0 deletions llvm/test/Transforms/PGOProfile/prof-verify.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
; Test prof-inject and prof-verify

; RUN: opt -passes=prof-inject %s -S -o - | FileCheck %s --check-prefix=INJECT
; RUN: not opt -passes=prof-verify %s -S -o - 2>&1 | FileCheck %s --check-prefix=VERIFY
; RUN: opt -passes=prof-inject,prof-verify %s --disable-output

define void @foo(i32 %i) {
%c = icmp eq i32 %i, 0
br i1 %c, label %yes, label %no
yes:
ret void
no:
ret void
}

; INJECT: br i1 %c, label %yes, label %no, !prof !0
; INJECT: !0 = !{!"branch_weights", i32 429496729, i32 715827882}

; VERIFY: Profile verification failed