Proteus
Programmable JIT compilation and optimization for C/C++ using LLVM
Loading...
Searching...
No Matches
JitEngineDevice.hpp
Go to the documentation of this file.
1//===-- JitEngineDevice.cpp -- Base JIT Engine Device header impl. --===//
2//
3// Part of the Proteus Project, under the Apache License v2.0 with LLVM
4// Exceptions. See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//===----------------------------------------------------------------------===//
10
11#ifndef PROTEUS_JITENGINEDEVICE_HPP
12#define PROTEUS_JITENGINEDEVICE_HPP
13
16#include "proteus/Cloning.h"
21#include "proteus/CoreLLVM.hpp"
22#include "proteus/Debug.h"
23#include "proteus/Hashing.hpp"
24#include "proteus/JitEngine.hpp"
26#include "proteus/Utils.h"
27
28#include <llvm/ADT/SmallPtrSet.h>
29#include <llvm/ADT/SmallVector.h>
30#include <llvm/ADT/StringRef.h>
31#include <llvm/Analysis/CallGraph.h>
32#include <llvm/Analysis/TargetTransformInfo.h>
33#include <llvm/Bitcode/BitcodeWriter.h>
34#include <llvm/CodeGen/CommandFlags.h>
35#include <llvm/CodeGen/MachineModuleInfo.h>
36#include <llvm/Config/llvm-config.h>
37#include <llvm/Demangle/Demangle.h>
38#include <llvm/ExecutionEngine/Orc/ThreadSafeModule.h>
39#include <llvm/IR/Constants.h>
40#include <llvm/IR/GlobalVariable.h>
41#include <llvm/IR/Instruction.h>
42#include <llvm/IR/Instructions.h>
43#include <llvm/IR/LLVMContext.h>
44#include <llvm/IR/LegacyPassManager.h>
45#include <llvm/IR/Module.h>
46#include <llvm/IR/ReplaceConstant.h>
47#include <llvm/IR/Type.h>
48#include <llvm/IR/Verifier.h>
49#include <llvm/IRReader/IRReader.h>
50#include <llvm/Linker/Linker.h>
51#include <llvm/MC/TargetRegistry.h>
52#include <llvm/Object/ELFObjectFile.h>
53#include <llvm/Passes/PassBuilder.h>
54#include <llvm/Support/Error.h>
55#include <llvm/Support/MemoryBuffer.h>
56#include <llvm/Support/MemoryBufferRef.h>
57#include <llvm/Target/TargetMachine.h>
58#include <llvm/Transforms/IPO/Internalize.h>
59#include <llvm/Transforms/Utils/Cloning.h>
60#include <llvm/Transforms/Utils/ModuleUtils.h>
61
62#include <cstdint>
63#include <functional>
64#include <memory>
65#include <optional>
66#include <string>
67
68namespace proteus {
69
70using namespace llvm;
71
78
80private:
81 FatbinWrapperT *FatbinWrapper;
82 std::unique_ptr<LLVMContext> Ctx;
83 SmallVector<std::string> LinkedModuleIds;
84 Module *LinkedModule;
85 std::optional<SmallVector<std::unique_ptr<Module>>> ExtractedModules;
86 std::optional<HashT> ExtractedModuleHash;
87 std::optional<CallGraph> ModuleCallGraph;
88 std::unique_ptr<MemoryBuffer> DeviceBinary;
89 std::unordered_map<std::string, GlobalVarInfo> VarNameToGlobalInfo;
90 bool GlobalsMapped;
91 std::once_flag Flag;
92
93public:
94 BinaryInfo() = default;
95 BinaryInfo(FatbinWrapperT *FatbinWrapper,
96 SmallVector<std::string> &&LinkedModuleIds)
98 LinkedModuleIds(LinkedModuleIds), LinkedModule(nullptr),
99 ExtractedModules(std::nullopt), ModuleCallGraph(std::nullopt),
100 DeviceBinary(nullptr), GlobalsMapped(false) {}
101
103
104 std::unique_ptr<LLVMContext> &getLLVMContext() { return Ctx; }
105
106 bool hasLinkedModule() const { return (LinkedModule != nullptr); }
108 if (!LinkedModule) {
109 if (!hasExtractedModules())
110 reportFatalError("Expected extracted modules");
111
112 Timer T;
113 // Avoid linking when there's a single module by moving it instead and
114 // making sure it's materialized for call graph analysis.
115 if (ExtractedModules->size() == 1) {
116 LinkedModule = ExtractedModules->front().get();
117 if (auto E = LinkedModule->materializeAll())
118 reportFatalError("Error materializing " + toString(std::move(E)));
119 } else {
120 // By the LLVM API, linkModules takes ownership of module pointers in
121 // ExtractedModules and returns a new unique ptr to the linked module.
122 // We update ExtractedModules to contain and own only the generated
123 // LinkedModule.
125 proteus::linkModules(*Ctx, std::move(ExtractedModules.value()));
127 NewExtractedModules.emplace_back(std::move(GeneratedLinkedModule));
129
130 LinkedModule = ExtractedModules->front().get();
131 }
132
134 << "getLinkedModule " << T.elapsed() << " ms\n");
135 }
136
137 return *LinkedModule;
138 }
139
140 bool hasExtractedModules() const { return ExtractedModules.has_value(); }
143 // This should be called only once when cloning the kernel module to
144 // cache.
146 for (auto &M : ExtractedModules.value())
147 ModulesRef.emplace_back(*M);
148
149 return ModulesRef;
150 }
151 void setExtractedModules(SmallVector<std::unique_ptr<Module>> &Modules) {
152 ExtractedModules = std::move(Modules);
153 }
154
155 bool hasModuleHash() const { return ExtractedModuleHash.has_value(); }
157 if (!hasModuleHash())
158 reportFatalError("Expected module hash to be set");
159
160 return ExtractedModuleHash.value();
161 }
162 void setModuleHash(HashT HashValue) { ExtractedModuleHash = HashValue; }
163 void updateModuleHash(HashT HashValue) {
164 if (ExtractedModuleHash)
165 ExtractedModuleHash = hashCombine(ExtractedModuleHash.value(), HashValue);
166 else
167 ExtractedModuleHash = HashValue;
168 }
169
171 if (!ModuleCallGraph.has_value()) {
172 if (!LinkedModule)
173 reportFatalError("Expected non-null linked module");
174 ModuleCallGraph.emplace(CallGraph(*LinkedModule));
175 }
176 return ModuleCallGraph.value();
177 }
178
179 bool hasDeviceBinary() { return (DeviceBinary != nullptr); }
181 if (!hasDeviceBinary())
182 reportFatalError("Expected non-null device binary");
183 return DeviceBinary->getMemBufferRef();
184 }
185 void setDeviceBinary(std::unique_ptr<MemoryBuffer> DeviceBinaryBuffer) {
186 DeviceBinary = std::move(DeviceBinaryBuffer);
187 }
188
189 void addModuleId(const char *ModuleId) {
190 LinkedModuleIds.push_back(ModuleId);
191 }
192
193 void registerGlobalVar(const char *VarName, const void *Addr,
195 VarNameToGlobalInfo.emplace(VarName, GlobalVarInfo(Addr, nullptr, VarSize));
196 }
197
198 void mapGlobals() {
199 std::call_once(Flag, [&]() {
200 for (auto &[GlobalName, GVI] : VarNameToGlobalInfo) {
201 void *DevPtr = resolveDeviceGlobalAddr(GVI.HostAddr);
202 VarNameToGlobalInfo.at(GlobalName).DevAddr = DevPtr;
203 }
204 auto TraceOut = [](std::unordered_map<std::string, GlobalVarInfo>
205 &VarNameToGlobalInfo) {
208 for (auto &[GlobalName, GVI] : VarNameToGlobalInfo) {
209 OS << "[GVarInfo]: " << GlobalName << " HAddr:" << GVI.HostAddr
210 << " DevAddr:" << GVI.DevAddr << " VarSize:" << GVI.VarSize
211 << "\n";
212 }
213
214 return S;
215 };
217 Logger::trace(TraceOut(VarNameToGlobalInfo));
218 GlobalsMapped = true;
219 });
220 }
221
222 std::unordered_map<std::string, GlobalVarInfo> &getVarNameToGlobalInfo() {
223 return VarNameToGlobalInfo;
224 }
225
226 auto &getModuleIds() { return LinkedModuleIds; }
227};
228
230 std::optional<void *> Kernel;
231 std::unique_ptr<LLVMContext> Ctx;
232 std::string Name;
234 std::optional<std::unique_ptr<Module>> ExtractedModule;
235 std::optional<std::unique_ptr<MemoryBuffer>> Bitcode;
236 std::optional<std::reference_wrapper<BinaryInfo>> BinInfo;
237 std::optional<HashT> StaticHash;
238 std::optional<SmallVector<std::pair<std::string, StringRef>>>
239 LambdaCalleeInfo;
240
241public:
242 JITKernelInfo(void *Kernel, BinaryInfo &BinInfo, char const *Name,
244 : Kernel(Kernel), Ctx(std::make_unique<LLVMContext>()), Name(Name),
245 RCInfoArray(RCInfoArray), ExtractedModule(std::nullopt),
246 Bitcode{std::nullopt}, BinInfo(BinInfo),
247 LambdaCalleeInfo(std::nullopt) {}
248
249 JITKernelInfo() = default;
250 void *getKernel() const {
251 assert(Kernel.has_value() && "Expected Kernel is inited");
252 return Kernel.value();
253 }
254 std::unique_ptr<LLVMContext> &getLLVMContext() { return Ctx; }
255 const std::string &getName() const { return Name; }
257 bool hasModule() const { return ExtractedModule.has_value(); }
258 Module &getModule() const { return *ExtractedModule->get(); }
259 BinaryInfo &getBinaryInfo() const { return BinInfo.value(); }
260 void setModule(std::unique_ptr<llvm::Module> Mod) {
261 ExtractedModule = std::move(Mod);
262 }
263
264 bool hasBitcode() { return Bitcode.has_value(); }
265 void setBitcode(std::unique_ptr<MemoryBuffer> ExtractedBitcode) {
266 Bitcode = std::move(ExtractedBitcode);
267 }
268 MemoryBufferRef getBitcode() { return Bitcode.value()->getMemBufferRef(); }
269
270 bool hasStaticHash() const { return StaticHash.has_value(); }
271 const HashT getStaticHash() const { return StaticHash.value(); }
272 void createStaticHash(HashT ModuleHash) {
273 StaticHash = hash(Name);
274 StaticHash = hashCombine(StaticHash.value(), ModuleHash);
275 }
276
277 bool hasLambdaCalleeInfo() { return LambdaCalleeInfo.has_value(); }
278 const auto &getLambdaCalleeInfo() { return LambdaCalleeInfo.value(); }
280 SmallVector<std::pair<std::string, StringRef>> &&LambdaInfo) {
281 LambdaCalleeInfo = std::move(LambdaInfo);
282 }
283};
284
285template <typename ImplT> struct DeviceTraits;
286
287template <typename ImplT> class JitEngineDevice : public JitEngine {
288public:
292
297
298 std::pair<std::unique_ptr<Module>, std::unique_ptr<MemoryBuffer>>
300 LLVMContext &Ctx) {
301 std::unique_ptr<Module> KernelModule =
302 static_cast<ImplT &>(*this).tryExtractKernelModule(BinInfo, KernelName,
303 Ctx);
304 std::unique_ptr<MemoryBuffer> Bitcode = nullptr;
305
306 // If there is no ready-made kernel module from AOT, extract per-TU or the
307 // single linked module and clone the kernel module.
308 if (!KernelModule) {
309 Timer T;
310 if (!BinInfo.hasExtractedModules())
311 static_cast<ImplT &>(*this).extractModules(BinInfo);
312
313 std::unique_ptr<Module> KernelModuleTmp = nullptr;
314 switch (Config::get().ProteusKernelClone) {
316 auto &LinkedModule = BinInfo.getLinkedModule();
317 KernelModule = llvm::CloneModule(LinkedModule);
318 break;
319 }
321 auto &LinkedModule = BinInfo.getLinkedModule();
324 break;
325 }
329 break;
330 }
331 default:
332 reportFatalError("Unsupported kernel cloning option");
333 }
334
336 << "Cloning "
337 << toString(Config::get().ProteusKernelClone) << " "
338 << T.elapsed() << " ms\n");
339 }
340
341 // Internalize and cleanup to simplify the module and prepare it for
342 // optimization.
345
346 // If the module is not in the provided context due to cloning, roundtrip
347 // it using bitcode. Re-use the roundtrip bitcode to return it.
348 if (&KernelModule->getContext() != &Ctx) {
355 if (auto E = ExpectedKernelModule.takeError())
356 reportFatalError("Error parsing bitcode: " + toString(std::move(E)));
357
359 Bitcode = MemoryBuffer::getMemBufferCopy(CloneStr);
360 } else {
361 // Parse the kernel module to create the bitcode since it has not been
362 // created by roundtripping.
366 auto BitcodeStr = StringRef{BitcodeBuffer.data(), BitcodeBuffer.size()};
367 Bitcode = MemoryBuffer::getMemBufferCopy(BitcodeStr);
368 }
369
370 return std::make_pair(std::move(KernelModule), std::move(Bitcode));
371 }
372
375
376 if (KernelInfo.hasModule() && KernelInfo.hasBitcode())
377 return;
378
379 if (KernelInfo.hasModule())
380 reportFatalError("Unexpected KernelInfo has module but not bitcode");
381
382 if (KernelInfo.hasBitcode())
383 reportFatalError("Unexpected KernelInfo has bitcode but not module");
384
385 BinaryInfo &BinInfo = KernelInfo.getBinaryInfo();
386
387 Timer T;
389 BinInfo, KernelInfo.getName(), *KernelInfo.getLLVMContext());
390
391 if (!KernelModule)
392 reportFatalError("Expected non-null kernel module");
393 if (!BitcodeBuffer)
394 reportFatalError("Expected non-null kernel bitcode");
395
396 KernelInfo.setModule(std::move(KernelModule));
397 KernelInfo.setBitcode(std::move(BitcodeBuffer));
399 << "Extract kernel module " << T.elapsed() << " ms\n");
400 }
401
403 if (!KernelInfo.hasModule())
405
406 if (!KernelInfo.hasModule())
407 reportFatalError("Expected module in KernelInfo");
408
409 return KernelInfo.getModule();
410 }
411
413 if (!KernelInfo.hasBitcode())
415
416 if (!KernelInfo.hasBitcode())
417 reportFatalError("Expected bitcode in KernelInfo");
418
419 return KernelInfo.getBitcode();
420 }
421
425 if (LR.empty()) {
426 KernelInfo.setLambdaCalleeInfo({});
427 return;
428 }
429
430 if (!KernelInfo.hasLambdaCalleeInfo()) {
432 PROTEUS_DBG(Logger::logs("proteus")
433 << "=== LAMBDA MATCHING\n"
434 << "Caller trigger " << KernelInfo.getName() << " -> "
435 << demangle(KernelInfo.getName()) << "\n");
436
438 for (auto &F : KernelModule.getFunctionList()) {
439 PROTEUS_DBG(Logger::logs("proteus")
440 << " Trying F " << demangle(F.getName().str()) << "\n ");
441 auto OptionalMapIt =
443 if (OptionalMapIt)
444 LambdaCalleeInfo.emplace_back(F.getName(),
445 OptionalMapIt.value()->first);
446 }
447
448 KernelInfo.setLambdaCalleeInfo(std::move(LambdaCalleeInfo));
449 }
450
451 for (auto &[FnName, LambdaType] : KernelInfo.getLambdaCalleeInfo()) {
453 LR.getJitVariables(LambdaType);
454 LambdaJitValuesVec.insert(LambdaJitValuesVec.end(), Values.begin(),
455 Values.end());
456 }
457 }
458
459 void insertRegisterVar(void *Handle, const char *VarName, const void *Addr,
461 if (!HandleToBinaryInfo.count(Handle))
462 reportFatalError("Expected Handle in map");
464
466 }
467
469 const char *ModuleId);
471 const char *ModuleId);
473 void registerFunction(void *Handle, void *Kernel, char *KernelName,
475
476 void *CurHandle = nullptr;
477 std::unordered_map<std::string, FatbinWrapperT *> ModuleIdToFatBinary;
478 std::unordered_map<const void *, BinaryInfo> HandleToBinaryInfo;
481
482 bool containsJITKernelInfo(const void *Func) {
483 return JITKernelInfoMap.contains(Func);
484 }
485
486 std::optional<std::reference_wrapper<JITKernelInfo>>
487 getJITKernelInfo(const void *Func) {
489 return std::nullopt;
490 }
491 return JITKernelInfoMap[Func];
492 }
493
495 if (KernelInfo.hasStaticHash())
496 return KernelInfo.getStaticHash();
497
498 BinaryInfo &BinInfo = KernelInfo.getBinaryInfo();
499
500 if (BinInfo.hasModuleHash()) {
501 KernelInfo.createStaticHash(BinInfo.getModuleHash());
502 return KernelInfo.getStaticHash();
503 }
504
505 HashT ModuleHash = static_cast<ImplT &>(*this).getModuleHash(BinInfo);
506
507 KernelInfo.createStaticHash(BinInfo.getModuleHash());
508 return KernelInfo.getStaticHash();
509 }
510
511 void finalize() {
512 if (Config::get().ProteusAsyncCompilation)
513 CompilerAsync::instance(Config::get().ProteusAsyncThreads)
515 }
516
518
519protected:
521
526
528 ObjectCacheChain LibraryCache{"JitEngineDevice"};
529 std::string DeviceArch;
530
532};
533
534template <typename ImplT>
537 JITKernelInfo &KernelInfo, dim3 GridDim, dim3 BlockDim, void **KernelArgs,
539 TIMESCOPE("compileAndRun");
540
541 auto &BinInfo = KernelInfo.getBinaryInfo();
542
543 // Lazy initialize the map of device global variables to device pointers by
544 // resolving the host address to the device address. For HIP it is fine to
545 // do this earlier (e.g., instertRegisterVar), but CUDA can't. So, we
546 // initialize this here the first time we need to compile a kernel.
547 BinInfo.mapGlobals();
548
550 getRuntimeConstantValues(KernelArgs, KernelInfo.getRCInfoArray());
551
554
555 HashT HashValue =
556 hash(getStaticHash(KernelInfo), RCVec, LambdaJitValuesVec, GridDim.x,
557 GridDim.y, GridDim.z, BlockDim.x, BlockDim.y, BlockDim.z);
558
560 CodeCache.lookup(HashValue);
561 if (KernelFunc)
562 return launchKernelFunction(KernelFunc, GridDim, BlockDim, KernelArgs,
564
565 // NOTE: we don't need a suffix to differentiate kernels, each
566 // specialization will be in its own module uniquely identify by HashValue.
567 // It exists only for debugging purposes to verify that the jitted kernel
568 // executes.
569 std::string Suffix = HashValue.toMangledSuffix();
570 std::string KernelMangled = (KernelInfo.getName() + Suffix);
571
573 auto CompiledLib = LibraryCache.lookup(HashValue);
574 if (CompiledLib) {
576 relinkGlobalsObject(CompiledLib->ObjectModule->getMemBufferRef(),
577 BinInfo.getVarNameToGlobalInfo());
578
580 KernelMangled, CompiledLib->ObjectModule->getBufferStart(),
582 BinInfo.getVarNameToGlobalInfo());
583
584 CodeCache.insert(HashValue, KernelFunc, KernelInfo.getName());
585
586 return launchKernelFunction(KernelFunc, GridDim, BlockDim, KernelArgs,
588 }
589 }
590
592 std::unique_ptr<MemoryBuffer> ObjBuf = nullptr;
593
594 if (Config::get().ProteusAsyncCompilation) {
595 auto &Compiler = CompilerAsync::instance(Config::get().ProteusAsyncThreads);
596 // If there is no compilation pending for the specialization, post the
597 // compilation task to the compiler.
598 if (!Compiler.isCompilationPending(HashValue)) {
599 PROTEUS_DBG(Logger::logs("proteus") << "Compile async for HashValue "
600 << HashValue.toString() << "\n");
601
603 KernelBitcode, HashValue, KernelInfo.getName(), Suffix, BlockDim,
604 GridDim, RCVec, KernelInfo.getLambdaCalleeInfo(),
605 BinInfo.getVarNameToGlobalInfo(), GlobalLinkedBinaries, DeviceArch,
606 /*CodeGenConfig */ Config::get().getCGConfig(KernelInfo.getName()),
607 /*DumpIR*/ Config::get().ProteusDumpLLVMIR,
608 /*RelinkGlobalsByCopy*/ Config::get().ProteusRelinkGlobalsByCopy});
609 }
610
611 // Compilation is pending, try to get the compilation result buffer. If
612 // buffer is null, compilation is not done, so execute the AOT version
613 // directly.
614 ObjBuf = Compiler.takeCompilationResult(
615 HashValue, Config::get().ProteusAsyncTestBlocking);
616 if (!ObjBuf) {
617 return launchKernelDirect(KernelInfo.getKernel(), GridDim, BlockDim,
619 }
620 } else {
621 // Process through synchronous compilation.
623 KernelBitcode, HashValue, KernelInfo.getName(), Suffix, BlockDim,
624 GridDim, RCVec, KernelInfo.getLambdaCalleeInfo(),
625 BinInfo.getVarNameToGlobalInfo(), GlobalLinkedBinaries, DeviceArch,
626 /*CodeGenConfig */ Config::get().getCGConfig(KernelInfo.getName()),
627 /*DumpIR*/ Config::get().ProteusDumpLLVMIR,
628 /*RelinkGlobalsByCopy*/ Config::get().ProteusRelinkGlobalsByCopy});
629 }
630
631 if (!ObjBuf)
632 reportFatalError("Expected non-null object");
633
635 KernelMangled, ObjBuf->getBufferStart(),
637 BinInfo.getVarNameToGlobalInfo());
638
639 CodeCache.insert(HashValue, KernelFunc, KernelInfo.getName());
640 if (Config::get().ProteusUseStoredCache) {
641 LibraryCache.store(HashValue,
642 CacheEntry::staticObject(ObjBuf->getMemBufferRef()));
643 }
644
645 return launchKernelFunction(KernelFunc, GridDim, BlockDim, KernelArgs,
647}
648
649template <typename ImplT>
652 const char *ModuleId) {
653 CurHandle = Handle;
654 PROTEUS_DBG(Logger::logs("proteus")
655 << "Register fatbinary Handle " << Handle << " FatbinWrapper "
656 << FatbinWrapper << " Binary " << (void *)FatbinWrapper->Binary
657 << " ModuleId " << ModuleId << "\n");
658 if (FatbinWrapper->PrelinkedFatbins) {
659 // This is RDC compilation, just insert the FatbinWrapper and ignore the
660 // ModuleId coming from the link.stub.
661 HandleToBinaryInfo.try_emplace(Handle, FatbinWrapper,
663
664 // Initialize GlobalLinkedBinaries with prelinked fatbins.
665 void *Ptr = FatbinWrapper->PrelinkedFatbins[0];
666 for (int I = 0; Ptr != nullptr;
667 ++I, Ptr = FatbinWrapper->PrelinkedFatbins[I]) {
668 PROTEUS_DBG(Logger::logs("proteus")
669 << "I " << I << " PrelinkedFatbin " << Ptr << "\n");
670 GlobalLinkedBinaries.insert(Ptr);
671 }
672 } else {
673 // This is non-RDC compilation, associate the ModuleId of the JIT bitcode
674 // in the module with the FatbinWrapper.
675 ModuleIdToFatBinary[ModuleId] = FatbinWrapper;
676 HandleToBinaryInfo.try_emplace(Handle, FatbinWrapper,
678 }
679}
680
681template <typename ImplT> void JitEngineDevice<ImplT>::registerFatBinaryEnd() {
682 PROTEUS_DBG(Logger::logs("proteus") << "Register fatbinary end\n");
683 // Erase linked binaries for which we have LLVM IR code, those binaries are
684 // stored in the ModuleIdToFatBinary map.
685 for (auto &[ModuleId, FatbinWrapper] : ModuleIdToFatBinary)
686 GlobalLinkedBinaries.erase((void *)FatbinWrapper->Binary);
687
688 CurHandle = nullptr;
689}
690
691template <typename ImplT>
693 void *Handle, void *Kernel, char *KernelName,
695 PROTEUS_DBG(Logger::logs("proteus") << "Register function " << Kernel
696 << " To Handle " << Handle << "\n");
697 // NOTE: HIP RDC might call multiple times the registerFunction for the same
698 // kernel, which has weak linkage, when it comes from different translation
699 // units. Either the first or the second call can prevail and should be
700 // equivalent. We let the first one prevail.
701 if (JITKernelInfoMap.contains(Kernel)) {
702 PROTEUS_DBG(Logger::logs("proteus")
703 << "Warning: duplicate register function for kernel " +
704 std::string(KernelName)
705 << "\n");
706 return;
707 }
708
709 if (!HandleToBinaryInfo.count(Handle))
710 reportFatalError("Expected Handle in map");
711 BinaryInfo &BinInfo = HandleToBinaryInfo[Handle];
712
713 PROTEUS_DBG(Logger::logs("proteus")
714 << "Register function " << KernelName << " with binary handle "
715 << Handle << "\n");
716
717 JITKernelInfoMap[Kernel] =
719}
720
721template <typename ImplT>
723 const char *ModuleId) {
724 PROTEUS_DBG(Logger::logs("proteus")
725 << "Register linked binary FatBinary " << FatbinWrapper
726 << " Binary " << (void *)FatbinWrapper->Binary << " ModuleId "
727 << ModuleId << "\n");
728 if (CurHandle) {
729 if (!HandleToBinaryInfo.count(CurHandle))
730 reportFatalError("Expected CurHandle in map");
731
732 HandleToBinaryInfo[CurHandle].addModuleId(ModuleId);
733 } else
734 GlobalLinkedModuleIds.push_back(ModuleId);
735
736 ModuleIdToFatBinary[ModuleId] = FatbinWrapper;
737}
738
739} // namespace proteus
740
741#endif
void const char * ModuleId
Definition CompilerInterfaceDevice.cpp:33
void * FatbinWrapper
Definition CompilerInterfaceDevice.cpp:32
const void const char * VarName
Definition CompilerInterfaceDevice.cpp:21
void char * KernelName
Definition CompilerInterfaceDevice.cpp:52
void * Kernel
Definition CompilerInterfaceDevice.cpp:52
const void const char uint64_t VarSize
Definition CompilerInterfaceDevice.cpp:22
ArrayRef< RuntimeConstantInfo * > RCInfoArray
Definition CompilerInterfaceHost.cpp:24
#define PROTEUS_DBG(x)
Definition Debug.h:9
void getLambdaJitValues(StringRef FnName, SmallVector< RuntimeConstant > &LambdaJitValuesVec)
Definition JitEngineHost.cpp:175
#define TIMESCOPE(x)
Definition TimeTracing.hpp:59
#define PROTEUS_TIMER_OUTPUT(x)
Definition TimeTracing.hpp:54
Definition JitEngineDevice.hpp:79
FatbinWrapperT * getFatbinWrapper() const
Definition JitEngineDevice.hpp:102
void mapGlobals()
Definition JitEngineDevice.hpp:198
void setExtractedModules(SmallVector< std::unique_ptr< Module > > &Modules)
Definition JitEngineDevice.hpp:151
std::unordered_map< std::string, GlobalVarInfo > & getVarNameToGlobalInfo()
Definition JitEngineDevice.hpp:222
MemoryBufferRef getDeviceBinary()
Definition JitEngineDevice.hpp:180
bool hasModuleHash() const
Definition JitEngineDevice.hpp:155
std::unique_ptr< LLVMContext > & getLLVMContext()
Definition JitEngineDevice.hpp:104
Module & getLinkedModule()
Definition JitEngineDevice.hpp:107
auto & getModuleIds()
Definition JitEngineDevice.hpp:226
void registerGlobalVar(const char *VarName, const void *Addr, uint64_t VarSize)
Definition JitEngineDevice.hpp:193
bool hasLinkedModule() const
Definition JitEngineDevice.hpp:106
bool hasDeviceBinary()
Definition JitEngineDevice.hpp:179
const SmallVector< std::reference_wrapper< Module > > getExtractedModules() const
Definition JitEngineDevice.hpp:142
void updateModuleHash(HashT HashValue)
Definition JitEngineDevice.hpp:163
HashT getModuleHash() const
Definition JitEngineDevice.hpp:156
bool hasExtractedModules() const
Definition JitEngineDevice.hpp:140
void addModuleId(const char *ModuleId)
Definition JitEngineDevice.hpp:189
CallGraph & getCallGraph()
Definition JitEngineDevice.hpp:170
BinaryInfo(FatbinWrapperT *FatbinWrapper, SmallVector< std::string > &&LinkedModuleIds)
Definition JitEngineDevice.hpp:95
void setModuleHash(HashT HashValue)
Definition JitEngineDevice.hpp:162
void setDeviceBinary(std::unique_ptr< MemoryBuffer > DeviceBinaryBuffer)
Definition JitEngineDevice.hpp:185
Definition CompilationTask.hpp:19
static CompilerAsync & instance(int NumThreads)
Definition CompilerAsync.hpp:49
void joinAllThreads()
Definition CompilerAsync.hpp:88
std::unique_ptr< MemoryBuffer > compile(CompilationTask &&CT)
Definition CompilerSync.hpp:21
static CompilerSync & instance()
Definition CompilerSync.hpp:16
int ProteusTraceOutput
Definition Config.hpp:315
static Config & get()
Definition Config.hpp:300
bool ProteusRelinkGlobalsByCopy
Definition Config.hpp:309
bool ProteusDumpLLVMIR
Definition Config.hpp:308
bool ProteusUseStoredCache
Definition Config.hpp:306
const CodeGenerationConfig & getCGConfig(llvm::StringRef KName="") const
Definition Config.hpp:322
Definition Func.hpp:431
Definition Hashing.hpp:21
std::string toString() const
Definition Hashing.hpp:29
std::string toMangledSuffix() const
Definition Hashing.hpp:32
Definition JitEngineDevice.hpp:229
bool hasBitcode()
Definition JitEngineDevice.hpp:264
const std::string & getName() const
Definition JitEngineDevice.hpp:255
void createStaticHash(HashT ModuleHash)
Definition JitEngineDevice.hpp:272
JITKernelInfo(void *Kernel, BinaryInfo &BinInfo, char const *Name, ArrayRef< RuntimeConstantInfo * > RCInfoArray)
Definition JitEngineDevice.hpp:242
void * getKernel() const
Definition JitEngineDevice.hpp:250
bool hasModule() const
Definition JitEngineDevice.hpp:257
const HashT getStaticHash() const
Definition JitEngineDevice.hpp:271
BinaryInfo & getBinaryInfo() const
Definition JitEngineDevice.hpp:259
ArrayRef< RuntimeConstantInfo * > getRCInfoArray() const
Definition JitEngineDevice.hpp:256
Module & getModule() const
Definition JitEngineDevice.hpp:258
void setModule(std::unique_ptr< llvm::Module > Mod)
Definition JitEngineDevice.hpp:260
void setLambdaCalleeInfo(SmallVector< std::pair< std::string, StringRef > > &&LambdaInfo)
Definition JitEngineDevice.hpp:279
const auto & getLambdaCalleeInfo()
Definition JitEngineDevice.hpp:278
bool hasLambdaCalleeInfo()
Definition JitEngineDevice.hpp:277
MemoryBufferRef getBitcode()
Definition JitEngineDevice.hpp:268
bool hasStaticHash() const
Definition JitEngineDevice.hpp:270
std::unique_ptr< LLVMContext > & getLLVMContext()
Definition JitEngineDevice.hpp:254
void setBitcode(std::unique_ptr< MemoryBuffer > ExtractedBitcode)
Definition JitEngineDevice.hpp:265
Definition JitEngineDevice.hpp:287
MemoryBufferRef getBitcode(JITKernelInfo &KernelInfo)
Definition JitEngineDevice.hpp:412
~JitEngineDevice()
Definition JitEngineDevice.hpp:522
typename DeviceTraits< ImplT >::DeviceError_t DeviceError_t
Definition JitEngineDevice.hpp:289
void extractModuleAndBitcode(JITKernelInfo &KernelInfo)
Definition JitEngineDevice.hpp:373
void registerLinkedBinary(FatbinWrapperT *FatbinWrapper, const char *ModuleId)
Definition JitEngineDevice.hpp:722
JitEngineDevice()
Definition JitEngineDevice.hpp:520
std::unordered_map< const void *, BinaryInfo > HandleToBinaryInfo
Definition JitEngineDevice.hpp:478
DenseMap< const void *, JITKernelInfo > JITKernelInfoMap
Definition JitEngineDevice.hpp:531
typename DeviceTraits< ImplT >::DeviceStream_t DeviceStream_t
Definition JitEngineDevice.hpp:290
void registerFatBinaryEnd()
Definition JitEngineDevice.hpp:681
MemoryCache< KernelFunction_t > CodeCache
Definition JitEngineDevice.hpp:527
Module & getModule(JITKernelInfo &KernelInfo)
Definition JitEngineDevice.hpp:402
ObjectCacheChain LibraryCache
Definition JitEngineDevice.hpp:528
bool containsJITKernelInfo(const void *Func)
Definition JitEngineDevice.hpp:482
std::optional< std::reference_wrapper< JITKernelInfo > > getJITKernelInfo(const void *Func)
Definition JitEngineDevice.hpp:487
std::pair< std::unique_ptr< Module >, std::unique_ptr< MemoryBuffer > > extractKernelModule(BinaryInfo &BinInfo, StringRef KernelName, LLVMContext &Ctx)
Definition JitEngineDevice.hpp:299
SmallPtrSet< void *, 8 > GlobalLinkedBinaries
Definition JitEngineDevice.hpp:480
void registerFunction(void *Handle, void *Kernel, char *KernelName, ArrayRef< RuntimeConstantInfo * > RCInfoArray)
Definition JitEngineDevice.hpp:692
void insertRegisterVar(void *Handle, const char *VarName, const void *Addr, uint64_t VarSize)
Definition JitEngineDevice.hpp:459
void finalize()
Definition JitEngineDevice.hpp:511
void * CurHandle
Definition JitEngineDevice.hpp:476
void registerFatBinary(void *Handle, FatbinWrapperT *FatbinWrapper, const char *ModuleId)
Definition JitEngineDevice.hpp:650
DeviceError_t compileAndRun(JITKernelInfo &KernelInfo, dim3 GridDim, dim3 BlockDim, void **KernelArgs, uint64_t ShmemSize, typename DeviceTraits< ImplT >::DeviceStream_t Stream)
Definition JitEngineDevice.hpp:536
std::unordered_map< std::string, FatbinWrapperT * > ModuleIdToFatBinary
Definition JitEngineDevice.hpp:477
typename DeviceTraits< ImplT >::KernelFunction_t KernelFunction_t
Definition JitEngineDevice.hpp:291
SmallVector< std::string > GlobalLinkedModuleIds
Definition JitEngineDevice.hpp:479
StringRef getDeviceArch() const
Definition JitEngineDevice.hpp:517
std::string DeviceArch
Definition JitEngineDevice.hpp:529
HashT getStaticHash(JITKernelInfo &KernelInfo)
Definition JitEngineDevice.hpp:494
void getLambdaJitValues(JITKernelInfo &KernelInfo, SmallVector< RuntimeConstant > &LambdaJitValuesVec)
Definition JitEngineDevice.hpp:422
Definition JitEngine.hpp:31
Definition LambdaRegistry.hpp:20
std::optional< DenseMap< StringRef, SmallVector< RuntimeConstant > >::iterator > matchJitVariableMap(StringRef FnName)
Definition LambdaRegistry.hpp:28
static LambdaRegistry & instance()
Definition LambdaRegistry.hpp:22
static llvm::raw_ostream & outs(const std::string &Name)
Definition Logger.hpp:25
static void trace(llvm::StringRef Msg)
Definition Logger.hpp:30
static llvm::raw_ostream & logs(const std::string &Name)
Definition Logger.hpp:19
Definition MemoryCache.hpp:28
void printStats()
Definition MemoryCache.hpp:62
Definition ObjectCacheChain.hpp:30
void printStats()
Definition ObjectCacheChain.cpp:136
Definition TimeTracing.hpp:40
Definition Helpers.h:141
Definition ObjectCacheChain.cpp:26
std::unique_ptr< Module > cloneKernelFromModules(ArrayRef< std::reference_wrapper< Module > > Mods, StringRef EntryName, function_ref< bool(const GlobalValue *)> ShouldCloneDefinition=nullptr)
Definition Cloning.h:513
HashT hash(FirstT &&First, RestTs &&...Rest)
Definition Hashing.hpp:142
void reportFatalError(const llvm::Twine &Reason, const char *FILE, unsigned Line)
Definition Error.cpp:14
cudaError_t launchKernelDirect(void *KernelFunc, dim3 GridDim, dim3 BlockDim, void **KernelArgs, uint64_t ShmemSize, CUstream Stream)
Definition CoreDeviceCUDA.hpp:21
T getRuntimeConstantValue(void *Arg)
Definition CompilerInterfaceRuntimeConstantInfo.h:113
cudaError_t launchKernelFunction(CUfunction KernelFunc, dim3 GridDim, dim3 BlockDim, void **KernelArgs, uint64_t ShmemSize, CUstream Stream)
Definition CoreDeviceCUDA.hpp:56
HashT hashCombine(HashT A, HashT B)
Definition Hashing.hpp:137
std::string toString(CodegenOption Option)
Definition Config.hpp:26
void * resolveDeviceGlobalAddr(const void *Addr)
Definition CoreDeviceCUDA.hpp:13
void internalize(Module &M, StringRef PreserveFunctionName)
Definition CoreLLVM.hpp:288
CUfunction getKernelFunctionFromImage(StringRef KernelName, const void *Image, bool RelinkGlobalsByCopy, const std::unordered_map< std::string, GlobalVarInfo > &VarNameToGlobalInfo)
Definition CoreDeviceCUDA.hpp:28
void runCleanupPassPipeline(Module &M)
Definition CoreLLVM.hpp:230
std::unique_ptr< Module > linkModules(LLVMContext &Ctx, SmallVector< std::unique_ptr< Module > > LinkedModules)
Definition CoreLLVM.hpp:213
Definition Hashing.hpp:158
static CacheEntry staticObject(MemoryBufferRef Buf)
Definition ObjectCache.hpp:31
Definition JitEngineDevice.hpp:285
Definition JitEngineDevice.hpp:72
const char * Binary
Definition JitEngineDevice.hpp:75
void ** PrelinkedFatbins
Definition JitEngineDevice.hpp:76
int32_t Magic
Definition JitEngineDevice.hpp:73
int32_t Version
Definition JitEngineDevice.hpp:74
Definition GlobalVarInfo.hpp:5