| Issue |
238406
|
| Summary |
[libc][GPU] On NVPTX, calloc() allocates from the libc allocator but free() is CUDA's
|
| Labels |
libc
|
| Assignees |
|
| Reporter |
eugeneepshteyn
|
On NVPTX, the GPU libc's `calloc` and `free` come from two different allocators, so `free(calloc(n, size))` hands `free` a pointer that its allocator never returned.
`malloc.cpp`, `free.cpp`, `realloc.cpp` and `aligned_alloc.cpp` in `libc/src/stdlib/gpu/` are all wrapped in `#ifndef LIBC_TARGET_ARCH_IS_NVPTX` (since 124277), so on NVPTX device code gets CUDA's device-heap `malloc` and `free`. `calloc.cpp` has no such guard: it calls `gpu::allocate`, the libc slab allocator. The only `free` that can release its result is CUDA's, which knows nothing about the slab.
For example, with OpenMP offload to NVPTX linked against the GPU libc:
```c
#include <stdlib.h>
#pragma omp declare target
int *zeros(int n) { return calloc(n, sizeof(int)); } // libc slab allocator
void release(int *p) { free(p); } // CUDA device heap
#pragma omp end declare target
```
The binding is visible without a GPU by compiling the two entrypoints at main (022e37a5) with a current clang:
```console
$ for f in calloc free; do clang++ -std=c++17 -O2 -nogpulib -ffreestanding -fno-builtin \
-DLIBC_NAMESPACE=__llvm_libc -DLIBC_COPT_PUBLIC_PACKAGING \
-Illvm-project/libc -Illvm-project/libc/include \
--target=nvptx64-nvidia-cuda -march=sm_90 -S \
llvm-project/libc/src/stdlib/gpu/$f.cpp -o $f.ptx; done
$ grep -E '\.func|call\.' calloc.ptx free.ptx
calloc.ptx:.extern .func (.param .b64 func_retval0) _ZN11__llvm_libc3gpu8allocateEy
calloc.ptx:.visible .func (.param .b64 func_retval0) _ZN11__llvm_libc6callocEmm
calloc.ptx:.visible .func (.param .b64 func_retval0) calloc(
calloc.ptx: call.uni (retval0), _ZN11__llvm_libc3gpu8allocateEy, (param0);
```
`free.ptx` defines no function. For amdgcn both files define their function, and both use the slab allocator.
I have not run this on a GPU, because I don't have an NVPTX build of the GPU libc. The GPU stdlib integration tests are skipped on NVPTX ("TODO: Test on NVPTX, requires CUDA VMEM API"), so no test covers this pairing.
A possible fix: give `calloc.cpp` the same NVPTX guard as the other entrypoints, and on NVPTX implement it as the device `malloc` followed by zeroing, so that `calloc` and `free` share one heap.
(This issue was filed with the help of AI)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs