Skip to content

Commit cc300ab

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 bcf787a commit cc300ab

11 files changed

Lines changed: 168 additions & 7 deletions

File tree

compiler/rustc_abi/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1702,6 +1702,9 @@ pub struct AddressSpace(pub u32);
17021702
impl AddressSpace {
17031703
/// LLVM's `0` address space.
17041704
pub const ZERO: Self = AddressSpace(0);
1705+
/// The address space for workgroup memory on nvptx and amdgpu.
1706+
/// See e.g. the `gpu_launch_sized_workgroup_mem` intrinsic for details.
1707+
pub const GPU_WORKGROUP: Self = AddressSpace(3);
17051708
}
17061709

17071710
/// 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: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ use std::ffi::c_uint;
44
use std::ptr;
55

66
use rustc_abi::{
7-
Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size, WrappingRange,
7+
AddressSpace, Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size,
8+
WrappingRange,
89
};
910
use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
1011
use rustc_codegen_ssa::codegen_attrs::autodiff_attrs;
@@ -24,7 +25,7 @@ use rustc_session::config::CrateType;
2425
use rustc_span::{Span, Symbol, sym};
2526
use rustc_symbol_mangling::{mangle_internal_symbol, symbol_name_for_instance_in_crate};
2627
use rustc_target::callconv::PassMode;
27-
use rustc_target::spec::Os;
28+
use rustc_target::spec::{Arch, Os};
2829
use tracing::debug;
2930

3031
use crate::abi::FnAbiLlvmExt;
@@ -560,6 +561,44 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
560561
return Ok(());
561562
}
562563

564+
sym::gpu_launch_sized_workgroup_mem => {
565+
// The name of the global variable is not relevant, the important properties are.
566+
// 1. The global is in the address space for workgroup memory
567+
// 2. It is an extern global
568+
// All instances of extern addrspace(gpu_workgroup) globals are merged in the LLVM backend.
569+
// Generate an unnamed global per intrinsic call, so that different kernels can have
570+
// different minimum alignments.
571+
// See https://docs.nvidia.com/cuda/cuda-c-programming-guide/#shared
572+
// FIXME Workaround an nvptx backend issue that extern globals must have a name
573+
let name = if tcx.sess.target.arch == Arch::Nvptx64 {
574+
"gpu_launch_sized_workgroup_mem"
575+
} else {
576+
""
577+
};
578+
let global = self.declare_global_in_addrspace(
579+
name,
580+
self.type_array(self.type_i8(), 0),
581+
AddressSpace::GPU_WORKGROUP,
582+
);
583+
let ty::RawPtr(inner_ty, _) = result.layout.ty.kind() else { unreachable!() };
584+
// The alignment of the global is used to specify the *minimum* alignment that
585+
// must be obeyed by the GPU runtime.
586+
// When multiple of these global variables are used by a kernel, the maximum alignment is taken.
587+
// See https://github.com/llvm/llvm-project/blob/a271d07488a85ce677674bbe8101b10efff58c95/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp#L821
588+
let alignment = self.align_of(*inner_ty).bytes() as u32;
589+
unsafe {
590+
// FIXME Workaround the above issue by taking maximum alignment if the global existed
591+
if tcx.sess.target.arch == Arch::Nvptx64 {
592+
if alignment > llvm::LLVMGetAlignment(global) {
593+
llvm::LLVMSetAlignment(global, alignment);
594+
}
595+
} else {
596+
llvm::LLVMSetAlignment(global, alignment);
597+
}
598+
}
599+
self.cx().const_pointercast(global, self.type_ptr())
600+
}
601+
563602
sym::amdgpu_dispatch_ptr => {
564603
let val = self.call_intrinsic("llvm.amdgcn.dispatch.ptr", &[], &[]);
565604
// 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
@@ -1979,6 +1979,13 @@ unsafe extern "C" {
19791979
NameLen: size_t,
19801980
T: &'a Type,
19811981
) -> &'a Value;
1982+
pub(crate) fn LLVMRustGetOrInsertGlobalInAddrspace<'a>(
1983+
M: &'a Module,
1984+
Name: *const c_char,
1985+
NameLen: size_t,
1986+
T: &'a Type,
1987+
AddressSpace: c_uint,
1988+
) -> &'a Value;
19821989
pub(crate) fn LLVMRustGetNamedValue(
19831990
M: &Module,
19841991
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
@@ -133,6 +133,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi
133133
| sym::forget
134134
| sym::frem_algebraic
135135
| sym::fsub_algebraic
136+
| sym::gpu_launch_sized_workgroup_mem
136137
| sym::is_val_statically_known
137138
| sym::log2f16
138139
| sym::log2f32
@@ -297,6 +298,7 @@ pub(crate) fn check_intrinsic_type(
297298
sym::offset_of => (1, 0, vec![tcx.types.u32, tcx.types.u32], tcx.types.usize),
298299
sym::rustc_peek => (1, 0, vec![param(0)], param(0)),
299300
sym::caller_location => (0, 0, vec![], tcx.caller_location_ty()),
301+
sym::gpu_launch_sized_workgroup_mem => (1, 0, vec![], Ty::new_mut_ptr(tcx, param(0))),
300302
sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => {
301303
(1, 0, vec![], tcx.types.unit)
302304
}

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -283,10 +283,10 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
283283
.getCallee());
284284
}
285285

286-
extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
287-
const char *Name,
288-
size_t NameLen,
289-
LLVMTypeRef Ty) {
286+
extern "C" LLVMValueRef
287+
LLVMRustGetOrInsertGlobalInAddrspace(LLVMModuleRef M, const char *Name,
288+
size_t NameLen, LLVMTypeRef Ty,
289+
unsigned AddressSpace) {
290290
Module *Mod = unwrap(M);
291291
auto NameRef = StringRef(Name, NameLen);
292292

@@ -297,10 +297,21 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
297297
GlobalVariable *GV = Mod->getGlobalVariable(NameRef, true);
298298
if (!GV)
299299
GV = new GlobalVariable(*Mod, unwrap(Ty), false,
300-
GlobalValue::ExternalLinkage, nullptr, NameRef);
300+
GlobalValue::ExternalLinkage, nullptr, NameRef,
301+
nullptr, GlobalValue::NotThreadLocal, AddressSpace);
301302
return wrap(GV);
302303
}
303304

305+
extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
306+
const char *Name,
307+
size_t NameLen,
308+
LLVMTypeRef Ty) {
309+
Module *Mod = unwrap(M);
310+
unsigned AddressSpace = Mod->getDataLayout().getDefaultGlobalsAddressSpace();
311+
return LLVMRustGetOrInsertGlobalInAddrspace(M, Name, NameLen, Ty,
312+
AddressSpace);
313+
}
314+
304315
// Must match the layout of `rustc_codegen_llvm::llvm::ffi::AttributeKind`.
305316
enum class LLVMRustAttributeKind {
306317
AlwaysInline = 0,

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,6 +1168,7 @@ symbols! {
11681168
global_asm,
11691169
global_registration,
11701170
globs,
1171+
gpu_launch_sized_workgroup_mem,
11711172
gt,
11721173
guard_patterns,
11731174
half_open_range_patterns,

library/core/src/intrinsics/mod.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3451,6 +3451,45 @@ pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize
34513451
)
34523452
}
34533453

3454+
/// Returns the pointer to workgroup memory allocated at launch-time on GPUs.
3455+
///
3456+
/// Workgroup memory is a memory region that is shared between all threads in
3457+
/// the same workgroup. It is faster to access than other memory but pointers do not
3458+
/// work outside the workgroup where they were obtained.
3459+
/// Workgroup memory can be allocated statically or after compilation, when
3460+
/// launching a gpu-kernel. `gpu_launch_sized_workgroup_mem` returns the pointer to
3461+
/// the memory that is allocated at launch-time.
3462+
/// The size of this memory can differ between launches of a gpu-kernel, depending on
3463+
/// what is specified at launch-time.
3464+
/// However, the alignment is fixed by the kernel itself, at compile-time.
3465+
///
3466+
/// The returned pointer is the start of the workgroup memory region that is
3467+
/// allocated at launch-time.
3468+
/// All calls to `gpu_launch_sized_workgroup_mem` in a workgroup, independent of the
3469+
/// generic type, return the same address, so alias the same memory.
3470+
/// The returned pointer is aligned by at least the alignment of `T`.
3471+
///
3472+
/// # Safety
3473+
///
3474+
/// The pointer is safe to dereference from the start (the returned pointer) up to the
3475+
/// size of workgroup memory that was specified when launching the current gpu-kernel.
3476+
///
3477+
/// The user must take care of synchronizing access to workgroup memory between
3478+
/// threads in a workgroup. The usual data race requirements apply.
3479+
///
3480+
/// # Other APIs
3481+
///
3482+
/// CUDA and HIP call this dynamic shared memory, shared between threads in a block.
3483+
/// OpenCL and SYCL call this local memory, shared between threads in a work-group.
3484+
/// GLSL calls this shared memory, shared between invocations in a work group.
3485+
/// DirectX calls this groupshared memory, shared between threads in a thread-group.
3486+
#[must_use = "returns a pointer that does nothing unless used"]
3487+
#[rustc_intrinsic]
3488+
#[rustc_nounwind]
3489+
#[unstable(feature = "gpu_launch_sized_workgroup_mem", issue = "135513")]
3490+
#[cfg(any(target_arch = "amdgpu", target_arch = "nvptx64"))]
3491+
pub fn gpu_launch_sized_workgroup_mem<T>() -> *mut T;
3492+
34543493
/// Copies the current location of arglist `src` to the arglist `dst`.
34553494
///
34563495
/// # Safety

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)