1//===--- VTuneSupportPlugin.cpp -- Support for VTune profiler --*- 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// Handles support for registering code with VIntel Tune's Amplfiier JIT API.
10//
11//===----------------------------------------------------------------------===//
12#include "llvm/ExecutionEngine/Orc/Debugging/VTuneSupportPlugin.h"
13#include "llvm/DebugInfo/DWARF/DWARFContext.h"
14#include "llvm/ExecutionEngine/Orc/Debugging/DebugInfoSupport.h"
15#include "llvm/ExecutionEngine/Orc/SPSProxySpec.h"
16
17using namespace llvm;
18using namespace llvm::orc;
19using namespace llvm::jitlink;
20
21static constexpr StringRef RegisterVTuneImplName = "llvm_orc_registerVTuneImpl";
22static constexpr StringRef UnregisterVTuneImplName =
23 "llvm_orc_unregisterVTuneImpl";
24static constexpr StringRef RegisterTestVTuneImplName =
25 "llvm_orc_test_registerVTuneImpl";
26
27// Controller-interface descriptors for the executor's VTune-support wrapper
28// calls.
29namespace llvm::orc::vtune_sps_ci {
30struct UnregisterVTuneImpl {
31 static constexpr SymbolNameSpec Name =
32 SymbolNameSpec::c(Name: UnregisterVTuneImplName);
33 using SPSSig = void(shared::SPSVTuneUnloadedMethodIDs);
34};
35} // namespace llvm::orc::vtune_sps_ci
36
37VTuneSupportPlugin::VTuneSupportPlugin(ExecutorProcessControl &EPC,
38 ExecutorAddr RegisterImplAddr,
39 ExecutorAddr UnregisterImplAddr,
40 bool EmitDebugInfo)
41 : EPC(EPC), RegisterVTuneImplAddr(RegisterImplAddr),
42 UnregisterVTuneImpl(
43 sps::ProxySpec<vtune_sps_ci::UnregisterVTuneImpl>::dispatch,
44 UnregisterImplAddr),
45 EmitDebugInfo(EmitDebugInfo) {}
46
47static VTuneMethodBatch getMethodBatch(LinkGraph &G, bool EmitDebugInfo) {
48 VTuneMethodBatch Batch;
49 std::unique_ptr<DWARFContext> DC;
50 StringMap<std::unique_ptr<MemoryBuffer>> DCBacking;
51 if (EmitDebugInfo) {
52 auto EDC = createDWARFContext(G);
53 if (!EDC) {
54 EmitDebugInfo = false;
55 } else {
56 DC = std::move(EDC->first);
57 DCBacking = std::move(EDC->second);
58 }
59 }
60
61 auto GetStringIdx = [Deduplicator = StringMap<uint32_t>(),
62 &Batch](StringRef S) mutable {
63 auto [I, Inserted] = Deduplicator.try_emplace(Key: S);
64 if (Inserted) {
65 Batch.Strings.push_back(x: S.str());
66 I->second = Batch.Strings.size();
67 }
68 return I->second;
69 };
70 for (auto Sym : G.defined_symbols()) {
71 if (!Sym->isCallable())
72 continue;
73
74 Batch.Methods.push_back(x: VTuneMethodInfo());
75 auto &Method = Batch.Methods.back();
76 Method.MethodID = 0;
77 Method.ParentMI = 0;
78 Method.LoadAddr = Sym->getAddress();
79 Method.LoadSize = Sym->getSize();
80 Method.NameSI = GetStringIdx(*Sym->getName());
81 Method.ClassFileSI = 0;
82 Method.SourceFileSI = 0;
83
84 if (!EmitDebugInfo)
85 continue;
86
87 auto &Section = Sym->getSection();
88 auto Addr = Sym->getAddress();
89 auto SAddr =
90 object::SectionedAddress{.Address: Addr.getValue(), .SectionIndex: Section.getOrdinal()};
91 DILineInfoTable LinesInfo = DC->getLineInfoForAddressRange(
92 Address: SAddr, Size: Sym->getSize(),
93 Specifier: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath);
94 Method.SourceFileSI = Batch.Strings.size();
95 Batch.Strings.push_back(
96 x: DC->getLineInfoForAddress(Address: SAddr).value_or(u: DILineInfo()).FileName);
97 for (auto &LInfo : LinesInfo) {
98 Method.LineTable.push_back(
99 x: std::pair<unsigned, unsigned>{/*unsigned*/ Sym->getOffset(),
100 /*DILineInfo*/ LInfo.second.Line});
101 }
102 }
103 return Batch;
104}
105
106void VTuneSupportPlugin::modifyPassConfig(MaterializationResponsibility &MR,
107 LinkGraph &G,
108 PassConfiguration &Config) {
109 Config.PostFixupPasses.push_back(x: [this, MR = &MR](LinkGraph &G) {
110 // the object file is generated but not linked yet
111 auto Batch = getMethodBatch(G, EmitDebugInfo);
112 if (Batch.Methods.empty()) {
113 return Error::success();
114 }
115 {
116 std::lock_guard<std::mutex> Lock(PluginMutex);
117 uint64_t Allocated = Batch.Methods.size();
118 uint64_t Start = NextMethodID;
119 NextMethodID += Allocated;
120 for (size_t i = Start; i < NextMethodID; ++i) {
121 Batch.Methods[i - Start].MethodID = i;
122 }
123 this->PendingMethodIDs[MR] = {Start, Allocated};
124 }
125 G.allocActions().push_back(
126 x: {.Finalize: cantFail(ValOrErr: shared::WrapperFunctionCall::Create<
127 shared::SPSArgList<shared::SPSVTuneMethodBatch>>(
128 FnAddr: RegisterVTuneImplAddr, Args: Batch)),
129 .Dealloc: {}});
130 return Error::success();
131 });
132}
133
134Error VTuneSupportPlugin::notifyEmitted(MaterializationResponsibility &MR) {
135 if (auto Err = MR.withResourceKeyDo(F: [this, MR = &MR](ResourceKey K) {
136 std::lock_guard<std::mutex> Lock(PluginMutex);
137 auto I = PendingMethodIDs.find(Val: MR);
138 if (I == PendingMethodIDs.end())
139 return;
140
141 LoadedMethodIDs[K].push_back(Elt: I->second);
142 PendingMethodIDs.erase(I);
143 })) {
144 return Err;
145 }
146 return Error::success();
147}
148
149Error VTuneSupportPlugin::notifyFailed(MaterializationResponsibility &MR) {
150 std::lock_guard<std::mutex> Lock(PluginMutex);
151 PendingMethodIDs.erase(Val: &MR);
152 return Error::success();
153}
154
155Error VTuneSupportPlugin::notifyRemovingResources(JITDylib &JD, ResourceKey K) {
156 // Unregistration not required if not provided
157 if (!UnregisterVTuneImpl) {
158 return Error::success();
159 }
160 VTuneUnloadedMethodIDs UnloadedIDs;
161 {
162 std::lock_guard<std::mutex> Lock(PluginMutex);
163 auto I = LoadedMethodIDs.find(Val: K);
164 if (I == LoadedMethodIDs.end())
165 return Error::success();
166
167 UnloadedIDs = std::move(I->second);
168 LoadedMethodIDs.erase(I);
169 }
170 if (auto Err = UnregisterVTuneImpl(EPC.getExecutionSession(), UnloadedIDs))
171 return Err;
172
173 return Error::success();
174}
175
176void VTuneSupportPlugin::notifyTransferringResources(JITDylib &JD,
177 ResourceKey DstKey,
178 ResourceKey SrcKey) {
179 std::lock_guard<std::mutex> Lock(PluginMutex);
180 auto I = LoadedMethodIDs.find(Val: SrcKey);
181 if (I == LoadedMethodIDs.end())
182 return;
183
184 auto &Dest = LoadedMethodIDs[DstKey];
185 llvm::append_range(C&: Dest, R&: I->second);
186 LoadedMethodIDs.erase(Val: SrcKey);
187}
188
189Expected<std::unique_ptr<VTuneSupportPlugin>>
190VTuneSupportPlugin::Create(ExecutorProcessControl &EPC, JITDylib &JD,
191 bool EmitDebugInfo, bool TestMode) {
192 auto &ES = EPC.getExecutionSession();
193 auto RegisterImplName =
194 ES.intern(SymName: TestMode ? RegisterTestVTuneImplName : RegisterVTuneImplName);
195 auto UnregisterImplName = ES.intern(SymName: UnregisterVTuneImplName);
196 SymbolLookupSet SLS{RegisterImplName, UnregisterImplName};
197 auto Res = ES.lookup(SearchOrder: makeJITDylibSearchOrder(JDs: {&JD}), Symbols: std::move(SLS));
198 if (!Res)
199 return Res.takeError();
200 ExecutorAddr RegisterImplAddr(
201 Res->find(Val: RegisterImplName)->second.getAddress());
202 ExecutorAddr UnregisterImplAddr(
203 Res->find(Val: UnregisterImplName)->second.getAddress());
204 return std::make_unique<VTuneSupportPlugin>(
205 args&: EPC, args&: RegisterImplAddr, args&: UnregisterImplAddr, args&: EmitDebugInfo);
206}
207