Skip to main content

rustc_codegen_llvm/builder/
gpu_offload.rs

1use std::ffi::CString;
2
3use bitflags::Flags;
4use llvm::Linkage::*;
5use rustc_abi::{Align, HasDataLayout, Integer, Primitive, Size};
6use rustc_codegen_ssa::MemFlags;
7use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
8use rustc_codegen_ssa::mir::place::PlaceValue;
9use rustc_codegen_ssa::traits::{
10    BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, ReturnSlot,
11};
12use rustc_middle::ty::offload_meta::{MappingFlags, OffloadMetadata, OffloadSize};
13use rustc_span::bug;
14
15use crate::attributes;
16use crate::builder::Builder;
17use crate::common::CodegenCx;
18use crate::context::SimpleCx;
19use crate::llvm::AttributePlace::Function;
20use crate::llvm::{self, FunctionSignature, Linkage, Type, TypeKind, Value};
21
22// LLVM kernel-independent globals required for offloading
23pub(crate) struct OffloadGlobals<'ll> {
24    pub launcher_fn: llvm::Value<'ll>,
25    pub launcher_ty: llvm::FunctionSignature<'ll>,
26
27    pub kernel_args_ty: KernelArgsTy,
28
29    pub offload_entry_ty: llvm::Type<'ll>,
30
31    pub begin_mapper: llvm::Value<'ll>,
32    pub end_mapper: llvm::Value<'ll>,
33    pub mapper_fn_ty: llvm::FunctionSignature<'ll>,
34
35    pub ident_t_global: llvm::Value<'ll>,
36}
37
38impl<'ll> OffloadGlobals<'ll> {
39    pub(crate) fn declare(cx: &CodegenCx<'ll, '_>) -> Self {
40        let (launcher_fn, launcher_ty) = generate_launcher(cx);
41        let kernel_args_ty = KernelArgsTy::new_decl(cx);
42        let offload_entry_ty = TgtOffloadEntry::new_decl(cx);
43        let (begin_mapper, _, end_mapper, mapper_fn_ty) = gen_tgt_data_mappers(cx);
44        let ident_t_global = generate_at_one(cx);
45
46        // We want LLVM's openmp-opt pass to pick up and optimize this module, since it covers both
47        // openmp and offload optimizations.
48        llvm::add_module_flag_u32(cx.llmod(), llvm::ModuleFlagMergeBehavior::Max, "openmp", 51);
49
50        OffloadGlobals {
51            launcher_fn,
52            launcher_ty,
53            kernel_args_ty,
54            offload_entry_ty,
55            begin_mapper,
56            end_mapper,
57            mapper_fn_ty,
58            ident_t_global,
59        }
60    }
61}
62
63pub(crate) struct OffloadKernelDims<'ll> {
64    num_workgroups: Value<'ll>,
65    threads_per_block: Value<'ll>,
66    workgroup_dims: [Value<'ll>; 3],
67    thread_dims: [Value<'ll>; 3],
68}
69
70impl<'ll> OffloadKernelDims<'ll> {
71    pub(crate) fn from_operands<'tcx>(
72        builder: &mut Builder<'_, 'll, 'tcx>,
73        workgroup_op: &OperandRef<'tcx, llvm::Value<'ll>>,
74        thread_op: &OperandRef<'tcx, llvm::Value<'ll>>,
75    ) -> Self {
76        fn load_3_u32<'ll>(
77            builder: &mut Builder<'_, 'll, '_>,
78            place: PlaceValue<Value<'ll>>,
79        ) -> [Value<'ll>; 3] {
80            let ty = builder.type_i32();
81            let size = 4;
82            let v0 = builder.load(ty, place.llval, place.align);
83            let p1 = builder.inbounds_ptradd(place.llval, builder.const_usize(size));
84            let v1 = builder.load(ty, p1, place.align.restrict_for_offset(Size::from_bytes(size)));
85            let p2 = builder.inbounds_ptradd(place.llval, builder.const_usize(size * 2));
86            let v2 =
87                builder.load(ty, p2, place.align.restrict_for_offset(Size::from_bytes(size * 2)));
88            [v0, v1, v2]
89        }
90
91        let OperandValue::Ref(place) = workgroup_op.val else {
92            ::rustc_span::macros::bug_impl(None,
    format_args!("expected array operand by reference"), Location::caller());bug!("expected array operand by reference");
93        };
94        let workgroup_val = load_3_u32(builder, place);
95
96        let OperandValue::Ref(place) = thread_op.val else {
97            ::rustc_span::macros::bug_impl(None,
    format_args!("expected array operand by reference"), Location::caller());bug!("expected array operand by reference");
98        };
99        let thread_val = load_3_u32(builder, place);
100
101        fn mul_dim3<'ll, 'tcx>(
102            builder: &mut Builder<'_, 'll, 'tcx>,
103            [x, y, z]: [Value<'ll>; 3],
104        ) -> Value<'ll> {
105            let xy = builder.mul(x, y);
106            builder.mul(xy, z)
107        }
108
109        let num_workgroups = mul_dim3(builder, workgroup_val);
110        let threads_per_block = mul_dim3(builder, thread_val);
111
112        OffloadKernelDims {
113            workgroup_dims: workgroup_val,
114            thread_dims: thread_val,
115            num_workgroups,
116            threads_per_block,
117        }
118    }
119}
120
121// ; Function Attrs: nounwind
122// declare i32 @__tgt_target_kernel(ptr, i64, i32, i32, ptr, ptr) #2
123fn generate_launcher<'ll>(
124    cx: &CodegenCx<'ll, '_>,
125) -> (llvm::Value<'ll>, llvm::FunctionSignature<'ll>) {
126    let tptr = cx.type_ptr();
127    let ti64 = cx.type_i64();
128    let ti32 = cx.type_i32();
129    let args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tptr, ti64, ti32, ti32, tptr, tptr]))vec![tptr, ti64, ti32, ti32, tptr, tptr];
130    let tgt_fn_ty = cx.type_func(&args, ti32);
131    let name = "__tgt_target_kernel";
132    let tgt_decl = declare_offload_fn(cx, name, tgt_fn_ty);
133    let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx);
134    attributes::apply_to_llfn(tgt_decl, Function, &[nounwind]);
135    (tgt_decl, tgt_fn_ty)
136}
137
138/// Declares the `omp_get_num_devices` runtime function and returns the
139/// declaration together with its type.
140pub(crate) fn declare_omp_get_num_devices<'ll>(
141    cx: &CodegenCx<'ll, '_>,
142) -> (llvm::Value<'ll>, llvm::FunctionSignature<'ll>) {
143    let ti32 = cx.type_i32();
144    let tgt_fn_ty = cx.type_func(&[], ti32);
145    let name = "omp_get_num_devices";
146    let tgt_decl = declare_offload_fn(cx, name, tgt_fn_ty);
147    let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx);
148    attributes::apply_to_llfn(tgt_decl, Function, &[nounwind]);
149    (tgt_decl, tgt_fn_ty)
150}
151
152// What is our @1 here? A magic global, used in our data_{begin/update/end}_mapper:
153// @0 = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00", align 1
154// @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 22, ptr @0 }, align 8
155// FIXME(offload): @0 should include the file name (e.g. lib.rs) in which the function to be
156// offloaded was defined.
157pub(crate) fn generate_at_one<'ll>(cx: &CodegenCx<'ll, '_>) -> llvm::Value<'ll> {
158    let unknown_txt = ";unknown;unknown;0;0;;";
159    let c_entry_name = CString::new(unknown_txt).unwrap();
160    let c_val = c_entry_name.as_bytes_with_nul();
161    let initializer = crate::common::bytes_in_context(cx.llcx, c_val);
162    let at_zero = add_unnamed_global(cx, "", initializer, PrivateLinkage);
163    llvm::set_alignment(at_zero, Align::ONE);
164
165    // @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 22, ptr @0 }, align 8
166    let struct_elems = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [cx.get_const_i32(0), cx.get_const_i32(2), cx.get_const_i32(0),
                cx.get_const_i32(22), at_zero]))vec![
167        cx.get_const_i32(0),
168        cx.get_const_i32(2),
169        cx.get_const_i32(0),
170        cx.get_const_i32(22),
171        at_zero,
172    ];
173    let struct_elems_ty: Vec<_> = struct_elems.iter().map(|&x| cx.val_ty(x)).collect();
174    let struct_ident_ty = cx.type_named_struct("struct.ident_t", &struct_elems_ty);
175    let initializer = crate::common::named_struct(struct_ident_ty, &struct_elems);
176    let at_one = add_unnamed_global(cx, "", initializer, PrivateLinkage);
177    llvm::set_alignment(at_one, Align::EIGHT);
178    at_one
179}
180
181pub(crate) struct TgtOffloadEntry {
182    //   uint64_t Reserved;
183    //   uint16_t Version;
184    //   uint16_t Kind;
185    //   uint32_t Flags; Flags associated with the entry (see Target Region Entry Flags)
186    //   void *Address; Address of global symbol within device image (function or global)
187    //   char *SymbolName;
188    //   uint64_t Size; Size of the entry info (0 if it is a function)
189    //   uint64_t Data;
190    //   void *AuxAddr;
191}
192
193impl TgtOffloadEntry {
194    pub(crate) fn new_decl<'ll>(cx: &CodegenCx<'ll, '_>) -> llvm::Type<'ll> {
195        let tptr = cx.type_ptr();
196        let ti64 = cx.type_i64();
197        let ti32 = cx.type_i32();
198        let ti16 = cx.type_i16();
199        // For each kernel to run on the gpu, we will later generate one entry of this type.
200        // copied from LLVM
201        let offload_entry_ty = cx.type_named_struct(
202            "struct.__tgt_offload_entry",
203            &[ti64, ti16, ti16, ti32, tptr, tptr, ti64, ti64, tptr],
204        );
205        offload_entry_ty
206    }
207
208    fn new<'ll>(
209        cx: &CodegenCx<'ll, '_>,
210        region_id: Value<'ll>,
211        llglobal: Value<'ll>,
212    ) -> [Value<'ll>; 9] {
213        let reserved = cx.get_const_i64(0);
214        let version = cx.get_const_i16(1);
215        let kind = cx.get_const_i16(1);
216        let flags = cx.get_const_i32(0);
217        let size = cx.get_const_i64(0);
218        let data = cx.get_const_i64(0);
219        let aux_addr = cx.const_null(cx.type_ptr());
220        [reserved, version, kind, flags, region_id, llglobal, size, data, aux_addr]
221    }
222}
223
224// Taken from the LLVM APITypes.h declaration:
225pub(crate) struct KernelArgsTy {
226    pub field_offsets: [(&'static str, Size); Self::FIELD_COUNT],
227    pub size: Size,
228    pub align: Align,
229    //  uint32_t Version = 0; // Version of this struct for ABI compatibility.
230    //  uint32_t NumArgs = 0; // Number of arguments in each input pointer.
231    //  void **ArgBasePtrs =
232    //      nullptr;                 // Base pointer of each argument (e.g. a struct).
233    //  void **ArgPtrs = nullptr;    // Pointer to the argument data.
234    //  int64_t *ArgSizes = nullptr; // Size of the argument data in bytes.
235    //  int64_t *ArgTypes = nullptr; // Type of the data (e.g. to / from).
236    //  void **ArgNames = nullptr;   // Name of the data for debugging, possibly null.
237    //  void **ArgMappers = nullptr; // User-defined mappers, possibly null.
238    //  uint64_t Tripcount =
239    // 0; // Tripcount for the teams / distribute loop, 0 otherwise.
240    // struct {
241    //    uint64_t NoWait : 1; // Was this kernel spawned with a `nowait` clause.
242    //    uint64_t IsCUDA : 1; // Was this kernel spawned via CUDA.
243    //    uint64_t Unused : 62;
244    //  } Flags = {0, 0, 0}; // totals to 64 Bit, 8 Byte
245    //  // The number of teams (for x,y,z dimension).
246    //  uint32_t NumTeams[3] = {0, 0, 0};
247    //  // The number of threads (for x,y,z dimension).
248    //  uint32_t ThreadLimit[3] = {0, 0, 0};
249    //  uint32_t DynCGroupMem = 0; // Amount of dynamic cgroup memory requested.
250}
251
252impl KernelArgsTy {
253    const FIELD_COUNT: usize = 17;
254    const OFFLOAD_VERSION: u64 = 3;
255    const FLAGS: u64 = 1 << 6; // Enable StrictBlocksAndThreads
256    const TRIPCOUNT: u64 = 0;
257
258    fn new_decl<'ll>(cx: &CodegenCx<'ll, '_>) -> Self {
259        let uint32_t = Primitive::Int(Integer::I32, false);
260        let ptr = Primitive::Pointer(cx.data_layout().default_address_space);
261        let uint64_t = Primitive::Int(Integer::I64, false);
262        let mut current_offset = Size::ZERO;
263        let mut max_align = Align::ONE;
264        let field_offsets = [
265            ("Version", uint32_t),
266            ("NumArgs", uint32_t),
267            ("ArgBasePtrs", ptr),
268            ("ArgPtrs", ptr),
269            ("ArgSizes", ptr),
270            ("ArgTypes", ptr),
271            ("ArgNames", ptr),
272            ("ArgMappers", ptr),
273            ("Tripcount", uint64_t),
274            ("Flags", uint64_t),
275            ("NumTeamsX", uint32_t),
276            ("NumTeamsY", uint32_t),
277            ("NumTeamsZ", uint32_t),
278            ("ThreadLimitX", uint32_t),
279            ("ThreadLimitY", uint32_t),
280            ("ThreadLimitZ", uint32_t),
281            ("DynCGroupMem", uint32_t),
282        ]
283        .map(|(name, ty)| {
284            let align = ty.default_align(cx);
285            let this_offset = current_offset.align_to(align);
286            current_offset = this_offset + ty.size(cx);
287            max_align = max_align.max(align);
288            (name, this_offset)
289        });
290        Self { field_offsets, size: current_offset.align_to(max_align), align: max_align }
291    }
292
293    fn new<'ll, 'tcx>(
294        cx: &CodegenCx<'ll, 'tcx>,
295        num_args: u64,
296        memtransfer_types: Value<'ll>,
297        geps: [Value<'ll>; 3],
298        workgroup_dims: [Value<'ll>; 3],
299        thread_dims: [Value<'ll>; 3],
300        dyn_cache: Value<'ll>,
301    ) -> [Value<'ll>; Self::FIELD_COUNT] {
302        [
303            // Version
304            cx.get_const_i32(KernelArgsTy::OFFLOAD_VERSION),
305            // NumArgs
306            cx.get_const_i32(num_args),
307            // ArgBasePtrs
308            geps[0],
309            // ArgPtrs
310            geps[1],
311            // ArgSizes
312            geps[2],
313            // ArgTypes
314            memtransfer_types,
315            // The next two are debug infos. FIXME(offload): set them
316            // ArgNames
317            cx.const_null(cx.type_ptr()), // dbg
318            // ArgMappers
319            cx.const_null(cx.type_ptr()), // dbg
320            // Tripcount
321            cx.get_const_i64(KernelArgsTy::TRIPCOUNT),
322            // Flags
323            cx.get_const_i64(KernelArgsTy::FLAGS),
324            // NumTeams
325            workgroup_dims[0],
326            workgroup_dims[1],
327            workgroup_dims[2],
328            // ThreadLimit
329            thread_dims[0],
330            thread_dims[1],
331            thread_dims[2],
332            // DynCGroupMem
333            dyn_cache,
334        ]
335    }
336}
337
338// Contains LLVM values needed to manage offloading for a single kernel.
339#[derive(#[automatically_derived]impl<'ll> ::core::marker::Copy for
    OffloadKernelGlobals<'ll> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'ll>
    ::core::clone::TrivialClone for OffloadKernelGlobals<'ll> {
}
#[automatically_derived]impl<'ll> ::core::clone::Clone for
    OffloadKernelGlobals<'ll> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<llvm::Value<'ll>>;
        let _: ::core::clone::AssertParamIsClone<llvm::Value<'ll>>;
        let _: ::core::clone::AssertParamIsClone<llvm::Value<'ll>>;
        let _: ::core::clone::AssertParamIsClone<llvm::Value<'ll>>;
        let _: ::core::clone::AssertParamIsClone<llvm::Value<'ll>>;
        *self
    }
}Clone)]
340pub(crate) struct OffloadKernelGlobals<'ll> {
341    pub offload_sizes: llvm::Value<'ll>,
342    pub memtransfer_begin: llvm::Value<'ll>,
343    pub memtransfer_kernel: llvm::Value<'ll>,
344    pub memtransfer_end: llvm::Value<'ll>,
345    pub region_id: llvm::Value<'ll>,
346}
347
348fn gen_tgt_data_mappers<'ll>(
349    cx: &CodegenCx<'ll, '_>,
350) -> (llvm::Value<'ll>, llvm::Value<'ll>, llvm::Value<'ll>, llvm::FunctionSignature<'ll>) {
351    let tptr = cx.type_ptr();
352    let ti64 = cx.type_i64();
353    let ti32 = cx.type_i32();
354
355    let args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tptr, ti64, ti32, tptr, tptr, tptr, tptr, tptr, tptr]))vec![tptr, ti64, ti32, tptr, tptr, tptr, tptr, tptr, tptr];
356    let mapper_fn_ty = cx.type_func(&args, cx.type_void());
357    let mapper_begin = "__tgt_target_data_begin_mapper";
358    let mapper_update = "__tgt_target_data_update_mapper";
359    let mapper_end = "__tgt_target_data_end_mapper";
360    let begin_mapper_decl = declare_offload_fn(cx, mapper_begin, mapper_fn_ty);
361    let update_mapper_decl = declare_offload_fn(cx, mapper_update, mapper_fn_ty);
362    let end_mapper_decl = declare_offload_fn(cx, mapper_end, mapper_fn_ty);
363
364    let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx);
365    attributes::apply_to_llfn(begin_mapper_decl, Function, &[nounwind]);
366    attributes::apply_to_llfn(update_mapper_decl, Function, &[nounwind]);
367    attributes::apply_to_llfn(end_mapper_decl, Function, &[nounwind]);
368
369    (begin_mapper_decl, update_mapper_decl, end_mapper_decl, mapper_fn_ty)
370}
371
372fn add_priv_unnamed_arr<'ll>(cx: &SimpleCx<'ll>, name: &str, vals: &[u64]) -> llvm::Value<'ll> {
373    let ti64 = cx.type_i64();
374    let mut size_val = Vec::with_capacity(vals.len());
375    for &val in vals {
376        size_val.push(cx.get_const_i64(val));
377    }
378    let initializer = cx.const_array(ti64, &size_val);
379    add_unnamed_global(cx, name, initializer, PrivateLinkage)
380}
381
382pub(crate) fn add_unnamed_global<'ll>(
383    cx: &SimpleCx<'ll>,
384    name: &str,
385    initializer: llvm::Value<'ll>,
386    l: Linkage,
387) -> llvm::Value<'ll> {
388    let llglobal = add_global(cx, name, initializer, l);
389    llvm::LLVMSetUnnamedAddress(llglobal, llvm::UnnamedAddr::Global);
390    llglobal
391}
392
393pub(crate) fn add_global<'ll>(
394    cx: &SimpleCx<'ll>,
395    name: &str,
396    initializer: llvm::Value<'ll>,
397    l: Linkage,
398) -> llvm::Value<'ll> {
399    let c_name = CString::new(name).unwrap();
400    let llglobal: llvm::Value<'ll> = llvm::add_global(cx.llmod, cx.val_ty(initializer), &c_name);
401    llvm::set_global_constant(llglobal, true);
402    llvm::set_linkage(llglobal, l);
403    llvm::set_initializer(llglobal, initializer);
404    llglobal
405}
406
407// This function returns a memtransfer value which encodes how arguments to this kernel shall be
408// mapped to/from the gpu. It also returns a region_id with the name of this kernel, to be
409// concatenated into the list of region_ids.
410pub(crate) fn gen_define_handling<'ll>(
411    cx: &CodegenCx<'ll, '_>,
412    metadata: &[OffloadMetadata],
413    symbol: String,
414    offload_globals: &OffloadGlobals<'ll>,
415) -> OffloadKernelGlobals<'ll> {
416    if let Some(entry) = cx.offload_kernel_cache.borrow().get(&symbol) {
417        return *entry;
418    }
419
420    let offload_entry_ty = offload_globals.offload_entry_ty;
421
422    let (sizes, transfer): (Vec<_>, Vec<_>) =
423        metadata.iter().map(|m| (m.payload_size, m.mode)).unzip();
424    // Our begin mapper should only see simplified information about which args have to be
425    // transferred to the device, the end mapper only about which args should be transferred back.
426    // Any information beyond that makes it harder for LLVM's opt pass to evaluate whether it can
427    // safely move (=optimize) the LLVM-IR location of this data transfer. Only the mapping types
428    // mentioned below are handled, so make sure that we don't generate any other ones.
429    let handled_mappings = MappingFlags::TO
430        | MappingFlags::FROM
431        | MappingFlags::TARGET_PARAM
432        | MappingFlags::LITERAL
433        | MappingFlags::IMPLICIT;
434    for arg in &transfer {
435        if true {
    if !!arg.contains_unknown_bits() {
        ::core::panicking::panic("assertion failed: !arg.contains_unknown_bits()")
    };
};debug_assert!(!arg.contains_unknown_bits());
436        if true {
    if !handled_mappings.contains(*arg) {
        ::core::panicking::panic("assertion failed: handled_mappings.contains(*arg)")
    };
};debug_assert!(handled_mappings.contains(*arg));
437    }
438
439    let valid_begin_mappings = MappingFlags::TO | MappingFlags::LITERAL | MappingFlags::IMPLICIT;
440    let transfer_to: Vec<u64> =
441        transfer.iter().map(|m| m.intersection(valid_begin_mappings).bits()).collect();
442    let transfer_from: Vec<u64> =
443        transfer.iter().map(|m| m.intersection(MappingFlags::FROM).bits()).collect();
444    let valid_kernel_mappings = MappingFlags::LITERAL | MappingFlags::IMPLICIT;
445    // FIXME(offload): add `OMP_MAP_TARGET_PARAM = 0x20` only if necessary
446    let transfer_kernel: Vec<u64> = transfer
447        .iter()
448        .map(|m| (m.intersection(valid_kernel_mappings) | MappingFlags::TARGET_PARAM).bits())
449        .collect();
450
451    let actual_sizes = sizes
452        .iter()
453        .map(|s| match s {
454            OffloadSize::Static(sz) => *sz,
455            // NOTE(Sa4dUs): set `.offload_sizes` entry to 0 for sizes that we determine at runtime, just like clang
456            _ => 0,
457        })
458        .collect::<Vec<_>>();
459    let offload_sizes =
460        add_priv_unnamed_arr(cx, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".offload_sizes.{0}", symbol))
    })format!(".offload_sizes.{symbol}"), &actual_sizes);
461    let memtransfer_begin =
462        add_priv_unnamed_arr(cx, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".offload_maptypes.{0}.begin",
                symbol))
    })format!(".offload_maptypes.{symbol}.begin"), &transfer_to);
463    let memtransfer_kernel =
464        add_priv_unnamed_arr(cx, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".offload_maptypes.{0}.kernel",
                symbol))
    })format!(".offload_maptypes.{symbol}.kernel"), &transfer_kernel);
465    let memtransfer_end =
466        add_priv_unnamed_arr(cx, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".offload_maptypes.{0}.end",
                symbol))
    })format!(".offload_maptypes.{symbol}.end"), &transfer_from);
467
468    // Next: For each function, generate these three entries. A weak constant,
469    // the llvm.rodata entry name, and  the llvm_offload_entries value
470
471    let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".{0}.region_id", symbol))
    })format!(".{symbol}.region_id");
472    let initializer = cx.get_const_i8(0);
473    let region_id = add_global(cx, &name, initializer, WeakAnyLinkage);
474
475    let c_entry_name = CString::new(symbol.clone()).unwrap();
476    let c_val = c_entry_name.as_bytes_with_nul();
477    let offload_entry_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".offloading.entry_name.{0}",
                symbol))
    })format!(".offloading.entry_name.{symbol}");
478
479    let initializer = crate::common::bytes_in_context(cx.llcx, c_val);
480    let llglobal = add_unnamed_global(cx, &offload_entry_name, initializer, InternalLinkage);
481    llvm::set_alignment(llglobal, Align::ONE);
482    llvm::set_section(llglobal, c".llvm.rodata.offloading");
483
484    let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".offloading.entry.{0}", symbol))
    })format!(".offloading.entry.{symbol}");
485
486    // See the __tgt_offload_entry documentation above.
487    let elems = TgtOffloadEntry::new(cx, region_id, llglobal);
488
489    let initializer = crate::common::named_struct(offload_entry_ty, &elems);
490    let c_name = CString::new(name).unwrap();
491    let offload_entry = llvm::add_global(cx.llmod, offload_entry_ty, &c_name);
492    llvm::set_global_constant(offload_entry, true);
493    llvm::set_linkage(offload_entry, WeakAnyLinkage);
494    llvm::set_initializer(offload_entry, initializer);
495    llvm::set_alignment(offload_entry, Align::EIGHT);
496    let c_section_name = CString::new("llvm_offload_entries").unwrap();
497    llvm::set_section(offload_entry, &c_section_name);
498
499    cx.add_compiler_used_global(offload_entry);
500
501    let result = OffloadKernelGlobals {
502        offload_sizes,
503        memtransfer_begin,
504        memtransfer_kernel,
505        memtransfer_end,
506        region_id,
507    };
508
509    cx.offload_kernel_cache.borrow_mut().insert(symbol, result);
510
511    result
512}
513
514fn declare_offload_fn<'ll>(
515    cx: &CodegenCx<'ll, '_>,
516    name: &str,
517    ty: llvm::FunctionSignature<'ll>,
518) -> llvm::Value<'ll> {
519    crate::declare::declare_simple_fn(
520        cx,
521        name,
522        llvm::CallConv::CCallConv,
523        llvm::UnnamedAddr::No,
524        llvm::Visibility::Default,
525        ty,
526    )
527}
528
529pub(crate) fn scalar_width<'ll>(cx: &SimpleCx<'ll>, ty: Type<'ll>) -> u64 {
530    if let Some(float) = cx.float_type(ty) {
531        float.size().bits()
532    } else if let Some(width) = cx.int_width(ty) {
533        width
534    } else if cx.type_kind(ty) == TypeKind::Pointer {
535        ::rustc_span::macros::bug_impl(None,
    format_args!("scalar_width doesn\'t support pointer type {0:?}", ty),
    Location::caller())bug!("scalar_width doesn't support pointer type {ty:?}")
536    } else {
537        ::rustc_span::macros::bug_impl(None,
    format_args!("scalar_width was called on a non scalar type {0:?}", ty),
    Location::caller())bug!("scalar_width was called on a non scalar type {ty:?}")
538    }
539}
540
541fn get_runtime_size<'ll, 'tcx>(
542    builder: &mut Builder<'_, 'll, 'tcx>,
543    args: &[Value<'ll>],
544    index: usize,
545    meta: &OffloadMetadata,
546) -> Value<'ll> {
547    match meta.payload_size {
548        OffloadSize::Slice { element_size } => {
549            let length_idx = index + 1;
550            let length = args[length_idx];
551            let length_i64 = builder.intcast(length, builder.cx.type_i64(), false);
552            builder.mul(length_i64, builder.cx.get_const_i64(element_size))
553        }
554        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected offload size {0:?}", meta.payload_size),
    Location::caller())bug!("unexpected offload size {:?}", meta.payload_size),
555    }
556}
557
558// For each kernel *call*, we now use some of our previous declared globals to move data to and from
559// the gpu. For now, we only handle the data transfer part of it.
560// If two consecutive kernels use the same memory, we still move it to the host and back to the gpu.
561// Since in our frontend users (by default) don't have to specify data transfer, this is something
562// we should optimize in the future! In some cases we can directly zero-allocate on the device and
563// only move data back, or if something is immutable, we might only copy it to the device.
564//
565// Current steps:
566// 0. Alloca some variables for the following steps
567// 1. set insert point before kernel call.
568// 2. generate all the GEPS and stores, to be used in 3)
569// 3. generate __tgt_target_data_begin calls to move data to the GPU
570//
571// unchanged: keep kernel call. Later move the kernel to the GPU
572//
573// 4. set insert point after kernel call.
574// 5. generate all the GEPS and stores, to be used in 6)
575// 6. generate __tgt_target_data_end calls to move data from the GPU
576pub(crate) fn gen_call_handling<'ll, 'tcx>(
577    builder: &mut Builder<'_, 'll, 'tcx>,
578    offload_data: &OffloadKernelGlobals<'ll>,
579    args: &[Value<'ll>],
580    types: &[Type<'ll>],
581    metadata: &[OffloadMetadata],
582    offload_globals: &OffloadGlobals<'ll>,
583    offload_dims: &OffloadKernelDims<'ll>,
584    dyn_cache: Value<'ll>,
585    device_id: Value<'ll>,
586) {
587    let cx = builder.cx;
588    let &OffloadKernelGlobals {
589        offload_sizes,
590        memtransfer_begin,
591        memtransfer_kernel,
592        memtransfer_end,
593        region_id,
594    } = offload_data;
595    let &OffloadKernelDims { num_workgroups, threads_per_block, workgroup_dims, thread_dims } =
596        offload_dims;
597
598    let has_dynamic = metadata.iter().any(|m| !#[allow(non_exhaustive_omitted_patterns)] match m.payload_size {
    OffloadSize::Static(_) => true,
    _ => false,
}matches!(m.payload_size, OffloadSize::Static(_)));
599
600    let tgt_decl = offload_globals.launcher_fn;
601    let tgt_target_kernel_ty = offload_globals.launcher_ty;
602
603    let tgt_kernel_decl = &offload_globals.kernel_args_ty;
604    let begin_mapper_decl = offload_globals.begin_mapper;
605    let end_mapper_decl = offload_globals.end_mapper;
606    let fn_ty = offload_globals.mapper_fn_ty;
607
608    let num_args = types.len() as u64;
609    let bb = builder.llbb();
610
611    // Step 0)
612    unsafe {
613        llvm::LLVMRustPositionBuilderPastAllocas(builder.llbuilder(), builder.llfn());
614    }
615
616    let pointer_array_size = cx.data_layout().pointer_size() * num_args;
617    // Baseptr are just the input pointer to the kernel, stored in a local alloca
618    let a1 = builder.direct_alloca(pointer_array_size, Align::EIGHT, ".offload_baseptrs");
619    // Ptrs are the result of a gep into the baseptr, at least for our trivial types.
620    let a2 = builder.direct_alloca(pointer_array_size, Align::EIGHT, ".offload_ptrs");
621    // These represent the sizes in bytes, e.g. the entry for `&[f64; 16]` will be 8*16.
622    let size_array_size = Size::from_bytes(8) * num_args;
623
624    let a4 = if has_dynamic {
625        let alloc = builder.direct_alloca(size_array_size, Align::EIGHT, ".offload_sizes");
626
627        builder.memcpy(
628            alloc,
629            Align::EIGHT,
630            offload_sizes,
631            Align::EIGHT,
632            cx.get_const_i64(8 * args.len() as u64),
633            MemFlags::empty(),
634            None,
635        );
636
637        alloc
638    } else {
639        offload_sizes
640    };
641
642    //%kernel_args = alloca %struct.__tgt_kernel_arguments, align 8
643    let a5 = builder.direct_alloca(tgt_kernel_decl.size, tgt_kernel_decl.align, "kernel_args");
644
645    // Step 1)
646    unsafe {
647        llvm::LLVMPositionBuilderAtEnd(builder.llbuilder(), bb);
648    }
649
650    // Now we allocate once per function param, a copy to be passed to one of our maps.
651    let mut vals = ::alloc::vec::Vec::new()vec![];
652    let mut geps = ::alloc::vec::Vec::new()vec![];
653    for &v in args {
654        let ty = cx.val_ty(v);
655        let ty_kind = cx.type_kind(ty);
656        let (base_val, gep_base) = match ty_kind {
657            TypeKind::Pointer => (v, v),
658            TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
659                // FIXME(Sa4dUs): check for `f128` support, latest NVIDIA cards support it
660                let num_bits = scalar_width(cx, ty);
661
662                let bb = builder.llbb();
663                unsafe {
664                    llvm::LLVMRustPositionBuilderPastAllocas(builder.llbuilder(), builder.llfn());
665                }
666                let addr = builder.direct_alloca(Size::from_bytes(8), Align::EIGHT, "addr");
667                unsafe {
668                    llvm::LLVMPositionBuilderAtEnd(builder.llbuilder(), bb);
669                }
670
671                let cast = builder.bitcast(v, cx.type_ix(num_bits));
672                let value = builder.zext(cast, cx.type_i64());
673                builder.store(value, addr, Align::EIGHT);
674                (value, addr)
675            }
676            other => ::rustc_span::macros::bug_impl(None,
    format_args!("offload does not support {0:?}", other), Location::caller())bug!("offload does not support {other:?}"),
677        };
678
679        vals.push(base_val);
680        geps.push(gep_base);
681    }
682
683    for i in 0..num_args {
684        let pointer_offset = cx.const_usize((cx.data_layout().pointer_size() * i).bytes());
685        let gep1 = builder.inbounds_ptradd(a1, pointer_offset);
686        builder.store(vals[i as usize], gep1, Align::EIGHT);
687        let gep2 = builder.inbounds_ptradd(a2, pointer_offset);
688        builder.store(geps[i as usize], gep2, Align::EIGHT);
689
690        if !#[allow(non_exhaustive_omitted_patterns)] match metadata[i as
                usize].payload_size {
    OffloadSize::Static(_) => true,
    _ => false,
}matches!(metadata[i as usize].payload_size, OffloadSize::Static(_)) {
691            let gep3 = builder.inbounds_ptradd(a4, cx.const_usize(8 * i));
692            let size_val = get_runtime_size(builder, args, i as usize, &metadata[i as usize]);
693            builder.store(size_val, gep3, Align::EIGHT);
694        }
695    }
696
697    // For now we have a very simplistic indexing scheme into our
698    // offload_{baseptrs,ptrs,sizes}. We will probably improve this along with our gpu frontend pr.
699    fn get_geps<'ll, 'tcx>(
700        _builder: &mut Builder<'_, 'll, 'tcx>,
701        a1: Value<'ll>,
702        a2: Value<'ll>,
703        a4: Value<'ll>,
704        _is_dynamic: bool,
705    ) -> [Value<'ll>; 3] {
706        [a1, a2, a4]
707    }
708
709    fn generate_mapper_call<'ll, 'tcx>(
710        builder: &mut Builder<'_, 'll, 'tcx>,
711        geps: [Value<'ll>; 3],
712        o_type: Value<'ll>,
713        fn_to_call: Value<'ll>,
714        fn_ty: FunctionSignature<'ll>,
715        num_args: u64,
716        s_ident_t: Value<'ll>,
717    ) {
718        let cx = builder.cx;
719        let nullptr = cx.const_null(cx.type_ptr());
720        let i64_max = cx.get_const_i64(u64::MAX);
721        let num_args = cx.get_const_i32(num_args);
722        let args =
723            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [s_ident_t, i64_max, num_args, geps[0], geps[1], geps[2], o_type,
                nullptr, nullptr]))vec![s_ident_t, i64_max, num_args, geps[0], geps[1], geps[2], o_type, nullptr, nullptr];
724        builder.call(fn_ty, None, None, fn_to_call, ReturnSlot::Direct, &args, None, None);
725    }
726
727    // Step 2)
728    let s_ident_t = offload_globals.ident_t_global;
729    let geps = get_geps(builder, a1, a2, a4, has_dynamic);
730    generate_mapper_call(
731        builder,
732        geps,
733        memtransfer_begin,
734        begin_mapper_decl,
735        fn_ty,
736        num_args,
737        s_ident_t,
738    );
739    let values = KernelArgsTy::new(
740        cx,
741        num_args,
742        memtransfer_kernel,
743        geps,
744        workgroup_dims,
745        thread_dims,
746        dyn_cache,
747    );
748
749    // Step 3)
750    // Here we fill the KernelArgsTy, see the documentation above
751    for ((name, offset), value) in tgt_kernel_decl.field_offsets.into_iter().zip(values) {
752        let ptr = if offset.bytes() == 0 {
753            a5
754        } else {
755            let ptr = builder.inbounds_ptradd(a5, cx.const_usize(offset.bytes()));
756            llvm::set_value_name(ptr, name.as_bytes());
757            ptr
758        };
759
760        builder.store(value, ptr, tgt_kernel_decl.align.restrict_for_offset(offset));
761    }
762
763    let device_id = builder.sext(device_id, cx.type_i64());
764    let args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [s_ident_t, device_id, num_workgroups, threads_per_block, region_id,
                a5]))vec![s_ident_t, device_id, num_workgroups, threads_per_block, region_id, a5];
765    builder.call(tgt_target_kernel_ty, None, None, tgt_decl, ReturnSlot::Direct, &args, None, None);
766    // %41 = call i32 @__tgt_target_kernel(ptr @1, i64 -1, i32 2097152, i32 256, ptr @.kernel_1.region_id, ptr %kernel_args)
767
768    // Step 4)
769    let geps = get_geps(builder, a1, a2, a4, has_dynamic);
770    generate_mapper_call(
771        builder,
772        geps,
773        memtransfer_end,
774        end_mapper_decl,
775        fn_ty,
776        num_args,
777        s_ident_t,
778    );
779}