Skip to content

Commit 8a95ca4

Browse files
committed
Add intrinsic for launch-sized workgroup memory on GPUs
Workgroup memory is a memory region that is shared between all threads in a workgroup on GPUs. Workgroup memory can be allocated statically or after compilation, when launching a gpu-kernel. The intrinsic added here returns the pointer to the memory that is allocated at launch-time. # Interface With this change, workgroup memory can be accessed in Rust by calling the new `gpu_launch_sized_workgroup_mem<T>() -> *mut T` intrinsic. It returns the pointer to workgroup 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 workgroup 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 Workgroup memory in amdgpu and nvptx lives in address space 3. Workgroup memory from a launch 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 launch-sized workgroup memory on amdgpu an nvptx, so users have to pass this out-of-band or rely on target specific ways for now.
1 parent 033b925 commit 8a95ca4

File tree

11 files changed

+175
-8
lines changed

11 files changed

+175
-8
lines changed

compiler/rustc_abi/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1694,6 +1694,9 @@ pub struct AddressSpace(pub u32);
16941694
impl AddressSpace {
16951695
/// LLVM's `0` address space.
16961696
pub const ZERO: Self = AddressSpace(0);
1697+
/// The address space for workgroup memory on nvptx and amdgpu.
1698+
/// See e.g. the `gpu_launch_sized_workgroup_mem` intrinsic for details.
1699+
pub const GPU_WORKGROUP: Self = AddressSpace(3);
16971700
}
16981701

16991702
/// How many scalable vectors are in a `BackendRepr::ScalableVector`?

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::{MiscCodegenMethods, TypeMembershipCodegenMethods};
1819
use rustc_data_structures::fx::FxIndexSet;
1920
use rustc_middle::ty::{Instance, Ty};
@@ -104,6 +105,28 @@ impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
104105
)
105106
}
106107
}
108+
109+
/// Declare a global value in a specific address space.
110+
///
111+
/// If there’s a value with the same name already declared, the function will
112+
/// return its Value instead.
113+
pub(crate) fn declare_global_in_addrspace(
114+
&self,
115+
name: &str,
116+
ty: &'ll Type,
117+
addr_space: AddressSpace,
118+
) -> &'ll Value {
119+
debug!("declare_global(name={name:?}, addrspace={addr_space:?})");
120+
unsafe {
121+
llvm::LLVMRustGetOrInsertGlobalInAddrspace(
122+
(**self).borrow().llmod,
123+
name.as_c_char_ptr(),
124+
name.len(),
125+
ty,
126+
addr_space.0,
127+
)
128+
}
129+
}
107130
}
108131

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

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use std::ffi::c_uint;
33
use std::{assert_matches, ptr};
44

55
use rustc_abi::{
6-
Align, BackendRepr, ExternAbi, Float, HasDataLayout, NumScalableVectors, Primitive, Size,
7-
WrappingRange,
6+
AddressSpace, Align, BackendRepr, ExternAbi, Float, HasDataLayout, NumScalableVectors,
7+
Primitive, Size, WrappingRange,
88
};
99
use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
1010
use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
@@ -24,7 +24,7 @@ use rustc_session::config::CrateType;
2424
use rustc_span::{Span, Symbol, sym};
2525
use rustc_symbol_mangling::{mangle_internal_symbol, symbol_name_for_instance_in_crate};
2626
use rustc_target::callconv::PassMode;
27-
use rustc_target::spec::Os;
27+
use rustc_target::spec::{Arch, Os};
2828
use tracing::debug;
2929

3030
use crate::abi::FnAbiLlvmExt;
@@ -600,6 +600,44 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
600600
return Ok(());
601601
}
602602

603+
sym::gpu_launch_sized_workgroup_mem => {
604+
// Generate an anonymous global per call, with these properties:
605+
// 1. The global is in the address space for workgroup memory
606+
// 2. It is an `external` global
607+
// 3. It is correctly aligned for the pointee `T`
608+
// All instances of extern addrspace(gpu_workgroup) globals are merged in the LLVM backend.
609+
// The name is irrelevant.
610+
// See https://docs.nvidia.com/cuda/cuda-c-programming-guide/#shared
611+
// FIXME Workaround an nvptx backend issue that extern globals must have a name
612+
let name = if tcx.sess.target.arch == Arch::Nvptx64 {
613+
"gpu_launch_sized_workgroup_mem"
614+
} else {
615+
""
616+
};
617+
let global = self.declare_global_in_addrspace(
618+
name,
619+
self.type_array(self.type_i8(), 0),
620+
AddressSpace::GPU_WORKGROUP,
621+
);
622+
let ty::RawPtr(inner_ty, _) = result.layout.ty.kind() else { unreachable!() };
623+
// The alignment of the global is used to specify the *minimum* alignment that
624+
// must be obeyed by the GPU runtime.
625+
// When multiple of these global variables are used by a kernel, the maximum alignment is taken.
626+
// See https://github.com/llvm/llvm-project/blob/a271d07488a85ce677674bbe8101b10efff58c95/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp#L821
627+
let alignment = self.align_of(*inner_ty).bytes() as u32;
628+
unsafe {
629+
// FIXME Workaround the above issue by taking maximum alignment if the global existed
630+
if tcx.sess.target.arch == Arch::Nvptx64 {
631+
if alignment > llvm::LLVMGetAlignment(global) {
632+
llvm::LLVMSetAlignment(global, alignment);
633+
}
634+
} else {
635+
llvm::LLVMSetAlignment(global, alignment);
636+
}
637+
}
638+
self.cx().const_pointercast(global, self.type_ptr())
639+
}
640+
603641
sym::amdgpu_dispatch_ptr => {
604642
let val = self.call_intrinsic("llvm.amdgcn.dispatch.ptr", &[], &[]);
605643
// Relying on `LLVMBuildPointerCast` to produce an addrspacecast

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1989,6 +1989,13 @@ unsafe extern "C" {
19891989
NameLen: size_t,
19901990
T: &'a Type,
19911991
) -> &'a Value;
1992+
pub(crate) fn LLVMRustGetOrInsertGlobalInAddrspace<'a>(
1993+
M: &'a Module,
1994+
Name: *const c_char,
1995+
NameLen: size_t,
1996+
T: &'a Type,
1997+
AddressSpace: c_uint,
1998+
) -> &'a Value;
19921999
pub(crate) fn LLVMRustGetNamedValue(
19932000
M: &Module,
19942001
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_launch_sized_workgroup_mem
114115
| sym::breakpoint
115116
| sym::amdgpu_dispatch_ptr
116117
| sym::assert_zero_valid

compiler/rustc_hir_analysis/src/check/intrinsic.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi
131131
| sym::forget
132132
| sym::frem_algebraic
133133
| sym::fsub_algebraic
134+
| sym::gpu_launch_sized_workgroup_mem
134135
| sym::is_val_statically_known
135136
| sym::log2f16
136137
| sym::log2f32
@@ -298,6 +299,7 @@ pub(crate) fn check_intrinsic_type(
298299
sym::field_offset => (1, 0, vec![], tcx.types.usize),
299300
sym::rustc_peek => (1, 0, vec![param(0)], param(0)),
300301
sym::caller_location => (0, 0, vec![], tcx.caller_location_ty()),
302+
sym::gpu_launch_sized_workgroup_mem => (1, 0, vec![], Ty::new_mut_ptr(tcx, param(0))),
301303
sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => {
302304
(1, 0, vec![], tcx.types.unit)
303305
}

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -298,10 +298,12 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
298298
.getCallee());
299299
}
300300

301-
extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
302-
const char *Name,
303-
size_t NameLen,
304-
LLVMTypeRef Ty) {
301+
// Get the global variable with the given name if it exists or create a new
302+
// external global.
303+
extern "C" LLVMValueRef
304+
LLVMRustGetOrInsertGlobalInAddrspace(LLVMModuleRef M, const char *Name,
305+
size_t NameLen, LLVMTypeRef Ty,
306+
unsigned int AddressSpace) {
305307
Module *Mod = unwrap(M);
306308
auto NameRef = StringRef(Name, NameLen);
307309

@@ -312,10 +314,24 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
312314
GlobalVariable *GV = Mod->getGlobalVariable(NameRef, true);
313315
if (!GV)
314316
GV = new GlobalVariable(*Mod, unwrap(Ty), false,
315-
GlobalValue::ExternalLinkage, nullptr, NameRef);
317+
GlobalValue::ExternalLinkage, nullptr, NameRef,
318+
nullptr, GlobalValue::NotThreadLocal, AddressSpace);
316319
return wrap(GV);
317320
}
318321

322+
// Get the global variable with the given name if it exists or create a new
323+
// external global.
324+
extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
325+
const char *Name,
326+
size_t NameLen,
327+
LLVMTypeRef Ty) {
328+
Module *Mod = unwrap(M);
329+
unsigned int AddressSpace =
330+
Mod->getDataLayout().getDefaultGlobalsAddressSpace();
331+
return LLVMRustGetOrInsertGlobalInAddrspace(M, Name, NameLen, Ty,
332+
AddressSpace);
333+
}
334+
319335
// Must match the layout of `rustc_codegen_llvm::llvm::ffi::AttributeKind`.
320336
enum class LLVMRustAttributeKind {
321337
AlwaysInline = 0,

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,7 @@ symbols! {
10261026
global_asm,
10271027
global_registration,
10281028
globs,
1029+
gpu_launch_sized_workgroup_mem,
10291030
gt,
10301031
guard,
10311032
guard_patterns,

library/core/src/intrinsics/gpu.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,46 @@
55
66
#![unstable(feature = "gpu_intrinsics", issue = "none")]
77

8+
/// Returns the pointer to workgroup memory allocated at launch-time on GPUs.
9+
///
10+
/// Workgroup memory is a memory region that is shared between all threads in
11+
/// the same workgroup. It is faster to access than other memory but pointers do not
12+
/// work outside the workgroup where they were obtained.
13+
/// Workgroup memory can be allocated statically or after compilation, when
14+
/// launching a gpu-kernel. `gpu_launch_sized_workgroup_mem` returns the pointer to
15+
/// the memory that is allocated at launch-time.
16+
/// The size of this memory can differ between launches of a gpu-kernel, depending on
17+
/// what is specified at launch-time.
18+
/// However, the alignment is fixed by the kernel itself, at compile-time.
19+
///
20+
/// The returned pointer is the start of the workgroup memory region that is
21+
/// allocated at launch-time.
22+
/// All calls to `gpu_launch_sized_workgroup_mem` in a workgroup, independent of the
23+
/// generic type, return the same address, so alias the same memory.
24+
/// The returned pointer is aligned by at least the alignment of `T`.
25+
///
26+
/// # Safety
27+
///
28+
/// The pointer is safe to dereference from the start (the returned pointer) up to the
29+
/// size of workgroup memory that was specified when launching the current gpu-kernel.
30+
/// This allocated size is not related in any way to `T`.
31+
///
32+
/// The user must take care of synchronizing access to workgroup memory between
33+
/// threads in a workgroup. The usual data race requirements apply.
34+
///
35+
/// # Other APIs
36+
///
37+
/// CUDA and HIP call this dynamic shared memory, shared between threads in a block.
38+
/// OpenCL and SYCL call this local memory, shared between threads in a work-group.
39+
/// GLSL calls this shared memory, shared between invocations in a work group.
40+
/// DirectX calls this groupshared memory, shared between threads in a thread-group.
41+
#[must_use = "returns a pointer that does nothing unless used"]
42+
#[rustc_intrinsic]
43+
#[rustc_nounwind]
44+
#[unstable(feature = "gpu_launch_sized_workgroup_mem", issue = "135513")]
45+
#[cfg(any(target_arch = "amdgpu", target_arch = "nvptx64"))]
46+
pub fn gpu_launch_sized_workgroup_mem<T>() -> *mut T;
47+
848
/// Returns a pointer to the HSA kernel dispatch packet.
949
///
1050
/// A `gpu-kernel` on amdgpu is always launched through a kernel dispatch packet.

src/tools/tidy/src/style.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,10 @@ fn should_ignore(line: &str) -> bool {
222222
|| static_regex!(
223223
"\\s*//@ \\!?(count|files|has|has-dir|hasraw|matches|matchesraw|snapshot)\\s.*"
224224
).is_match(line)
225+
// Matching for FileCheck checks
226+
|| static_regex!(
227+
"\\s*// [a-zA-Z0-9-_]*:\\s.*"
228+
).is_match(line)
225229
}
226230

227231
/// Returns `true` if `line` is allowed to be longer than the normal limit.

0 commit comments

Comments
 (0)