Skip to content

Commit dbbf076

Browse files
authored
[ctx_prof] CtxProfAnalysis (#102084)
This is an immutable analysis that loads and makes the contextual profile available to other passes. This patch introduces the analysis and an analysis printer pass. Subsequent patches will introduce the APIs that IPO passes will call to modify the profile as result of their changes.
1 parent 5855237 commit dbbf076

File tree

7 files changed

+228
-1
lines changed

7 files changed

+228
-1
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
//===- CtxProfAnalysis.h - maintain contextual profile info -*- C++ ---*-===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
//
9+
#ifndef LLVM_ANALYSIS_CTXPROFANALYSIS_H
10+
#define LLVM_ANALYSIS_CTXPROFANALYSIS_H
11+
12+
#include "llvm/IR/GlobalValue.h"
13+
#include "llvm/IR/PassManager.h"
14+
#include "llvm/ProfileData/PGOCtxProfReader.h"
15+
#include <map>
16+
17+
namespace llvm {
18+
19+
class CtxProfAnalysis;
20+
21+
/// The instrumented contextual profile, produced by the CtxProfAnalysis.
22+
class PGOContextualProfile {
23+
std::optional<PGOCtxProfContext::CallTargetMapTy> Profiles;
24+
25+
public:
26+
explicit PGOContextualProfile(PGOCtxProfContext::CallTargetMapTy &&Profiles)
27+
: Profiles(std::move(Profiles)) {}
28+
PGOContextualProfile() = default;
29+
PGOContextualProfile(const PGOContextualProfile &) = delete;
30+
PGOContextualProfile(PGOContextualProfile &&) = default;
31+
32+
operator bool() const { return Profiles.has_value(); }
33+
34+
const PGOCtxProfContext::CallTargetMapTy &profiles() const {
35+
return *Profiles;
36+
}
37+
38+
bool invalidate(Module &, const PreservedAnalyses &PA,
39+
ModuleAnalysisManager::Invalidator &) {
40+
// Check whether the analysis has been explicitly invalidated. Otherwise,
41+
// it's stateless and remains preserved.
42+
auto PAC = PA.getChecker<CtxProfAnalysis>();
43+
return !PAC.preservedWhenStateless();
44+
}
45+
};
46+
47+
class CtxProfAnalysis : public AnalysisInfoMixin<CtxProfAnalysis> {
48+
StringRef Profile;
49+
50+
public:
51+
static AnalysisKey Key;
52+
explicit CtxProfAnalysis(StringRef Profile) : Profile(Profile) {};
53+
54+
using Result = PGOContextualProfile;
55+
56+
PGOContextualProfile run(Module &M, ModuleAnalysisManager &MAM);
57+
};
58+
59+
class CtxProfAnalysisPrinterPass
60+
: public PassInfoMixin<CtxProfAnalysisPrinterPass> {
61+
raw_ostream &OS;
62+
63+
public:
64+
explicit CtxProfAnalysisPrinterPass(raw_ostream &OS) : OS(OS) {}
65+
66+
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
67+
static bool isRequired() { return true; }
68+
};
69+
} // namespace llvm
70+
#endif // LLVM_ANALYSIS_CTXPROFANALYSIS_H

llvm/lib/Analysis/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ add_llvm_component_library(LLVMAnalysis
4646
CostModel.cpp
4747
CodeMetrics.cpp
4848
ConstantFolding.cpp
49+
CtxProfAnalysis.cpp
4950
CycleAnalysis.cpp
5051
DDG.cpp
5152
DDGPrinter.cpp

llvm/lib/Analysis/CtxProfAnalysis.cpp

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
//===- CtxProfAnalysis.cpp - contextual profile analysis ------------------===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
//
9+
// Implementation of the contextual profile analysis, which maintains contextual
10+
// profiling info through IPO passes.
11+
//
12+
//===----------------------------------------------------------------------===//
13+
14+
#include "llvm/Analysis/CtxProfAnalysis.h"
15+
#include "llvm/ADT/STLExtras.h"
16+
#include "llvm/IR/Analysis.h"
17+
#include "llvm/IR/Module.h"
18+
#include "llvm/IR/PassManager.h"
19+
#include "llvm/ProfileData/PGOCtxProfReader.h"
20+
#include "llvm/Support/JSON.h"
21+
#include "llvm/Support/MemoryBuffer.h"
22+
23+
#define DEBUG_TYPE "ctx_prof"
24+
25+
namespace llvm {
26+
namespace json {
27+
Value toJSON(const PGOCtxProfContext &P) {
28+
Object Ret;
29+
Ret["Guid"] = P.guid();
30+
Ret["Counters"] = Array(P.counters());
31+
if (P.callsites().empty())
32+
return Ret;
33+
auto AllCS =
34+
::llvm::map_range(P.callsites(), [](const auto &P) { return P.first; });
35+
auto MaxIt = ::llvm::max_element(AllCS);
36+
assert(MaxIt != AllCS.end() && "We should have a max value because the "
37+
"callsites collection is not empty.");
38+
Array CSites;
39+
// Iterate to, and including, the maximum index.
40+
for (auto I = 0U, Max = *MaxIt; I <= Max; ++I) {
41+
CSites.push_back(Array());
42+
Array &Targets = *CSites.back().getAsArray();
43+
if (P.hasCallsite(I))
44+
for (const auto &[_, Ctx] : P.callsite(I))
45+
Targets.push_back(toJSON(Ctx));
46+
}
47+
Ret["Callsites"] = std::move(CSites);
48+
49+
return Ret;
50+
}
51+
52+
Value toJSON(const PGOCtxProfContext::CallTargetMapTy &P) {
53+
Array Ret;
54+
for (const auto &[_, Ctx] : P)
55+
Ret.push_back(toJSON(Ctx));
56+
return Ret;
57+
}
58+
} // namespace json
59+
} // namespace llvm
60+
61+
using namespace llvm;
62+
63+
AnalysisKey CtxProfAnalysis::Key;
64+
65+
CtxProfAnalysis::Result CtxProfAnalysis::run(Module &M,
66+
ModuleAnalysisManager &MAM) {
67+
ErrorOr<std::unique_ptr<MemoryBuffer>> MB = MemoryBuffer::getFile(Profile);
68+
if (auto EC = MB.getError()) {
69+
M.getContext().emitError("could not open contextual profile file: " +
70+
EC.message());
71+
return {};
72+
}
73+
PGOCtxProfileReader Reader(MB.get()->getBuffer());
74+
auto MaybeCtx = Reader.loadContexts();
75+
if (!MaybeCtx) {
76+
M.getContext().emitError("contextual profile file is invalid: " +
77+
toString(MaybeCtx.takeError()));
78+
return {};
79+
}
80+
return Result(std::move(*MaybeCtx));
81+
}
82+
83+
PreservedAnalyses CtxProfAnalysisPrinterPass::run(Module &M,
84+
ModuleAnalysisManager &MAM) {
85+
CtxProfAnalysis::Result &C = MAM.getResult<CtxProfAnalysis>(M);
86+
if (!C) {
87+
M.getContext().emitError("Invalid CtxProfAnalysis");
88+
return PreservedAnalyses::all();
89+
}
90+
const auto JSONed = ::llvm::json::toJSON(C.profiles());
91+
92+
OS << formatv("{0:2}", JSONed);
93+
OS << "\n";
94+
return PreservedAnalyses::all();
95+
}

llvm/lib/Passes/PassBuilder.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include "llvm/Analysis/CallGraph.h"
2929
#include "llvm/Analysis/CallPrinter.h"
3030
#include "llvm/Analysis/CostModel.h"
31+
#include "llvm/Analysis/CtxProfAnalysis.h"
3132
#include "llvm/Analysis/CycleAnalysis.h"
3233
#include "llvm/Analysis/DDG.h"
3334
#include "llvm/Analysis/DDGPrinter.h"
@@ -330,6 +331,8 @@ cl::opt<bool> PrintPipelinePasses(
330331
"(best-effort only)."));
331332
} // namespace llvm
332333

334+
extern cl::opt<std::string> UseCtxProfile;
335+
333336
AnalysisKey NoOpModuleAnalysis::Key;
334337
AnalysisKey NoOpCGSCCAnalysis::Key;
335338
AnalysisKey NoOpFunctionAnalysis::Key;

llvm/lib/Passes/PassBuilderPipelines.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ static cl::opt<bool> UseLoopVersioningLICM(
304304
"enable-loop-versioning-licm", cl::init(false), cl::Hidden,
305305
cl::desc("Enable the experimental Loop Versioning LICM pass"));
306306

307-
static cl::opt<std::string>
307+
cl::opt<std::string>
308308
UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden,
309309
cl::desc("Use the specified contextual profile file"));
310310

llvm/lib/Passes/PassRegistry.def

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#endif
2121
MODULE_ANALYSIS("callgraph", CallGraphAnalysis())
2222
MODULE_ANALYSIS("collector-metadata", CollectorMetadataAnalysis())
23+
MODULE_ANALYSIS("ctx-prof-analysis", CtxProfAnalysis(UseCtxProfile))
2324
MODULE_ANALYSIS("inline-advisor", InlineAdvisorAnalysis())
2425
MODULE_ANALYSIS("ir-similarity", IRSimilarityAnalysis())
2526
MODULE_ANALYSIS("lcg", LazyCallGraphAnalysis())
@@ -79,6 +80,7 @@ MODULE_PASS("insert-gcov-profiling", GCOVProfilerPass())
7980
MODULE_PASS("instrorderfile", InstrOrderFilePass())
8081
MODULE_PASS("instrprof", InstrProfilingLoweringPass())
8182
MODULE_PASS("ctx-instr-lower", PGOCtxProfLoweringPass())
83+
MODULE_PASS("print<ctx-prof-analysis>", CtxProfAnalysisPrinterPass(dbgs()))
8284
MODULE_PASS("invalidate<all>", InvalidateAllAnalysesPass())
8385
MODULE_PASS("iroutliner", IROutlinerPass())
8486
MODULE_PASS("jmc-instrumenter", JMCInstrumenterPass())
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
; RUN: split-file %s %t
2+
; RUN: llvm-ctxprof-util fromJSON --input=%t/profile.json --output=%t/profile.ctxprofdata
3+
; RUN: not opt -passes='require<ctx-prof-analysis>,print<ctx-prof-analysis>' \
4+
; RUN: %t/empty.ll -S 2>&1 | FileCheck %s --check-prefix=NO-FILE
5+
6+
; RUN: not opt -passes='require<ctx-prof-analysis>,print<ctx-prof-analysis>' \
7+
; RUN: -use-ctx-profile=does_not_exist.ctxprofdata %t/empty.ll -S 2>&1 | FileCheck %s --check-prefix=NO-FILE
8+
9+
; RUN: opt -passes='require<ctx-prof-analysis>,print<ctx-prof-analysis>' \
10+
; RUN: -use-ctx-profile=%t/profile.ctxprofdata %t/empty.ll -S 2> %t/output.json
11+
; RUN: diff %t/profile.json %t/output.json
12+
13+
; NO-FILE: error: could not open contextual profile file
14+
;
15+
; This is the reference profile, laid out in the format the json formatter will
16+
; output it from opt.
17+
;--- profile.json
18+
[
19+
{
20+
"Callsites": [
21+
[],
22+
[
23+
{
24+
"Counters": [
25+
4,
26+
5
27+
],
28+
"Guid": 2000
29+
},
30+
{
31+
"Counters": [
32+
6,
33+
7,
34+
8
35+
],
36+
"Guid": 18446744073709551613
37+
}
38+
]
39+
],
40+
"Counters": [
41+
1,
42+
2,
43+
3
44+
],
45+
"Guid": 1000
46+
},
47+
{
48+
"Counters": [
49+
5,
50+
9,
51+
10
52+
],
53+
"Guid": 18446744073709551612
54+
}
55+
]
56+
;--- empty.ll

0 commit comments

Comments
 (0)