Proteus
Programmable JIT compilation and optimization for C/C++ using LLVM
Loading...
Searching...
No Matches
CoreLLVMCUDA.hpp
Go to the documentation of this file.
1#ifndef PROTEUS_CORE_LLVM_CUDA_HPP
2#define PROTEUS_CORE_LLVM_CUDA_HPP
3
4#include <llvm/ADT/SmallVector.h>
5#include <llvm/ADT/StringRef.h>
6#include <llvm/CodeGen/MachineModuleInfo.h>
7#include <llvm/IR/LegacyPassManager.h>
8#include <llvm/IR/Module.h>
9#include <llvm/Support/MemoryBufferRef.h>
10#include <llvm/Support/TargetSelect.h>
11#include <llvm/Target/TargetMachine.h>
12
14#include "proteus/Debug.h"
15#include "proteus/Logger.hpp"
17#include "proteus/UtilsCUDA.h"
18
19namespace proteus {
20
21using namespace llvm;
22
23namespace detail {
24
25inline const SmallVector<StringRef> &gridDimXFnName() {
26 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.nctaid.x"};
27 return Names;
28}
29
30inline const SmallVector<StringRef> &gridDimYFnName() {
31 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.nctaid.y"};
32 return Names;
33}
34
35inline const SmallVector<StringRef> &gridDimZFnName() {
36 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.nctaid.z"};
37 return Names;
38}
39
40inline const SmallVector<StringRef> &blockDimXFnName() {
41 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ntid.x"};
42 return Names;
43}
44
45inline const SmallVector<StringRef> &blockDimYFnName() {
46 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ntid.y"};
47 return Names;
48}
49
50inline const SmallVector<StringRef> &blockDimZFnName() {
51 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ntid.z"};
52 return Names;
53}
54
55inline const SmallVector<StringRef> &blockIdxXFnName() {
56 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ctaid.x"};
57 return Names;
58}
59
60inline const SmallVector<StringRef> &blockIdxYFnName() {
61 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ctaid.y"};
62 return Names;
63}
64
65inline const SmallVector<StringRef> &blockIdxZFnName() {
66 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ctaid.z"};
67 return Names;
68}
69
70inline const SmallVector<StringRef> &threadIdxXFnName() {
71 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.tid.x"};
72 return Names;
73}
74
75inline const SmallVector<StringRef> &threadIdxYFnName() {
76 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.tid.y"};
77 return Names;
78}
79
80inline const SmallVector<StringRef> &threadIdxZFnName() {
81 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.tid.z"};
82 return Names;
83}
84
85} // namespace detail
86
87inline void setLaunchBoundsForKernel(Function &F, int MaxThreadsPerSM,
88 int MinBlocksPerSM = 0) {
89 auto *M = F.getParent();
90 NamedMDNode *NvvmAnnotations = M->getNamedMetadata("nvvm.annotations");
91 assert(NvvmAnnotations && "Expected non-null nvvm.annotations metadata");
92 auto *FuncMetadata = ConstantAsMetadata::get(&F);
93
94 auto SetMDNode = [&](const char *MDName, int MDValue) {
95 auto *MDNodeName = MDString::get(M->getContext(), MDName);
96 auto *MDNodeValue = ConstantAsMetadata::get(
97 ConstantInt::get(Type::getInt32Ty(M->getContext()), MDValue));
98
99 for (auto *MetadataNode : NvvmAnnotations->operands()) {
100 // Expecting 3 operands ptr, desc, i32 value.
101 assert(MetadataNode->getNumOperands() == 3);
102
103 auto *PtrMetadata = MetadataNode->getOperand(0).get();
104 auto *DescMetadata = MetadataNode->getOperand(1).get();
105 if (PtrMetadata == FuncMetadata && MDNodeName == DescMetadata) {
106 MetadataNode->replaceOperandWith(2, MDNodeValue);
107 return;
108 }
109 }
110 Metadata *MDVals[] = {FuncMetadata, MDNodeName, MDNodeValue};
111 NvvmAnnotations->addOperand(MDNode::get(M->getContext(), MDVals));
112 };
113
114 // TODO: fix hardcoded 1024 as the maximum, by reading device
115 // properties.
116 SetMDNode("maxntid", std::min(1024, MaxThreadsPerSM));
117 if (MinBlocksPerSM != 0)
118 SetMDNode("minctasm", MinBlocksPerSM);
119}
120
121inline void codegenPTX(Module &M, StringRef DeviceArch,
122 SmallVectorImpl<char> &PTXStr) {
123 // TODO: It is possbile to use PTX directly through the CUDA PTX JIT
124 // interface. Maybe useful if we can re-link globals using the CUDA API.
125 // Check this reference for PTX JIT caching:
126 // https://developer.nvidia.com/blog/cuda-pro-tip-understand-fat-binaries-jit-caching/
127 // Interesting env vars: CUDA_CACHE_DISABLE, CUDA_CACHE_MAXSIZE,
128 // CUDA_CACHE_PATH, CUDA_FORCE_PTX_JIT.
129
130 Timer T;
131 auto TMExpected = proteus::detail::createTargetMachine(M, DeviceArch);
132 if (!TMExpected)
133 PROTEUS_FATAL_ERROR(toString(TMExpected.takeError()));
134
135 std::unique_ptr<TargetMachine> TM = std::move(*TMExpected);
136 TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
137 M.setDataLayout(TM->createDataLayout());
138
139 legacy::PassManager PM;
140 PM.add(new TargetLibraryInfoWrapperPass(TLII));
141 MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(
142 reinterpret_cast<LLVMTargetMachine *>(TM.get()));
143
144 raw_svector_ostream PTXOS(PTXStr);
145#if LLVM_VERSION_MAJOR >= 18
146 TM->addPassesToEmitFile(PM, PTXOS, nullptr, CodeGenFileType::AssemblyFile,
147 /* DisableVerify */ false, MMIWP);
148#else
149 TM->addPassesToEmitFile(PM, PTXOS, nullptr, CGFT_AssemblyFile,
150 /* DisableVerify */ false, MMIWP);
151#endif
152
153 PM.run(M);
154
156 << "Codegen ptx " << T.elapsed() << " ms\n");
157}
158
159inline std::unique_ptr<MemoryBuffer>
160codegenObject(Module &M, StringRef DeviceArch,
161 SmallPtrSetImpl<void *> &GlobalLinkedBinaries,
163 if (CGOption != CodegenOption::RTC)
164 PROTEUS_FATAL_ERROR("Only RTC compilation is supported for CUDA");
165 SmallVector<char, 4096> PTXStr;
166 size_t BinSize;
167
168 codegenPTX(M, DeviceArch, PTXStr);
169 PTXStr.push_back('\0');
170
171 Timer T;
172 nvPTXCompilerHandle PTXCompiler;
174 nvPTXCompilerCreate(&PTXCompiler, PTXStr.size(), PTXStr.data()));
175 std::string ArchOpt = ("--gpu-name=" + DeviceArch).str();
176 std::string RDCOption = "";
177 if (!GlobalLinkedBinaries.empty())
178 RDCOption = "-c";
179#if PROTEUS_ENABLE_DEBUG
180 const char *CompileOptions[] = {ArchOpt.c_str(), "--verbose",
181 RDCOption.c_str()};
182 size_t NumCompileOptions = 2 + (RDCOption.empty() ? 0 : 1);
183#else
184 const char *CompileOptions[] = {ArchOpt.c_str(), RDCOption.c_str()};
185 size_t NumCompileOptions = 1 + (RDCOption.empty() ? 0 : 1);
186#endif
188 nvPTXCompilerCompile(PTXCompiler, NumCompileOptions, CompileOptions));
190 nvPTXCompilerGetCompiledProgramSize(PTXCompiler, &BinSize));
191 auto ObjBuf = WritableMemoryBuffer::getNewUninitMemBuffer(BinSize);
193 nvPTXCompilerGetCompiledProgram(PTXCompiler, ObjBuf->getBufferStart()));
194#if PROTEUS_ENABLE_DEBUG
195 {
196 size_t LogSize;
198 nvPTXCompilerGetInfoLogSize(PTXCompiler, &LogSize));
199 auto Log = std::make_unique<char[]>(LogSize);
201 nvPTXCompilerGetInfoLog(PTXCompiler, Log.get()));
202 Logger::logs("proteus") << "=== nvPTXCompiler Log\n" << Log.get() << "\n";
203 }
204#endif
205 proteusNvPTXCompilerErrCheck(nvPTXCompilerDestroy(&PTXCompiler));
206
207 std::unique_ptr<MemoryBuffer> FinalObjBuf;
208 if (!GlobalLinkedBinaries.empty()) {
209 // Create CUDA context if needed. This is required by threaded async
210 // compilation.
211 CUcontext CUCtx;
212 proteusCuErrCheck(cuCtxGetCurrent(&CUCtx));
213 if (!CUCtx) {
214 CUdevice CUDev;
215 CUresult CURes = cuCtxGetDevice(&CUDev);
216 if (CURes == CUDA_ERROR_INVALID_CONTEXT or !CUDev)
217 proteusCuErrCheck(cuDeviceGet(&CUDev, 0));
218
219 proteusCuErrCheck(cuCtxGetCurrent(&CUCtx));
220 proteusCuErrCheck(cuCtxCreate(&CUCtx, 0, CUDev));
221 }
222
223 // TODO: re-implement using the more recent nvJitLink interface.
224 CUlinkState CULinkState;
225 proteusCuErrCheck(cuLinkCreate(0, nullptr, nullptr, &CULinkState));
226 for (auto *Ptr : GlobalLinkedBinaries) {
227 // We do not know the size of the binary but the CUDA API just needs a
228 // non-zero argument.
229 proteusCuErrCheck(cuLinkAddData(CULinkState, CU_JIT_INPUT_FATBINARY, Ptr,
230 1, "", 0, 0, 0));
231 }
232
233 // Again using a non-zero argument, though we can get the size from the ptx
234 // compiler.
235 proteusCuErrCheck(cuLinkAddData(
236 CULinkState, CU_JIT_INPUT_FATBINARY,
237 static_cast<void *>(ObjBuf->getBufferStart()), 1, "", 0, 0, 0));
238
239 void *BinOut;
240 size_t BinSize;
241 proteusCuErrCheck(cuLinkComplete(CULinkState, &BinOut, &BinSize));
242 FinalObjBuf = MemoryBuffer::getMemBufferCopy(
243 StringRef{static_cast<char *>(BinOut), BinSize});
244 } else {
245 FinalObjBuf = std::move(ObjBuf);
246 }
247
249 << "Codegen CUDA RTC " << T.elapsed() << " ms\n");
250 return FinalObjBuf;
251}
252
253} // namespace proteus
254
255#endif
#define PROTEUS_FATAL_ERROR(x)
Definition Error.h:7
#define PROTEUS_TIMER_OUTPUT(x)
Definition TimeTracing.hpp:57
#define proteusNvPTXCompilerErrCheck(CALL)
Definition UtilsCUDA.h:39
#define proteusCuErrCheck(CALL)
Definition UtilsCUDA.h:28
static llvm::raw_ostream & outs(const std::string &Name)
Definition Logger.hpp:25
static llvm::raw_ostream & logs(const std::string &Name)
Definition Logger.hpp:19
Definition TimeTracing.hpp:36
uint64_t elapsed()
Definition TimeTracing.hpp:45
Definition Helpers.h:76
const SmallVector< StringRef > & threadIdxXFnName()
Definition CoreLLVMCUDA.hpp:70
const SmallVector< StringRef > & gridDimYFnName()
Definition CoreLLVMCUDA.hpp:30
const SmallVector< StringRef > & threadIdxZFnName()
Definition CoreLLVMCUDA.hpp:80
const SmallVector< StringRef > & blockIdxZFnName()
Definition CoreLLVMCUDA.hpp:65
const SmallVector< StringRef > & gridDimZFnName()
Definition CoreLLVMCUDA.hpp:35
const SmallVector< StringRef > & gridDimXFnName()
Definition CoreLLVMCUDA.hpp:25
const SmallVector< StringRef > & blockIdxXFnName()
Definition CoreLLVMCUDA.hpp:55
Expected< std::unique_ptr< TargetMachine > > createTargetMachine(Module &M, StringRef Arch, unsigned OptLevel=3)
Definition CoreLLVM.hpp:52
const SmallVector< StringRef > & threadIdxYFnName()
Definition CoreLLVMCUDA.hpp:75
const SmallVector< StringRef > & blockIdxYFnName()
Definition CoreLLVMCUDA.hpp:60
const SmallVector< StringRef > & blockDimYFnName()
Definition CoreLLVMCUDA.hpp:45
const SmallVector< StringRef > & blockDimZFnName()
Definition CoreLLVMCUDA.hpp:50
const SmallVector< StringRef > & blockDimXFnName()
Definition CoreLLVMCUDA.hpp:40
Definition BuiltinsCUDA.cpp:4
void codegenPTX(Module &M, StringRef DeviceArch, SmallVectorImpl< char > &PTXStr)
Definition CoreLLVMCUDA.hpp:121
void setLaunchBoundsForKernel(Function &F, int MaxThreadsPerSM, int MinBlocksPerSM=0)
Definition CoreLLVMCUDA.hpp:87
CodegenOption
Definition Config.hpp:11
std::unique_ptr< MemoryBuffer > codegenObject(Module &M, StringRef DeviceArch, SmallPtrSetImpl< void * > &GlobalLinkedBinaries, CodegenOption CGOption=CodegenOption::RTC)
Definition CoreLLVMCUDA.hpp:160
std::string toString(CodegenOption Option)
Definition Config.hpp:23