1use std::ptr;
23use rustc_ast::expand::autodiff_attrs::{DiffActivity, DiffMode};
4use rustc_ast::expand::typetree::FncTree;
5use rustc_codegen_ssa::common::TypeKind;
6use rustc_codegen_ssa::mir::IntrinsicResult;
7use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
8use rustc_codegen_ssa::mir::place::PlaceValue;
9use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods};
10use rustc_data_structures::thin_vec::ThinVec;
11use rustc_hir::attrs::RustcAutodiff;
12use rustc_middle::ty::{PseudoCanonicalInput, Ty, TyCtxt, TypingEnv};
13use rustc_middle::{bug, ty};
14use rustc_target::callconv::PassMode;
15use tracing::debug;
1617use crate::builder::{Builder, UNNAMED};
18use crate::context::SimpleCx;
19use crate::declare::declare_simple_fn;
20use crate::llvm::{self, TRUE, Type, Value};
2122pub(crate) fn adjust_activity_to_abi<'tcx>(
23 tcx: TyCtxt<'tcx>,
24 fn_ptr_ty: Ty<'tcx>,
25 typing_env: TypingEnv<'tcx>,
26 da: &mut ThinVec<DiffActivity>,
27) {
28if !#[allow(non_exhaustive_omitted_patterns)] match fn_ptr_ty.kind() {
ty::FnPtr(..) => true,
_ => false,
}matches!(fn_ptr_ty.kind(), ty::FnPtr(..)) {
29::rustc_middle::util::bug::bug_fmt(format_args!("expected fn ptr for autodiff, got {0:?}",
fn_ptr_ty));bug!("expected fn ptr for autodiff, got {:?}", fn_ptr_ty);
30 }
3132// We don't actually pass the types back into the type system.
33 // All we do is decide how to handle the arguments.
34let fn_sig = fn_ptr_ty.fn_sig(tcx);
35let sig = fn_sig.skip_binder();
3637// FIXME(Sa4dUs): pass proper varargs once we have support for differentiating variadic functions
38let Ok(fn_abi) = tcx.fn_abi_of_fn_ptr(typing_env.as_query_input((fn_sig, ty::List::empty())))
39else {
40::rustc_middle::util::bug::bug_fmt(format_args!("failed to get fn_abi of fn_ptr with empty varargs"));bug!("failed to get fn_abi of fn_ptr with empty varargs");
41 };
4243let mut new_activities = ::alloc::vec::Vec::new()vec![];
44let mut new_positions = ::alloc::vec::Vec::new()vec![];
45let mut del_activities = 0;
46for (i, ty) in sig.inputs().iter().enumerate() {
47if let Some(inner_ty) = ty.builtin_deref(true) {
48let tail_ty = tcx.struct_tail_for_codegen(inner_ty, typing_env);
49if let ty::Slice(element_ty) = tail_ty.kind() {
50// Now we need to figure out the size of each slice element in memory to allow
51 // safety checks and usability improvements in the backend.
52let pci = PseudoCanonicalInput {
53 typing_env: TypingEnv::fully_monomorphized(),
54 value: *element_ty,
55 };
5657let layout = tcx.layout_of(pci);
58let elem_size = match layout {
59Ok(layout) => layout.size,
60Err(_) => {
61::rustc_middle::util::bug::bug_fmt(format_args!("autodiff failed to compute slice element size"));bug!("autodiff failed to compute slice element size");
62 }
63 };
64let elem_size: u32 = elem_size.bytes() as u32;
6566// We know that the length will be passed as extra arg.
67if !da.is_empty() {
68// We are looking at a slice. The length of that slice will become an
69 // extra integer on llvm level. Integers are always const.
70 // However, if the slice get's duplicated, we want to know to later check the
71 // size. So we mark the new size argument as FakeActivitySize.
72 // There is one FakeActivitySize per slice, so for convenience we store the
73 // slice element size in bytes in it. We will use the size in the backend.
74let activity = match da[i] {
75 DiffActivity::DualOnly
76 | DiffActivity::Dual
77 | DiffActivity::Dualv
78 | DiffActivity::DuplicatedOnly
79 | DiffActivity::Duplicated => {
80 DiffActivity::FakeActivitySize(Some(elem_size))
81 }
82 DiffActivity::Const => DiffActivity::Const,
83_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected activity for ptr/ref"))bug!("unexpected activity for ptr/ref"),
84 };
85 new_activities.push(activity);
86 new_positions.push(i + 1);
87 }
8889continue;
90 }
91 }
9293let pci = PseudoCanonicalInput { typing_env: TypingEnv::fully_monomorphized(), value: *ty };
9495let layout = match tcx.layout_of(pci) {
96Ok(layout) => layout.layout,
97Err(_) => {
98::rustc_middle::util::bug::bug_fmt(format_args!("failed to compute layout for type {0:?}",
ty));bug!("failed to compute layout for type {:?}", ty);
99 }
100 };
101102let pass_mode = &fn_abi.args[i].mode;
103104// For ZST, just ignore and don't add its activity, as this arg won't be present
105 // in the LLVM passed to Enzyme.
106 // Some targets pass ZST indirectly in the C ABI, in that case, handle it as a normal arg
107 // FIXME(Sa4dUs): Enforce ZST corresponding diff activity be `Const`
108if *pass_mode == PassMode::Ignore {
109 del_activities += 1;
110 da.remove(i);
111 }
112113// If the argument is lowered as a `ScalarPair`, we need to duplicate its activity.
114 // Otherwise, the number of activities won't match the number of LLVM arguments and
115 // this will lead to errors when verifying the Enzyme call.
116if let rustc_abi::BackendRepr::ScalarPair { a: _, b: _, b_offset: _ } =
117 layout.backend_repr()
118 {
119 new_activities.push(da[i].clone());
120 new_positions.push(i + 1 - del_activities);
121 }
122 }
123// now add the extra activities coming from slices
124 // Reverse order to not invalidate the indices
125for _ in 0..new_activities.len() {
126let pos = new_positions.pop().unwrap();
127let activity = new_activities.pop().unwrap();
128 da.insert(pos, activity);
129 }
130}
131132// When we call the `__enzyme_autodiff` or `__enzyme_fwddiff` function, we need to pass all the
133// original inputs, as well as metadata and the additional shadow arguments.
134// This function matches the arguments from the outer function to the inner enzyme call.
135//
136// This function also considers that Rust level arguments not always match the llvm-ir level
137// arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
138// llvm-ir level. The number of activities matches the number of Rust level arguments, so we
139// need to match those.
140// FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
141// using iterators and peek()?
142fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
143 builder: &mut Builder<'_, 'll, 'tcx>,
144 width: u32,
145 args: &mut Vec<&'ll Value>,
146 inputs: &[DiffActivity],
147 outer_args: &[&'ll Value],
148) {
149{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder/autodiff.rs:149",
"rustc_codegen_llvm::builder::autodiff",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder/autodiff.rs"),
::tracing_core::__macro_support::Option::Some(149u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder::autodiff"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("matching autodiff arguments")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("matching autodiff arguments");
150// We now handle the issue that Rust level arguments not always match the llvm-ir level
151 // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
152 // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
153 // need to match those.
154 // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
155 // using iterators and peek()?
156let cx = &builder.scx;
157let mut outer_pos: usize = 0;
158let mut activity_pos = 0;
159160// We used to use llvm's metadata to instruct enzyme how to differentiate a function.
161 // In debug mode we would use incremental compilation which caused the metadata to be
162 // dropped. This is prevented by now using named globals, which are also understood
163 // by Enzyme.
164let global_const = cx.declare_global("enzyme_const", cx.type_ptr());
165let global_out = cx.declare_global("enzyme_out", cx.type_ptr());
166let global_dup = cx.declare_global("enzyme_dup", cx.type_ptr());
167let global_dupv = cx.declare_global("enzyme_dupv", cx.type_ptr());
168let global_dupnoneed = cx.declare_global("enzyme_dupnoneed", cx.type_ptr());
169let global_dupnoneedv = cx.declare_global("enzyme_dupnoneedv", cx.type_ptr());
170171while activity_pos < inputs.len() {
172let diff_activity = inputs[activity_pos as usize];
173// Duplicated arguments received a shadow argument, into which enzyme will write the
174 // gradient.
175let (activity, duplicated): (&Value, bool) = match diff_activity {
176 DiffActivity::None => { ::core::panicking::panic_fmt(format_args!("not a valid input activity")); }panic!("not a valid input activity"),
177 DiffActivity::Const => (global_const, false),
178 DiffActivity::Active => (global_out, false),
179 DiffActivity::ActiveOnly => (global_out, false),
180 DiffActivity::Dual => (global_dup, true),
181 DiffActivity::Dualv => (global_dupv, true),
182 DiffActivity::DualOnly => (global_dupnoneed, true),
183 DiffActivity::DualvOnly => (global_dupnoneedv, true),
184 DiffActivity::Duplicated => (global_dup, true),
185 DiffActivity::DuplicatedOnly => (global_dupnoneed, true),
186 DiffActivity::FakeActivitySize(_) => (global_const, false),
187 };
188let outer_arg = outer_args[outer_pos];
189 args.push(activity);
190if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) {
191let next_outer_arg = outer_args[outer_pos + 1];
192let elem_bytes_size: u64 = match inputs[activity_pos + 1] {
193 DiffActivity::FakeActivitySize(Some(s)) => s.into(),
194_ => ::rustc_middle::util::bug::bug_fmt(format_args!("incorrect Dualv handling recognized."))bug!("incorrect Dualv handling recognized."),
195 };
196// stride: sizeof(T) * n_elems.
197 // n_elems is the next integer.
198 // Now we multiply `4 * next_outer_arg` to get the stride.
199let mul = unsafe {
200 llvm::LLVMBuildMul(
201 builder.llbuilder,
202 cx.get_const_int(cx.type_i64(), elem_bytes_size),
203 next_outer_arg,
204 UNNAMED,
205 )
206 };
207 args.push(mul);
208 }
209 args.push(outer_arg);
210if duplicated {
211// We know that duplicated args by construction have a following argument,
212 // so this can not be out of bounds.
213let next_outer_arg = outer_args[outer_pos + 1];
214let next_outer_ty = cx.val_ty(next_outer_arg);
215// FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
216 // vectors behind references (&Vec<T>) are already supported. Users can not pass a
217 // Vec by value for reverse mode, so this would only help forward mode autodiff.
218let slice = {
219if activity_pos + 1 >= inputs.len() {
220// If there is no arg following our ptr, it also can't be a slice,
221 // since that would lead to a ptr, int pair.
222false
223} else {
224let next_activity = inputs[activity_pos + 1];
225// We analyze the MIR types and add this dummy activity if we visit a slice.
226#[allow(non_exhaustive_omitted_patterns)] match next_activity {
DiffActivity::FakeActivitySize(_) => true,
_ => false,
}matches!(next_activity, DiffActivity::FakeActivitySize(_))227 }
228 };
229if slice {
230// A duplicated slice will have the following two outer_fn arguments:
231 // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
232 // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
233 // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
234 // int2 >= int1, which means the shadow vector is large enough to store the gradient.
235{
match (&cx.type_kind(next_outer_ty), &TypeKind::Integer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Integer);
236237let iterations =
238if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Dualv => true,
_ => false,
}matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
239240for i in 0..iterations {
241let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
242let next_outer_ty2 = cx.val_ty(next_outer_arg2);
243{
match (&cx.type_kind(next_outer_ty2), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty2), TypeKind::Pointer);
244let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
245let next_outer_ty3 = cx.val_ty(next_outer_arg3);
246{
match (&cx.type_kind(next_outer_ty3), &TypeKind::Integer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty3), TypeKind::Integer);
247 args.push(next_outer_arg2);
248 }
249 args.push(global_const);
250 args.push(next_outer_arg);
251 outer_pos += 2 + 2 * iterations;
252 activity_pos += 2;
253 } else {
254// A duplicated pointer will have the following two outer_fn arguments:
255 // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
256 // (..., metadata! enzyme_dup, ptr, ptr, ...).
257if #[allow(non_exhaustive_omitted_patterns)] match diff_activity {
DiffActivity::Duplicated | DiffActivity::DuplicatedOnly => true,
_ => false,
}matches!(diff_activity, DiffActivity::Duplicated | DiffActivity::DuplicatedOnly)258 {
259{
match (&cx.type_kind(next_outer_ty), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Pointer);
260 }
261// In the case of Dual we don't have assumptions, e.g. f32 would be valid.
262args.push(next_outer_arg);
263 outer_pos += 2;
264 activity_pos += 1;
265266// Now, if width > 1, we need to account for that
267for _ in 1..width {
268let next_outer_arg = outer_args[outer_pos];
269 args.push(next_outer_arg);
270 outer_pos += 1;
271 }
272 }
273 } else {
274// We do not differentiate with resprect to this argument.
275 // We already added the metadata and argument above, so just increase the counters.
276outer_pos += 1;
277 activity_pos += 1;
278 }
279 }
280}
281282/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
283/// function with expected naming and calling conventions[^1] which will be
284/// discovered by the enzyme LLVM pass and its body populated with the differentiated
285/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
286/// function and handle the differences between the Rust calling convention and
287/// Enzyme.
288/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
289// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
290// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
291pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
292 bx: &mut Builder<'_, 'll, 'tcx>,
293 fn_to_diff: &'ll Value,
294 outer_name: &str,
295 ret_ty: &'ll Type,
296 fn_args: &[&'ll Value],
297 attrs: &RustcAutodiff,
298 dest_layout: ty::layout::TyAndLayout<'tcx>,
299 dest_place: Option<PlaceValue<&'ll Value>>,
300 fnc_tree: FncTree,
301) -> IntrinsicResult<'tcx, &'ll Value> {
302let cx: &SimpleCx<'ll> = &bx.scx;
303// We have to pick the name depending on whether we want forward or reverse mode autodiff.
304let mut ad_name: String = match attrs.mode {
305 DiffMode::Forward => "__enzyme_fwddiff",
306 DiffMode::Reverse => "__enzyme_autodiff",
307_ => {
::core::panicking::panic_fmt(format_args!("logic bug in autodiff, unrecognized mode"));
}panic!("logic bug in autodiff, unrecognized mode"),
308 }
309 .to_string();
310311// add outer_name to ad_name to make it unique, in case users apply autodiff to multiple
312 // functions. Unwrap will only panic, if LLVM gave us an invalid string.
313ad_name.push_str(outer_name);
314315// Let us assume the user wrote the following function square:
316 //
317 // ```llvm
318 // define double @square(double %x) {
319 // entry:
320 // %0 = fmul double %x, %x
321 // ret double %0
322 // }
323 //
324 // define double @dsquare(double %x) {
325 // return 0.0;
326 // }
327 // ```
328 //
329 // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
330 // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
331 // Again, the arguments to all functions are slightly simplified.
332 // ```llvm
333 // declare double @__enzyme_autodiff_square(...)
334 //
335 // define double @dsquare(double %x) {
336 // entry:
337 // %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
338 // ret double %0
339 // }
340 // ```
341let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
342343// FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
344 // think a bit more about what should go here.
345let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
346let ad_fn = declare_simple_fn(
347cx,
348&ad_name,
349 llvm::CallConv::try_from(cc).expect("invalid callconv"),
350 llvm::UnnamedAddr::No,
351 llvm::Visibility::Default,
352enzyme_ty,
353 );
354355let num_args = llvm::LLVMCountParams(&fn_to_diff);
356let mut args = Vec::with_capacity(num_argsas usize + 1);
357args.push(fn_to_diff);
358359let global_primal_ret = cx.declare_global("enzyme_primal_return", cx.type_ptr());
360if #[allow(non_exhaustive_omitted_patterns)] match attrs.ret_activity {
DiffActivity::Dual | DiffActivity::Active => true,
_ => false,
}matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
361args.push(global_primal_ret);
362 }
363if attrs.width > 1 {
364let global_width = cx.declare_global("enzyme_width", cx.type_ptr());
365args.push(global_width);
366args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
367 }
368369match_args_from_caller_to_enzyme(bx, attrs.width, &mut args, &attrs.input_activity, fn_args);
370371if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() {
372crate::typetree::add_tt(&bx, fn_to_diff, fnc_tree);
373 }
374375let call = bx.call(enzyme_ty, None, None, ad_fn, &args, None, None);
376377let fn_ret_ty = bx.cx.val_ty(call);
378if fn_ret_ty == bx.cx.type_void() || fn_ret_ty == bx.cx.type_struct(&[], false) {
379// If we return void or an empty struct, then our caller (due to how we generated it)
380 // does not expect a return value. As such, we have no pointer (or place) into which
381 // we could store our value, and would store into an undef, which would cause UB.
382 // As such, we just ignore the return value in those cases.
383IntrinsicResult::Operand(OperandValue::ZeroSized)
384 } else if let Some(dest_place) = dest_place {
385bx.store_to_place(call, dest_place);
386 IntrinsicResult::WroteIntoPlace
387 } else {
388 IntrinsicResult::Operand(
389 OperandRef::from_immediate_or_packed_pair(bx, call, dest_layout).val,
390 )
391 }
392}