LLVM 20.0.0git
CtxProfAnalysis.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/IR/Analysis.h"
17#include "llvm/IR/Module.h"
18#include "llvm/IR/PassManager.h"
21#include "llvm/Support/JSON.h"
23
24#define DEBUG_TYPE "ctx_prof"
25
26using namespace llvm;
28 UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden,
29 cl::desc("Use the specified contextual profile file"));
30
31namespace llvm {
32namespace json {
34 Object Ret;
35 Ret["Guid"] = P.guid();
36 Ret["Counters"] = Array(P.counters());
37 if (P.callsites().empty())
38 return Ret;
39 auto AllCS =
40 ::llvm::map_range(P.callsites(), [](const auto &P) { return P.first; });
41 auto MaxIt = ::llvm::max_element(AllCS);
42 assert(MaxIt != AllCS.end() && "We should have a max value because the "
43 "callsites collection is not empty.");
44 Array CSites;
45 // Iterate to, and including, the maximum index.
46 for (auto I = 0U, Max = *MaxIt; I <= Max; ++I) {
47 CSites.push_back(Array());
48 Array &Targets = *CSites.back().getAsArray();
49 if (P.hasCallsite(I))
50 for (const auto &[_, Ctx] : P.callsite(I))
51 Targets.push_back(toJSON(Ctx));
52 }
53 Ret["Callsites"] = std::move(CSites);
54
55 return Ret;
56}
57
59 Array Ret;
60 for (const auto &[_, Ctx] : P)
61 Ret.push_back(toJSON(Ctx));
62 return Ret;
63}
64} // namespace json
65} // namespace llvm
66
68
72 if (auto EC = MB.getError()) {
73 M.getContext().emitError("could not open contextual profile file: " +
74 EC.message());
75 return {};
76 }
77 PGOCtxProfileReader Reader(MB.get()->getBuffer());
78 auto MaybeCtx = Reader.loadContexts();
79 if (!MaybeCtx) {
80 M.getContext().emitError("contextual profile file is invalid: " +
81 toString(MaybeCtx.takeError()));
82 return {};
83 }
84 return Result(std::move(*MaybeCtx));
85}
86
90 if (!C) {
91 M.getContext().emitError("Invalid CtxProfAnalysis");
93 }
94 const auto JSONed = ::llvm::json::toJSON(C.profiles());
95
96 OS << formatv("{0:2}", JSONed);
97 OS << "\n";
99}
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
#define _
This file supports working with JSON data.
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
#define P(N)
Reader for contextual iFDO profile, which comes in bitstream format.
ModuleAnalysisManager MAM
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PGOContextualProfile run(Module &M, ModuleAnalysisManager &MAM)
static AnalysisKey Key
PGOContextualProfile Result
Represents either an error or a value T.
Definition: ErrorOr.h:56
reference get()
Definition: ErrorOr.h:149
std::error_code getError() const
Definition: ErrorOr.h:152
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
The instrumented contextual profile, produced by the CtxProfAnalysis.
A node (context) in the loaded contextual profile, suitable for mutation during IPO passes.
std::map< GlobalValue::GUID, PGOCtxProfContext > CallTargetMapTy
Expected< std::map< GlobalValue::GUID, PGOCtxProfContext > > loadContexts()
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:164
void push_back(const Value &E)
Definition: JSON.h:552
Value & back()
Definition: JSON.h:537
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:98
A Value is an JSON value of unknown type.
Definition: JSON.h:288
const json::Array * getAsArray() const
Definition: JSON.h:468
Pass manager infrastructure for declaring and invalidating analyses.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
Value toJSON(const std::optional< T > &Opt)
Definition: JSON.h:827
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto map_range(ContainerTy &&C, FuncTy F)
Definition: STLExtras.h:377
auto max_element(R &&Range)
Definition: STLExtras.h:1986
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:28