xref: /libCEED/backends/cuda/ceed-cuda-compile.cpp (revision 2027fb9d13fe34211738d8539f90542a9801ae2c)
1d275d636SJeremy L Thompson // Copyright (c) 2017-2025, Lawrence Livermore National Security, LLC and other CEED contributors.
2c9c2c079SJeremy L Thompson // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3c9c2c079SJeremy L Thompson //
4c9c2c079SJeremy L Thompson // SPDX-License-Identifier: BSD-2-Clause
5c9c2c079SJeremy L Thompson //
6c9c2c079SJeremy L Thompson // This file is part of CEED:  http://github.com/ceed
7c9c2c079SJeremy L Thompson 
82b730f8bSJeremy L Thompson #include "ceed-cuda-compile.h"
92b730f8bSJeremy L Thompson 
1049aac155SJeremy L Thompson #include <ceed.h>
11c9c2c079SJeremy L Thompson #include <ceed/backend.h>
12c9c2c079SJeremy L Thompson #include <ceed/jit-tools.h>
13c9c2c079SJeremy L Thompson #include <cuda_runtime.h>
14*2027fb9dSSirAlienTheGreat #include <dirent.h>
15c9c2c079SJeremy L Thompson #include <nvrtc.h>
16c9c2c079SJeremy L Thompson #include <stdarg.h>
17c9c2c079SJeremy L Thompson #include <string.h>
18*2027fb9dSSirAlienTheGreat #include <sys/types.h>
192b730f8bSJeremy L Thompson 
20*2027fb9dSSirAlienTheGreat #include <cstdlib>
21*2027fb9dSSirAlienTheGreat #include <fstream>
22*2027fb9dSSirAlienTheGreat #include <iostream>
232b730f8bSJeremy L Thompson #include <sstream>
24*2027fb9dSSirAlienTheGreat #include <string>
252b730f8bSJeremy L Thompson 
26c9c2c079SJeremy L Thompson #include "ceed-cuda-common.h"
27c9c2c079SJeremy L Thompson 
28c9c2c079SJeremy L Thompson #define CeedChk_Nvrtc(ceed, x)                                                                              \
29c9c2c079SJeremy L Thompson   do {                                                                                                      \
30c9c2c079SJeremy L Thompson     nvrtcResult result = static_cast<nvrtcResult>(x);                                                       \
312b730f8bSJeremy L Thompson     if (result != NVRTC_SUCCESS) return CeedError((ceed), CEED_ERROR_BACKEND, nvrtcGetErrorString(result)); \
32c9c2c079SJeremy L Thompson   } while (0)
33c9c2c079SJeremy L Thompson 
342b730f8bSJeremy L Thompson #define CeedCallNvrtc(ceed, ...)  \
352b730f8bSJeremy L Thompson   do {                            \
362b730f8bSJeremy L Thompson     int ierr_q_ = __VA_ARGS__;    \
372b730f8bSJeremy L Thompson     CeedChk_Nvrtc(ceed, ierr_q_); \
386574a04fSJeremy L Thompson   } while (0)
392b730f8bSJeremy L Thompson 
40*2027fb9dSSirAlienTheGreat #define CeedCallSystem(ceed, command, message) CeedCallBackend(CeedCallSystem_Core(ceed, command, message))
41*2027fb9dSSirAlienTheGreat 
42*2027fb9dSSirAlienTheGreat //------------------------------------------------------------------------------
43*2027fb9dSSirAlienTheGreat // Call system command and capture stdout + stderr
44*2027fb9dSSirAlienTheGreat //------------------------------------------------------------------------------
45*2027fb9dSSirAlienTheGreat static int CeedCallSystem_Core(Ceed ceed, const char *command, const char *message) {
46*2027fb9dSSirAlienTheGreat   CeedDebug(ceed, "Running command:\n$ %s\n", command);
47*2027fb9dSSirAlienTheGreat   FILE *output_stream = popen((command + std::string(" 2>&1")).c_str(), "r");
48*2027fb9dSSirAlienTheGreat 
49*2027fb9dSSirAlienTheGreat   CeedCheck(output_stream != nullptr, ceed, CEED_ERROR_BACKEND, "Failed to %s with command: %s", message, command);
50*2027fb9dSSirAlienTheGreat 
51*2027fb9dSSirAlienTheGreat   char output[4 * CEED_MAX_RESOURCE_LEN];
52*2027fb9dSSirAlienTheGreat 
53*2027fb9dSSirAlienTheGreat   while (fgets(output, sizeof(output), output_stream) != nullptr) {
54*2027fb9dSSirAlienTheGreat   }
55*2027fb9dSSirAlienTheGreat   CeedDebug(ceed, "Command output:\n%s\n", output);
56*2027fb9dSSirAlienTheGreat 
57*2027fb9dSSirAlienTheGreat   CeedCheck(pclose(output_stream) == 0, ceed, CEED_ERROR_BACKEND, "Failed to %s with error: %s", message, output);
58*2027fb9dSSirAlienTheGreat   return CEED_ERROR_SUCCESS;
59*2027fb9dSSirAlienTheGreat }
60*2027fb9dSSirAlienTheGreat 
61c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
62c9c2c079SJeremy L Thompson // Compile CUDA kernel
63c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
64*2027fb9dSSirAlienTheGreat using std::ifstream;
65*2027fb9dSSirAlienTheGreat using std::ofstream;
66*2027fb9dSSirAlienTheGreat using std::ostringstream;
67*2027fb9dSSirAlienTheGreat 
68ddae5012SJeremy L Thompson static int CeedCompileCore_Cuda(Ceed ceed, const char *source, const bool throw_error, bool *is_compile_good, CUmodule *module,
69ddae5012SJeremy L Thompson                                 const CeedInt num_defines, va_list args) {
70ca735530SJeremy L Thompson   size_t                ptx_size;
7122070f95SJeremy L Thompson   char                 *ptx;
72a491a57eSJeremy L Thompson   const int             num_opts            = 4;
734753b775SJeremy L Thompson   CeedInt               num_jit_source_dirs = 0, num_jit_defines = 0;
74b13efd58SJeremy L Thompson   const char          **opts;
75c9c2c079SJeremy L Thompson   nvrtcProgram          prog;
76ca735530SJeremy L Thompson   struct cudaDeviceProp prop;
77ca735530SJeremy L Thompson   Ceed_Cuda            *ceed_data;
78ca735530SJeremy L Thompson 
79ca735530SJeremy L Thompson   cudaFree(0);  // Make sure a Context exists for nvrtc
80c9c2c079SJeremy L Thompson 
81c9c2c079SJeremy L Thompson   std::ostringstream code;
82*2027fb9dSSirAlienTheGreat   bool               using_clang;
83*2027fb9dSSirAlienTheGreat 
84*2027fb9dSSirAlienTheGreat   CeedCallBackend(CeedGetIsClang(ceed, &using_clang));
85*2027fb9dSSirAlienTheGreat 
86*2027fb9dSSirAlienTheGreat   CeedDebug256(ceed, CEED_DEBUG_COLOR_SUCCESS,
87*2027fb9dSSirAlienTheGreat                using_clang ? "Compiling CUDA with Clang backend (with Rust QFunction support)"
88*2027fb9dSSirAlienTheGreat                            : "Compiling CUDA with NVRTC backend (without Rust QFunction support).\nTo use the Clang backend, set the environment "
89*2027fb9dSSirAlienTheGreat                              "variable GPU_CLANG=1");
90c9c2c079SJeremy L Thompson 
91c9c2c079SJeremy L Thompson   // Get kernel specific options, such as kernel constants
92c9c2c079SJeremy L Thompson   if (num_defines > 0) {
93c9c2c079SJeremy L Thompson     char *name;
94c9c2c079SJeremy L Thompson     int   val;
95ca735530SJeremy L Thompson 
96c9c2c079SJeremy L Thompson     for (int i = 0; i < num_defines; i++) {
97c9c2c079SJeremy L Thompson       name = va_arg(args, char *);
98c9c2c079SJeremy L Thompson       val  = va_arg(args, int);
99c9c2c079SJeremy L Thompson       code << "#define " << name << " " << val << "\n";
100c9c2c079SJeremy L Thompson     }
101c9c2c079SJeremy L Thompson   }
102c9c2c079SJeremy L Thompson 
103c9c2c079SJeremy L Thompson   // Standard libCEED definitions for CUDA backends
10491adc9c8SJeremy L Thompson   code << "#include <ceed/jit-source/cuda/cuda-jit.h>\n\n";
105c9c2c079SJeremy L Thompson 
106c9c2c079SJeremy L Thompson   // Non-macro options
107b13efd58SJeremy L Thompson   CeedCallBackend(CeedCalloc(num_opts, &opts));
108c9c2c079SJeremy L Thompson   opts[0] = "-default-device";
1092b730f8bSJeremy L Thompson   CeedCallBackend(CeedGetData(ceed, &ceed_data));
1102b730f8bSJeremy L Thompson   CeedCallCuda(ceed, cudaGetDeviceProperties(&prop, ceed_data->device_id));
11129ec485eSJed Brown   std::string arch_arg =
11229ec485eSJed Brown #if CUDA_VERSION >= 11010
11329ec485eSJed Brown       // NVRTC used to support only virtual architectures through the option
11429ec485eSJed Brown       // -arch, since it was only emitting PTX. It will now support actual
11529ec485eSJed Brown       // architectures as well to emit SASS.
11629ec485eSJed Brown       // https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#dynamic-code-generation
11729ec485eSJed Brown       "-arch=sm_"
11829ec485eSJed Brown #else
11929ec485eSJed Brown       "-arch=compute_"
12029ec485eSJed Brown #endif
12129ec485eSJed Brown       + std::to_string(prop.major) + std::to_string(prop.minor);
122c9c2c079SJeremy L Thompson   opts[1] = arch_arg.c_str();
123c9c2c079SJeremy L Thompson   opts[2] = "-Dint32_t=int";
124a491a57eSJeremy L Thompson   opts[3] = "-DCEED_RUNNING_JIT_PASS=1";
1254753b775SJeremy L Thompson   // Additional include dirs
126b13efd58SJeremy L Thompson   {
127b13efd58SJeremy L Thompson     const char **jit_source_dirs;
128b13efd58SJeremy L Thompson 
129b13efd58SJeremy L Thompson     CeedCallBackend(CeedGetJitSourceRoots(ceed, &num_jit_source_dirs, &jit_source_dirs));
130b13efd58SJeremy L Thompson     CeedCallBackend(CeedRealloc(num_opts + num_jit_source_dirs, &opts));
131b13efd58SJeremy L Thompson     for (CeedInt i = 0; i < num_jit_source_dirs; i++) {
1324753b775SJeremy L Thompson       std::ostringstream include_dir_arg;
133b13efd58SJeremy L Thompson 
1344753b775SJeremy L Thompson       include_dir_arg << "-I" << jit_source_dirs[i];
1354753b775SJeremy L Thompson       CeedCallBackend(CeedStringAllocCopy(include_dir_arg.str().c_str(), (char **)&opts[num_opts + i]));
136b13efd58SJeremy L Thompson     }
137b13efd58SJeremy L Thompson     CeedCallBackend(CeedRestoreJitSourceRoots(ceed, &jit_source_dirs));
138b13efd58SJeremy L Thompson   }
1394753b775SJeremy L Thompson   // User defines
1404753b775SJeremy L Thompson   {
1414753b775SJeremy L Thompson     const char **jit_defines;
1424753b775SJeremy L Thompson 
1434753b775SJeremy L Thompson     CeedCallBackend(CeedGetJitDefines(ceed, &num_jit_defines, &jit_defines));
1444753b775SJeremy L Thompson     CeedCallBackend(CeedRealloc(num_opts + num_jit_source_dirs + num_jit_defines, &opts));
1454753b775SJeremy L Thompson     for (CeedInt i = 0; i < num_jit_defines; i++) {
1464753b775SJeremy L Thompson       std::ostringstream define_arg;
1474753b775SJeremy L Thompson 
1484753b775SJeremy L Thompson       define_arg << "-D" << jit_defines[i];
1494753b775SJeremy L Thompson       CeedCallBackend(CeedStringAllocCopy(define_arg.str().c_str(), (char **)&opts[num_opts + num_jit_source_dirs + i]));
1504753b775SJeremy L Thompson     }
1514753b775SJeremy L Thompson     CeedCallBackend(CeedRestoreJitDefines(ceed, &jit_defines));
1524753b775SJeremy L Thompson   }
153c9c2c079SJeremy L Thompson 
154c9c2c079SJeremy L Thompson   // Add string source argument provided in call
155c9c2c079SJeremy L Thompson   code << source;
156c9c2c079SJeremy L Thompson 
157c9c2c079SJeremy L Thompson   // Create Program
158c9c2c079SJeremy L Thompson 
159c9c2c079SJeremy L Thompson   // Compile kernel
160c21e34e2SJeremy L Thompson   CeedDebug256(ceed, CEED_DEBUG_COLOR_SUCCESS, "---------- ATTEMPTING TO COMPILE JIT SOURCE ----------\n");
16126ef7cdaSJeremy L Thompson   CeedDebug(ceed, "Source:\n%s\n", code.str().c_str());
162c21e34e2SJeremy L Thompson   CeedDebug256(ceed, CEED_DEBUG_COLOR_SUCCESS, "---------- END OF JIT SOURCE ----------\n");
163*2027fb9dSSirAlienTheGreat 
164*2027fb9dSSirAlienTheGreat   if (!using_clang) {
165*2027fb9dSSirAlienTheGreat     CeedCallNvrtc(ceed, nvrtcCreateProgram(&prog, code.str().c_str(), NULL, 0, NULL, NULL));
166*2027fb9dSSirAlienTheGreat 
167bdcc2728SJeremy L Thompson     if (CeedDebugFlag(ceed)) {
168bdcc2728SJeremy L Thompson       // LCOV_EXCL_START
169c21e34e2SJeremy L Thompson       CeedDebug256(ceed, CEED_DEBUG_COLOR_SUCCESS, "---------- JiT COMPILER OPTIONS ----------\n");
170bdcc2728SJeremy L Thompson       for (CeedInt i = 0; i < num_opts + num_jit_source_dirs + num_jit_defines; i++) {
171bdcc2728SJeremy L Thompson         CeedDebug(ceed, "Option %d: %s", i, opts[i]);
172bdcc2728SJeremy L Thompson       }
173bdcc2728SJeremy L Thompson       CeedDebug(ceed, "");
174c21e34e2SJeremy L Thompson       CeedDebug256(ceed, CEED_DEBUG_COLOR_SUCCESS, "---------- END OF JiT COMPILER OPTIONS ----------\n");
175bdcc2728SJeremy L Thompson       // LCOV_EXCL_STOP
176bdcc2728SJeremy L Thompson     }
177*2027fb9dSSirAlienTheGreat 
1784753b775SJeremy L Thompson     nvrtcResult result = nvrtcCompileProgram(prog, num_opts + num_jit_source_dirs + num_jit_defines, opts);
179ca735530SJeremy L Thompson 
180b13efd58SJeremy L Thompson     for (CeedInt i = 0; i < num_jit_source_dirs; i++) {
181b13efd58SJeremy L Thompson       CeedCallBackend(CeedFree(&opts[num_opts + i]));
182b13efd58SJeremy L Thompson     }
1834753b775SJeremy L Thompson     for (CeedInt i = 0; i < num_jit_defines; i++) {
1844753b775SJeremy L Thompson       CeedCallBackend(CeedFree(&opts[num_opts + num_jit_source_dirs + i]));
1854753b775SJeremy L Thompson     }
186b13efd58SJeremy L Thompson     CeedCallBackend(CeedFree(&opts));
187ddae5012SJeremy L Thompson     *is_compile_good = result == NVRTC_SUCCESS;
18828c1f747SJeremy L Thompson     if (!*is_compile_good) {
189c9c2c079SJeremy L Thompson       char  *log;
190ca735530SJeremy L Thompson       size_t log_size;
191ca735530SJeremy L Thompson 
192ca735530SJeremy L Thompson       CeedCallNvrtc(ceed, nvrtcGetProgramLogSize(prog, &log_size));
1932b730f8bSJeremy L Thompson       CeedCallBackend(CeedMalloc(log_size, &log));
1942b730f8bSJeremy L Thompson       CeedCallNvrtc(ceed, nvrtcGetProgramLog(prog, log));
19528c1f747SJeremy L Thompson       if (throw_error) {
1962b730f8bSJeremy L Thompson         return CeedError(ceed, CEED_ERROR_BACKEND, "%s\n%s", nvrtcGetErrorString(result), log);
19728c1f747SJeremy L Thompson       } else {
198c49dc7a7SJeremy L Thompson         // LCOV_EXCL_START
19928c1f747SJeremy L Thompson         CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- COMPILE ERROR DETECTED ----------\n");
20028c1f747SJeremy L Thompson         CeedDebug(ceed, "Error: %s\nCompile log:\n%s\n", nvrtcGetErrorString(result), log);
201*2027fb9dSSirAlienTheGreat         CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- BACKEND MAY FALLBACK ----------\n");
20228c1f747SJeremy L Thompson         CeedCallBackend(CeedFree(&log));
20328c1f747SJeremy L Thompson         CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
20428c1f747SJeremy L Thompson         return CEED_ERROR_SUCCESS;
205c49dc7a7SJeremy L Thompson         // LCOV_EXCL_STOP
20628c1f747SJeremy L Thompson       }
207c9c2c079SJeremy L Thompson     }
208c9c2c079SJeremy L Thompson 
20929ec485eSJed Brown #if CUDA_VERSION >= 11010
21029ec485eSJed Brown     CeedCallNvrtc(ceed, nvrtcGetCUBINSize(prog, &ptx_size));
21129ec485eSJed Brown     CeedCallBackend(CeedMalloc(ptx_size, &ptx));
21229ec485eSJed Brown     CeedCallNvrtc(ceed, nvrtcGetCUBIN(prog, ptx));
21329ec485eSJed Brown #else
2142b730f8bSJeremy L Thompson     CeedCallNvrtc(ceed, nvrtcGetPTXSize(prog, &ptx_size));
2152b730f8bSJeremy L Thompson     CeedCallBackend(CeedMalloc(ptx_size, &ptx));
2162b730f8bSJeremy L Thompson     CeedCallNvrtc(ceed, nvrtcGetPTX(prog, ptx));
21729ec485eSJed Brown #endif
2182b730f8bSJeremy L Thompson     CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
219c9c2c079SJeremy L Thompson 
2202b730f8bSJeremy L Thompson     CeedCallCuda(ceed, cuModuleLoadData(module, ptx));
2212b730f8bSJeremy L Thompson     CeedCallBackend(CeedFree(&ptx));
222c9c2c079SJeremy L Thompson     return CEED_ERROR_SUCCESS;
223*2027fb9dSSirAlienTheGreat   } else {
224*2027fb9dSSirAlienTheGreat     const char *full_filename = "temp_kernel_source.cu";
225*2027fb9dSSirAlienTheGreat     FILE       *file          = fopen(full_filename, "w");
226*2027fb9dSSirAlienTheGreat 
227*2027fb9dSSirAlienTheGreat     CeedCheck(file, ceed, CEED_ERROR_BACKEND, "Failed to create file. Write access is required for cuda-clang\n");
228*2027fb9dSSirAlienTheGreat     fputs(code.str().c_str(), file);
229*2027fb9dSSirAlienTheGreat     fclose(file);
230*2027fb9dSSirAlienTheGreat 
231*2027fb9dSSirAlienTheGreat     // Get rust crate directories
232*2027fb9dSSirAlienTheGreat 
233*2027fb9dSSirAlienTheGreat     const char **rust_source_dirs     = nullptr;
234*2027fb9dSSirAlienTheGreat     int          num_rust_source_dirs = 0;
235*2027fb9dSSirAlienTheGreat 
236*2027fb9dSSirAlienTheGreat     CeedCallBackend(CeedGetRustSourceRoots(ceed, &num_rust_source_dirs, &rust_source_dirs));
237*2027fb9dSSirAlienTheGreat 
238*2027fb9dSSirAlienTheGreat     std::string rust_dirs[10];
239*2027fb9dSSirAlienTheGreat 
240*2027fb9dSSirAlienTheGreat     if (num_rust_source_dirs > 0) {
241*2027fb9dSSirAlienTheGreat       CeedDebug(ceed, "There are %d source dirs, including %s\n", num_rust_source_dirs, rust_source_dirs[0]);
242*2027fb9dSSirAlienTheGreat     }
243*2027fb9dSSirAlienTheGreat 
244*2027fb9dSSirAlienTheGreat     for (CeedInt i = 0; i < num_rust_source_dirs; i++) {
245*2027fb9dSSirAlienTheGreat       rust_dirs[i] = std::string(rust_source_dirs[i]);
246*2027fb9dSSirAlienTheGreat     }
247*2027fb9dSSirAlienTheGreat 
248*2027fb9dSSirAlienTheGreat     CeedCallBackend(CeedRestoreRustSourceRoots(ceed, &rust_source_dirs));
249*2027fb9dSSirAlienTheGreat 
250*2027fb9dSSirAlienTheGreat     char *rust_toolchain = std::getenv("RUST_TOOLCHAIN");
251*2027fb9dSSirAlienTheGreat 
252*2027fb9dSSirAlienTheGreat     if (rust_toolchain == nullptr) {
253*2027fb9dSSirAlienTheGreat       rust_toolchain = (char *)"nightly";
254*2027fb9dSSirAlienTheGreat       setenv("RUST_TOOLCHAIN", "nightly", 0);
255*2027fb9dSSirAlienTheGreat     }
256*2027fb9dSSirAlienTheGreat 
257*2027fb9dSSirAlienTheGreat     // Compile Rust crate(s) needed
258*2027fb9dSSirAlienTheGreat     std::string command;
259*2027fb9dSSirAlienTheGreat 
260*2027fb9dSSirAlienTheGreat     for (CeedInt i = 0; i < num_rust_source_dirs; i++) {
261*2027fb9dSSirAlienTheGreat       command = "cargo +" + std::string(rust_toolchain) + " build --release --target nvptx64-nvidia-cuda --config " + rust_dirs[i] +
262*2027fb9dSSirAlienTheGreat                 "/.cargo/config.toml --manifest-path " + rust_dirs[i] + "/Cargo.toml";
263*2027fb9dSSirAlienTheGreat       CeedCallSystem(ceed, command.c_str(), "build Rust crate");
264*2027fb9dSSirAlienTheGreat     }
265*2027fb9dSSirAlienTheGreat 
266*2027fb9dSSirAlienTheGreat     // Compile wrapper kernel
267*2027fb9dSSirAlienTheGreat     command = "clang++ -flto=thin --cuda-gpu-arch=sm_" + std::to_string(prop.major) + std::to_string(prop.minor) +
268*2027fb9dSSirAlienTheGreat               " --cuda-device-only -emit-llvm -S temp_kernel_source.cu -o temp_kernel.ll ";
269*2027fb9dSSirAlienTheGreat     command += opts[4];
270*2027fb9dSSirAlienTheGreat     CeedCallSystem(ceed, command.c_str(), "JiT kernel source");
271*2027fb9dSSirAlienTheGreat 
272*2027fb9dSSirAlienTheGreat     // the find command finds the rust-installed llvm-link tool and runs it
273*2027fb9dSSirAlienTheGreat     command = "$(find $(rustup run " + std::string(rust_toolchain) +
274*2027fb9dSSirAlienTheGreat               " rustc --print sysroot) -name llvm-link) temp_kernel.ll --ignore-non-bitcode --internalize --only-needed -S -o "
275*2027fb9dSSirAlienTheGreat               "temp_kernel_linked.ll  ";
276*2027fb9dSSirAlienTheGreat 
277*2027fb9dSSirAlienTheGreat     // Searches for .a files in rust directoy
278*2027fb9dSSirAlienTheGreat     // Note: this is necessary because rust crate names may not match the folder they are in
279*2027fb9dSSirAlienTheGreat     for (CeedInt i = 0; i < num_rust_source_dirs; i++) {
280*2027fb9dSSirAlienTheGreat       std::string dir = rust_dirs[i] + "/target/nvptx64-nvidia-cuda/release";
281*2027fb9dSSirAlienTheGreat       DIR        *dp  = opendir(dir.c_str());
282*2027fb9dSSirAlienTheGreat 
283*2027fb9dSSirAlienTheGreat       CeedCheck(dp != nullptr, ceed, CEED_ERROR_BACKEND, "Could not open directory: %s", dir.c_str());
284*2027fb9dSSirAlienTheGreat       struct dirent *entry;
285*2027fb9dSSirAlienTheGreat 
286*2027fb9dSSirAlienTheGreat       // finds files ending in .a
287*2027fb9dSSirAlienTheGreat       while ((entry = readdir(dp)) != nullptr) {
288*2027fb9dSSirAlienTheGreat         std::string filename(entry->d_name);
289*2027fb9dSSirAlienTheGreat 
290*2027fb9dSSirAlienTheGreat         if (filename.size() >= 2 && filename.substr(filename.size() - 2) == ".a") {
291*2027fb9dSSirAlienTheGreat           command += dir + "/" + filename + " ";
292*2027fb9dSSirAlienTheGreat         }
293*2027fb9dSSirAlienTheGreat       }
294*2027fb9dSSirAlienTheGreat       closedir(dp);
295*2027fb9dSSirAlienTheGreat       // TODO: when libCEED switches to c++17, switch to std::filesystem for the loop above
296*2027fb9dSSirAlienTheGreat     }
297*2027fb9dSSirAlienTheGreat 
298*2027fb9dSSirAlienTheGreat     // Link, optimize, and compile final CUDA kernel
299*2027fb9dSSirAlienTheGreat     // note that the find command is used to find the rust-installed llvm tool
300*2027fb9dSSirAlienTheGreat     CeedCallSystem(ceed, command.c_str(), "link C and Rust source");
301*2027fb9dSSirAlienTheGreat     CeedCallSystem(ceed,
302*2027fb9dSSirAlienTheGreat                    ("$(find $(rustup run " + std::string(rust_toolchain) +
303*2027fb9dSSirAlienTheGreat                     " rustc --print sysroot) -name opt) --passes internalize,inline temp_kernel_linked.ll -o temp_kernel_opt.bc")
304*2027fb9dSSirAlienTheGreat                        .c_str(),
305*2027fb9dSSirAlienTheGreat                    "optimize linked C and Rust source");
306*2027fb9dSSirAlienTheGreat     CeedCallSystem(ceed,
307*2027fb9dSSirAlienTheGreat                    ("$(find $(rustup run " + std::string(rust_toolchain) + " rustc --print sysroot) -name llc) -O3 -mcpu=sm_" +
308*2027fb9dSSirAlienTheGreat                     std::to_string(prop.major) + std::to_string(prop.minor) + " temp_kernel_opt.bc -o temp_kernel_final.ptx")
309*2027fb9dSSirAlienTheGreat                        .c_str(),
310*2027fb9dSSirAlienTheGreat                    "compile final CUDA kernel");
311*2027fb9dSSirAlienTheGreat 
312*2027fb9dSSirAlienTheGreat     ifstream      ptxfile("temp_kernel_final.ptx");
313*2027fb9dSSirAlienTheGreat     ostringstream sstr;
314*2027fb9dSSirAlienTheGreat 
315*2027fb9dSSirAlienTheGreat     sstr << ptxfile.rdbuf();
316*2027fb9dSSirAlienTheGreat 
317*2027fb9dSSirAlienTheGreat     auto ptx_data = sstr.str();
318*2027fb9dSSirAlienTheGreat     ptx_size      = ptx_data.length();
319*2027fb9dSSirAlienTheGreat 
320*2027fb9dSSirAlienTheGreat     int result = cuModuleLoadData(module, ptx_data.c_str());
321*2027fb9dSSirAlienTheGreat 
322*2027fb9dSSirAlienTheGreat     *is_compile_good = result == 0;
323*2027fb9dSSirAlienTheGreat     if (!*is_compile_good) {
324*2027fb9dSSirAlienTheGreat       if (throw_error) {
325*2027fb9dSSirAlienTheGreat         return CeedError(ceed, CEED_ERROR_BACKEND, "Failed to load module data");
326*2027fb9dSSirAlienTheGreat       } else {
327*2027fb9dSSirAlienTheGreat         // LCOV_EXCL_START
328*2027fb9dSSirAlienTheGreat         CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- COMPILE ERROR DETECTED ----------\n");
329*2027fb9dSSirAlienTheGreat         CeedDebug(ceed, "Error: Failed to load module data");
330*2027fb9dSSirAlienTheGreat         CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- BACKEND MAY FALLBACK ----------\n");
331*2027fb9dSSirAlienTheGreat         return CEED_ERROR_SUCCESS;
332*2027fb9dSSirAlienTheGreat         // LCOV_EXCL_STOP
333*2027fb9dSSirAlienTheGreat       }
334*2027fb9dSSirAlienTheGreat     }
335*2027fb9dSSirAlienTheGreat   }
336*2027fb9dSSirAlienTheGreat   return CEED_ERROR_SUCCESS;
337c9c2c079SJeremy L Thompson }
338c9c2c079SJeremy L Thompson 
339ddae5012SJeremy L Thompson int CeedCompile_Cuda(Ceed ceed, const char *source, CUmodule *module, const CeedInt num_defines, ...) {
340ddae5012SJeremy L Thompson   bool    is_compile_good = true;
341ddae5012SJeremy L Thompson   va_list args;
342ddae5012SJeremy L Thompson 
343ddae5012SJeremy L Thompson   va_start(args, num_defines);
34418c38aeeSJeremy L Thompson   const CeedInt ierr = CeedCompileCore_Cuda(ceed, source, true, &is_compile_good, module, num_defines, args);
34518c38aeeSJeremy L Thompson 
346ddae5012SJeremy L Thompson   va_end(args);
34718c38aeeSJeremy L Thompson   CeedCallBackend(ierr);
348ddae5012SJeremy L Thompson   return CEED_ERROR_SUCCESS;
349ddae5012SJeremy L Thompson }
350ddae5012SJeremy L Thompson 
351ddae5012SJeremy L Thompson int CeedTryCompile_Cuda(Ceed ceed, const char *source, bool *is_compile_good, CUmodule *module, const CeedInt num_defines, ...) {
352ddae5012SJeremy L Thompson   va_list args;
353ddae5012SJeremy L Thompson 
354ddae5012SJeremy L Thompson   va_start(args, num_defines);
35518c38aeeSJeremy L Thompson   const CeedInt ierr = CeedCompileCore_Cuda(ceed, source, false, is_compile_good, module, num_defines, args);
35618c38aeeSJeremy L Thompson 
357ddae5012SJeremy L Thompson   va_end(args);
35818c38aeeSJeremy L Thompson   CeedCallBackend(ierr);
359ddae5012SJeremy L Thompson   return CEED_ERROR_SUCCESS;
360ddae5012SJeremy L Thompson }
361ddae5012SJeremy L Thompson 
362c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
363c9c2c079SJeremy L Thompson // Get CUDA kernel
364c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
365eb7e6cafSJeremy L Thompson int CeedGetKernel_Cuda(Ceed ceed, CUmodule module, const char *name, CUfunction *kernel) {
3662b730f8bSJeremy L Thompson   CeedCallCuda(ceed, cuModuleGetFunction(kernel, module, name));
367c9c2c079SJeremy L Thompson   return CEED_ERROR_SUCCESS;
368c9c2c079SJeremy L Thompson }
369c9c2c079SJeremy L Thompson 
370b2165e7aSSebastian Grimberg //------------------------------------------------------------------------------
371b2165e7aSSebastian Grimberg // Run CUDA kernel with block size selected automatically based on the kernel
372b2165e7aSSebastian Grimberg //     (which may use enough registers to require a smaller block size than the
373b2165e7aSSebastian Grimberg //      hardware is capable)
374b2165e7aSSebastian Grimberg //------------------------------------------------------------------------------
3752b730f8bSJeremy L Thompson int CeedRunKernelAutoblockCuda(Ceed ceed, CUfunction kernel, size_t points, void **args) {
376c9c2c079SJeremy L Thompson   int min_grid_size, max_block_size;
377ca735530SJeremy L Thompson 
3782b730f8bSJeremy L Thompson   CeedCallCuda(ceed, cuOccupancyMaxPotentialBlockSize(&min_grid_size, &max_block_size, kernel, NULL, 0, 0x10000));
379eb7e6cafSJeremy L Thompson   CeedCallBackend(CeedRunKernel_Cuda(ceed, kernel, CeedDivUpInt(points, max_block_size), max_block_size, args));
380ca735530SJeremy L Thompson   return CEED_ERROR_SUCCESS;
381c9c2c079SJeremy L Thompson }
382c9c2c079SJeremy L Thompson 
383c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
384c9c2c079SJeremy L Thompson // Run CUDA kernel
385c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
386eb7e6cafSJeremy L Thompson int CeedRunKernel_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size, void **args) {
387e9c76bddSJeremy L Thompson   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, NULL, grid_size, block_size, 1, 1, 0, args));
388c9c2c079SJeremy L Thompson   return CEED_ERROR_SUCCESS;
389c9c2c079SJeremy L Thompson }
390c9c2c079SJeremy L Thompson 
391c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
392c9c2c079SJeremy L Thompson // Run CUDA kernel for spatial dimension
393c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
394eb7e6cafSJeremy L Thompson int CeedRunKernelDim_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y, const int block_size_z,
3952b730f8bSJeremy L Thompson                           void **args) {
396e9c76bddSJeremy L Thompson   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, NULL, grid_size, block_size_x, block_size_y, block_size_z, 0, args));
397c9c2c079SJeremy L Thompson   return CEED_ERROR_SUCCESS;
398c9c2c079SJeremy L Thompson }
399c9c2c079SJeremy L Thompson 
400c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
401ea61e9acSJeremy L Thompson // Run CUDA kernel for spatial dimension with shared memory
402c9c2c079SJeremy L Thompson //------------------------------------------------------------------------------
403e9c76bddSJeremy L Thompson static int CeedRunKernelDimSharedCore_Cuda(Ceed ceed, CUfunction kernel, CUstream stream, const int grid_size, const int block_size_x,
404e9c76bddSJeremy L Thompson                                            const int block_size_y, const int block_size_z, const int shared_mem_size, const bool throw_error,
405e9c76bddSJeremy L Thompson                                            bool *is_good_run, void **args) {
406023b8a51Sabdelfattah83 #if CUDA_VERSION >= 9000
407023b8a51Sabdelfattah83   cuFuncSetAttribute(kernel, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_mem_size);
408023b8a51Sabdelfattah83 #endif
409e9c76bddSJeremy L Thompson   CUresult result = cuLaunchKernel(kernel, grid_size, 1, 1, block_size_x, block_size_y, block_size_z, shared_mem_size, stream, args, NULL);
410ca735530SJeremy L Thompson 
411c9c2c079SJeremy L Thompson   if (result == CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES) {
412c9c2c079SJeremy L Thompson     int max_threads_per_block, shared_size_bytes, num_regs;
413ca735530SJeremy L Thompson 
4142b730f8bSJeremy L Thompson     cuFuncGetAttribute(&max_threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, kernel);
4152b730f8bSJeremy L Thompson     cuFuncGetAttribute(&shared_size_bytes, CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, kernel);
416c9c2c079SJeremy L Thompson     cuFuncGetAttribute(&num_regs, CU_FUNC_ATTRIBUTE_NUM_REGS, kernel);
417c49dc7a7SJeremy L Thompson     if (throw_error) {
418c9c2c079SJeremy L Thompson       return CeedError(ceed, CEED_ERROR_BACKEND,
419c9c2c079SJeremy L Thompson                        "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: max_threads_per_block %d on block size (%d,%d,%d), shared_size %d, num_regs %d",
4202b730f8bSJeremy L Thompson                        max_threads_per_block, block_size_x, block_size_y, block_size_z, shared_size_bytes, num_regs);
421c49dc7a7SJeremy L Thompson     } else {
422c49dc7a7SJeremy L Thompson       // LCOV_EXCL_START
423c49dc7a7SJeremy L Thompson       CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- LAUNCH ERROR DETECTED ----------\n");
424c49dc7a7SJeremy L Thompson       CeedDebug(ceed, "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: max_threads_per_block %d on block size (%d,%d,%d), shared_size %d, num_regs %d\n",
425c49dc7a7SJeremy L Thompson                 max_threads_per_block, block_size_x, block_size_y, block_size_z, shared_size_bytes, num_regs);
426c21e34e2SJeremy L Thompson       CeedDebug256(ceed, CEED_DEBUG_COLOR_WARNING, "---------- BACKEND MAY FALLBACK ----------\n");
427c49dc7a7SJeremy L Thompson       // LCOV_EXCL_STOP
428ddae5012SJeremy L Thompson     }
429c49dc7a7SJeremy L Thompson     *is_good_run = false;
430c9c2c079SJeremy L Thompson   } else CeedChk_Cu(ceed, result);
431c9c2c079SJeremy L Thompson   return CEED_ERROR_SUCCESS;
432c9c2c079SJeremy L Thompson }
4332a86cc9dSSebastian Grimberg 
434e9c76bddSJeremy L Thompson int CeedRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, CUstream stream, const int grid_size, const int block_size_x, const int block_size_y,
435ddae5012SJeremy L Thompson                                 const int block_size_z, const int shared_mem_size, void **args) {
436ddae5012SJeremy L Thompson   bool is_good_run = true;
437ddae5012SJeremy L Thompson 
438e9c76bddSJeremy L Thompson   CeedCallBackend(CeedRunKernelDimSharedCore_Cuda(ceed, kernel, stream, grid_size, block_size_x, block_size_y, block_size_z, shared_mem_size, true,
439e9c76bddSJeremy L Thompson                                                   &is_good_run, args));
440ddae5012SJeremy L Thompson   return CEED_ERROR_SUCCESS;
441ddae5012SJeremy L Thompson }
442ddae5012SJeremy L Thompson 
443e9c76bddSJeremy L Thompson int CeedTryRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, CUstream stream, const int grid_size, const int block_size_x, const int block_size_y,
444ddae5012SJeremy L Thompson                                    const int block_size_z, const int shared_mem_size, bool *is_good_run, void **args) {
445e9c76bddSJeremy L Thompson   CeedCallBackend(CeedRunKernelDimSharedCore_Cuda(ceed, kernel, stream, grid_size, block_size_x, block_size_y, block_size_z, shared_mem_size, false,
446e9c76bddSJeremy L Thompson                                                   is_good_run, args));
447ddae5012SJeremy L Thompson   return CEED_ERROR_SUCCESS;
448ddae5012SJeremy L Thompson }
449ddae5012SJeremy L Thompson 
4502a86cc9dSSebastian Grimberg //------------------------------------------------------------------------------
451