Skip to content

Commit 3390a11

Browse files
committed
Add intrinsic for dynamic group-shared memory on GPUs
Group-shared memory is a memory region that is shared between all threads in a work-group on GPUs. Dynamic group-shared memory is in that memory region, though the allocated size is specified late, when launching a kernel, instead of early at compile-time. # Interface With this change, dynamic group-shared memory can be accessed in Rust by calling the new `gpu_dynamic_groupshared_mem<T>() -> *mut T` intrinsic. It returns the pointer to dynamic group-shared memory guaranteeing that it is aligned to at least the alignment of `T`. The pointer is dereferencable for the size specified when launching the current gpu-kernel (which may be the size of `T` but can also be larger or smaller or zero). All calls to this intrinsic return a pointer to the same address. See the intrinsic documentation for more details. ## Alternative Interfaces It was also considered to expose dynamic group-shared memory as extern static variables in Rust, like they are represented in LLVM IR. However, due to the pointer not being guaranteed to be dereferencable (that depends on the allocated size at runtime), such a global must be zero- sized, which makes global variables a bad fit. # Implementation Details Group-shared memory in amdgpu and nvptx lives in address space 3. Dynamic group-shared memory is implemented by creating an external global variable in address space 3. The global is declared with size 0, as the actual size is only known at runtime. It is defined behavior in LLVM to access an external global outside the defined size. There is no similar way to get the allocated size of dynamic shared memory on amdgpu an nvptx, so users have to pass this out-of-band or rely on target specific ways.
1 parent 83e49b7 commit 3390a11

File tree

10 files changed

+147
-6
lines changed

10 files changed

+147
-6
lines changed

compiler/rustc_abi/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1719,6 +1719,9 @@ pub struct AddressSpace(pub u32);
17191719
impl AddressSpace {
17201720
/// LLVM's `0` address space.
17211721
pub const ZERO: Self = AddressSpace(0);
1722+
/// The address space for work-group shared memory on nvptx and amdgpu.
1723+
/// See e.g. the `gpu_dynamic_groupshared_mem` intrinsic for details.
1724+
pub const GPU_SHARED: Self = AddressSpace(3);
17221725
}
17231726

17241727
/// The way we represent values to the backend

compiler/rustc_codegen_llvm/src/declare.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use std::borrow::Borrow;
1515

1616
use itertools::Itertools;
17+
use rustc_abi::AddressSpace;
1718
use rustc_codegen_ssa::traits::TypeMembershipCodegenMethods;
1819
use rustc_data_structures::fx::FxIndexSet;
1920
use rustc_middle::ty::{Instance, Ty};
@@ -97,6 +98,28 @@ impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
9798
)
9899
}
99100
}
101+
102+
/// Declare a global value in a specific address space.
103+
///
104+
/// If there’s a value with the same name already declared, the function will
105+
/// return its Value instead.
106+
pub(crate) fn declare_global_in_addrspace(
107+
&self,
108+
name: &str,
109+
ty: &'ll Type,
110+
addr_space: AddressSpace,
111+
) -> &'ll Value {
112+
debug!("declare_global(name={name:?}, addrspace={addr_space:?})");
113+
unsafe {
114+
llvm::LLVMRustGetOrInsertGlobalInAddrspace(
115+
(**self).borrow().llmod,
116+
name.as_c_char_ptr(),
117+
name.len(),
118+
ty,
119+
addr_space.0,
120+
)
121+
}
122+
}
100123
}
101124

102125
impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use std::assert_matches::assert_matches;
22
use std::cmp::Ordering;
33

4-
use rustc_abi::{Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size};
4+
use rustc_abi::{
5+
AddressSpace, Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size,
6+
};
57
use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
68
use rustc_codegen_ssa::codegen_attrs::autodiff_attrs;
79
use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
@@ -553,6 +555,31 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
553555
return Ok(());
554556
}
555557

558+
sym::gpu_dynamic_groupshared_mem => {
559+
// The name of the global variable is not relevant, the important properties are.
560+
// 1. The global is in the shared address space
561+
// 2. It is an extern global
562+
// All instances of extern addrspace(shared) globals are merged in the LLVM backend.
563+
// Generate an unnamed global per intrinsic call, so that different kernels can have
564+
// different minimum alignments.
565+
// See https://docs.nvidia.com/cuda/cuda-c-programming-guide/#shared
566+
let global = self.declare_global_in_addrspace(
567+
"",
568+
self.type_array(self.type_i8(), 0),
569+
AddressSpace::GPU_SHARED,
570+
);
571+
let ty::RawPtr(inner_ty, _) = result.layout.ty.kind() else { unreachable!() };
572+
// The alignment of the global is used to specify the *minimum* alignment that the
573+
// must be obeyed by the GPU runtime.
574+
// When multiple of these global variables are merged, the maximum alignment is taken.
575+
// See https://github.com/llvm/llvm-project/blob/a271d07488a85ce677674bbe8101b10efff58c95/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp#L821
576+
let alignment = self.align_of(*inner_ty).bytes() as u32;
577+
unsafe {
578+
llvm::LLVMSetAlignment(global, alignment);
579+
}
580+
self.cx().const_pointercast(global, self.type_ptr())
581+
}
582+
556583
_ if name.as_str().starts_with("simd_") => {
557584
// Unpack non-power-of-2 #[repr(packed, simd)] arguments.
558585
// This gives them the expected layout of a regular #[repr(simd)] vector.

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2017,6 +2017,13 @@ unsafe extern "C" {
20172017
NameLen: size_t,
20182018
T: &'a Type,
20192019
) -> &'a Value;
2020+
pub(crate) fn LLVMRustGetOrInsertGlobalInAddrspace<'a>(
2021+
M: &'a Module,
2022+
Name: *const c_char,
2023+
NameLen: size_t,
2024+
T: &'a Type,
2025+
AddressSpace: c_uint,
2026+
) -> &'a Value;
20202027
pub(crate) fn LLVMRustGetNamedValue(
20212028
M: &Module,
20222029
Name: *const c_char,

compiler/rustc_codegen_ssa/src/mir/intrinsic.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
111111
sym::abort
112112
| sym::unreachable
113113
| sym::cold_path
114+
| sym::gpu_dynamic_groupshared_mem
114115
| sym::breakpoint
115116
| sym::assert_zero_valid
116117
| sym::assert_mem_uninitialized_valid

compiler/rustc_hir_analysis/src/check/intrinsic.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi
132132
| sym::forget
133133
| sym::frem_algebraic
134134
| sym::fsub_algebraic
135+
| sym::gpu_dynamic_groupshared_mem
135136
| sym::is_val_statically_known
136137
| sym::log2f16
137138
| sym::log2f32
@@ -293,6 +294,7 @@ pub(crate) fn check_intrinsic_type(
293294
sym::offset_of => (1, 0, vec![tcx.types.u32, tcx.types.u32], tcx.types.usize),
294295
sym::rustc_peek => (1, 0, vec![param(0)], param(0)),
295296
sym::caller_location => (0, 0, vec![], tcx.caller_location_ty()),
297+
sym::gpu_dynamic_groupshared_mem => (1, 0, vec![], Ty::new_mut_ptr(tcx, param(0))),
296298
sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => {
297299
(1, 0, vec![], tcx.types.unit)
298300
}

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -261,10 +261,10 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
261261
.getCallee());
262262
}
263263

264-
extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
265-
const char *Name,
266-
size_t NameLen,
267-
LLVMTypeRef Ty) {
264+
extern "C" LLVMValueRef
265+
LLVMRustGetOrInsertGlobalInAddrspace(LLVMModuleRef M, const char *Name,
266+
size_t NameLen, LLVMTypeRef Ty,
267+
unsigned AddressSpace) {
268268
Module *Mod = unwrap(M);
269269
auto NameRef = StringRef(Name, NameLen);
270270

@@ -275,10 +275,21 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
275275
GlobalVariable *GV = Mod->getGlobalVariable(NameRef, true);
276276
if (!GV)
277277
GV = new GlobalVariable(*Mod, unwrap(Ty), false,
278-
GlobalValue::ExternalLinkage, nullptr, NameRef);
278+
GlobalValue::ExternalLinkage, nullptr, NameRef,
279+
nullptr, GlobalValue::NotThreadLocal, AddressSpace);
279280
return wrap(GV);
280281
}
281282

283+
extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
284+
const char *Name,
285+
size_t NameLen,
286+
LLVMTypeRef Ty) {
287+
Module *Mod = unwrap(M);
288+
unsigned AddressSpace = Mod->getDataLayout().getDefaultGlobalsAddressSpace();
289+
return LLVMRustGetOrInsertGlobalInAddrspace(M, Name, NameLen, Ty,
290+
AddressSpace);
291+
}
292+
282293
// Must match the layout of `rustc_codegen_llvm::llvm::ffi::AttributeKind`.
283294
enum class LLVMRustAttributeKind {
284295
AlwaysInline = 0,

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,6 +1152,7 @@ symbols! {
11521152
global_asm,
11531153
global_registration,
11541154
globs,
1155+
gpu_dynamic_groupshared_mem,
11551156
gt,
11561157
guard_patterns,
11571158
half_open_range_patterns,

library/core/src/intrinsics/mod.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3436,6 +3436,44 @@ pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize
34363436
)
34373437
}
34383438

3439+
/// Returns the pointer to dynamic group-shared memory on GPUs.
3440+
///
3441+
/// Group-shared memory is a memory region that is shared between all threads in
3442+
/// the same work-group. It is faster to access then other memory but pointers do not
3443+
/// work outside the work-group where they were obtained.
3444+
/// Dynamic group-shared memory is in the group-shared memory region, the allocated
3445+
/// size is specified late, after compilation, when launching a gpu-kernel.
3446+
/// The size can differ between launches of a gpu-kernel, therefore it is called dynamic.
3447+
///
3448+
/// The returned pointer is the start of the dynamic group-shared memory region.
3449+
/// All calls to `gpu_dynamic_groupshared_mem` in a work-group, independent of the
3450+
/// generic type, return the same address, so alias the same memory.
3451+
/// The returned pointer is aligned by at least the alignment of `T`.
3452+
///
3453+
/// # Safety
3454+
///
3455+
/// The pointer is safe to dereference from the start (the returned pointer) up to the
3456+
/// size of dynamic group-shared memory that was specified when launching the current
3457+
/// gpu-kernel.
3458+
///
3459+
/// The user must take care of synchronizing access to group-shared memory between
3460+
/// threads in a work-group. It is undefined behavior if one thread makes a non-atomic
3461+
/// write to a group-shared memory location and another thread simultaneously accesses
3462+
/// the same location.
3463+
///
3464+
/// # Other APIs
3465+
///
3466+
/// CUDA and HIP call this shared memory, shared between threads in a block.
3467+
/// OpenCL and SYCL call this local memory, shared between threads in a work-group.
3468+
/// GLSL calls this shared memory, shared between invocations in a work group.
3469+
/// DirectX calls this groupshared memory, shared between threads in a thread-group.
3470+
#[must_use = "returns a pointer that does nothing unless used"]
3471+
#[rustc_intrinsic]
3472+
#[rustc_nounwind]
3473+
#[unstable(feature = "gpu_dynamic_groupshared_mem", issue = "135513")]
3474+
#[cfg(any(target_arch = "amdgpu", target_arch = "nvptx64"))]
3475+
pub fn gpu_dynamic_groupshared_mem<T>() -> *mut T;
3476+
34393477
/// Copies the current location of arglist `src` to the arglist `dst`.
34403478
///
34413479
/// # Safety
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Checks that the GPU dynamic group-shared memory intrinsic works.
2+
3+
//@ revisions: amdgpu nvptx
4+
//@ compile-flags: --crate-type=rlib
5+
//
6+
//@ [amdgpu] compile-flags: --target amdgcn-amd-amdhsa -Ctarget-cpu=gfx900
7+
//@ [amdgpu] needs-llvm-components: amdgpu
8+
//@ [nvptx] compile-flags: --target nvptx64-nvidia-cuda
9+
//@ [nvptx] needs-llvm-components: nvptx
10+
//@ add-minicore
11+
#![feature(intrinsics, no_core, rustc_attrs)]
12+
#![no_core]
13+
14+
extern crate minicore;
15+
16+
#[rustc_intrinsic]
17+
#[rustc_nounwind]
18+
fn gpu_dynamic_groupshared_mem<T>() -> *mut T;
19+
20+
// CHECK-DAG: @[[SMALL:[^ ]+]] = external addrspace(3) global [0 x i8], align 4
21+
// CHECK-DAG: @[[BIG:[^ ]+]] = external addrspace(3) global [0 x i8], align 8
22+
// CHECK: ret { ptr, ptr } { ptr addrspacecast (ptr addrspace(3) @[[SMALL]] to ptr), ptr addrspacecast (ptr addrspace(3) @[[BIG]] to ptr) }
23+
#[unsafe(no_mangle)]
24+
pub fn fun() -> (*mut i32, *mut f64) {
25+
let small = gpu_dynamic_groupshared_mem::<i32>();
26+
let big = gpu_dynamic_groupshared_mem::<f64>(); // Increase alignment to 8
27+
(small, big)
28+
}

0 commit comments

Comments
 (0)