rustc_codegen_llvm/builder/autodiff.rs
1use std::ptr;
2
3use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
4use rustc_codegen_ssa::common::TypeKind;
5use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods};
6use rustc_middle::ty::{PseudoCanonicalInput, Ty, TyCtxt, TypingEnv};
7use rustc_middle::{bug, ty};
8use tracing::debug;
9
10use crate::builder::{Builder, PlaceRef, UNNAMED};
11use crate::context::SimpleCx;
12use crate::declare::declare_simple_fn;
13use crate::llvm;
14use crate::llvm::{Metadata, TRUE, Type};
15use crate::value::Value;
16
17pub(crate) fn adjust_activity_to_abi<'tcx>(
18 tcx: TyCtxt<'tcx>,
19 fn_ty: Ty<'tcx>,
20 da: &mut Vec<DiffActivity>,
21) {
22 if !matches!(fn_ty.kind(), ty::FnDef(..)) {
23 bug!("expected fn def for autodiff, got {:?}", fn_ty);
24 }
25
26 // We don't actually pass the types back into the type system.
27 // All we do is decide how to handle the arguments.
28 let sig = fn_ty.fn_sig(tcx).skip_binder();
29
30 let mut new_activities = vec![];
31 let mut new_positions = vec![];
32 for (i, ty) in sig.inputs().iter().enumerate() {
33 if let Some(inner_ty) = ty.builtin_deref(true) {
34 if inner_ty.is_slice() {
35 // Now we need to figure out the size of each slice element in memory to allow
36 // safety checks and usability improvements in the backend.
37 let sty = match inner_ty.builtin_index() {
38 Some(sty) => sty,
39 None => {
40 panic!("slice element type unknown");
41 }
42 };
43 let pci = PseudoCanonicalInput {
44 typing_env: TypingEnv::fully_monomorphized(),
45 value: sty,
46 };
47
48 let layout = tcx.layout_of(pci);
49 let elem_size = match layout {
50 Ok(layout) => layout.size,
51 Err(_) => {
52 bug!("autodiff failed to compute slice element size");
53 }
54 };
55 let elem_size: u32 = elem_size.bytes() as u32;
56
57 // We know that the length will be passed as extra arg.
58 if !da.is_empty() {
59 // We are looking at a slice. The length of that slice will become an
60 // extra integer on llvm level. Integers are always const.
61 // However, if the slice get's duplicated, we want to know to later check the
62 // size. So we mark the new size argument as FakeActivitySize.
63 // There is one FakeActivitySize per slice, so for convenience we store the
64 // slice element size in bytes in it. We will use the size in the backend.
65 let activity = match da[i] {
66 DiffActivity::DualOnly
67 | DiffActivity::Dual
68 | DiffActivity::Dualv
69 | DiffActivity::DuplicatedOnly
70 | DiffActivity::Duplicated => {
71 DiffActivity::FakeActivitySize(Some(elem_size))
72 }
73 DiffActivity::Const => DiffActivity::Const,
74 _ => bug!("unexpected activity for ptr/ref"),
75 };
76 new_activities.push(activity);
77 new_positions.push(i + 1);
78 }
79
80 continue;
81 }
82 }
83 }
84 // now add the extra activities coming from slices
85 // Reverse order to not invalidate the indices
86 for _ in 0..new_activities.len() {
87 let pos = new_positions.pop().unwrap();
88 let activity = new_activities.pop().unwrap();
89 da.insert(pos, activity);
90 }
91}
92
93// When we call the `__enzyme_autodiff` or `__enzyme_fwddiff` function, we need to pass all the
94// original inputs, as well as metadata and the additional shadow arguments.
95// This function matches the arguments from the outer function to the inner enzyme call.
96//
97// This function also considers that Rust level arguments not always match the llvm-ir level
98// arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
99// llvm-ir level. The number of activities matches the number of Rust level arguments, so we
100// need to match those.
101// FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
102// using iterators and peek()?
103fn match_args_from_caller_to_enzyme<'ll, 'tcx>(
104 cx: &SimpleCx<'ll>,
105 builder: &mut Builder<'_, 'll, 'tcx>,
106 width: u32,
107 args: &mut Vec<&'ll llvm::Value>,
108 inputs: &[DiffActivity],
109 outer_args: &[&'ll llvm::Value],
110) {
111 debug!("matching autodiff arguments");
112 // We now handle the issue that Rust level arguments not always match the llvm-ir level
113 // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
114 // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
115 // need to match those.
116 // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
117 // using iterators and peek()?
118 let mut outer_pos: usize = 0;
119 let mut activity_pos = 0;
120
121 let enzyme_const = cx.create_metadata(b"enzyme_const");
122 let enzyme_out = cx.create_metadata(b"enzyme_out");
123 let enzyme_dup = cx.create_metadata(b"enzyme_dup");
124 let enzyme_dupv = cx.create_metadata(b"enzyme_dupv");
125 let enzyme_dupnoneed = cx.create_metadata(b"enzyme_dupnoneed");
126 let enzyme_dupnoneedv = cx.create_metadata(b"enzyme_dupnoneedv");
127
128 while activity_pos < inputs.len() {
129 let diff_activity = inputs[activity_pos as usize];
130 // Duplicated arguments received a shadow argument, into which enzyme will write the
131 // gradient.
132 let (activity, duplicated): (&Metadata, bool) = match diff_activity {
133 DiffActivity::None => panic!("not a valid input activity"),
134 DiffActivity::Const => (enzyme_const, false),
135 DiffActivity::Active => (enzyme_out, false),
136 DiffActivity::ActiveOnly => (enzyme_out, false),
137 DiffActivity::Dual => (enzyme_dup, true),
138 DiffActivity::Dualv => (enzyme_dupv, true),
139 DiffActivity::DualOnly => (enzyme_dupnoneed, true),
140 DiffActivity::DualvOnly => (enzyme_dupnoneedv, true),
141 DiffActivity::Duplicated => (enzyme_dup, true),
142 DiffActivity::DuplicatedOnly => (enzyme_dupnoneed, true),
143 DiffActivity::FakeActivitySize(_) => (enzyme_const, false),
144 };
145 let outer_arg = outer_args[outer_pos];
146 args.push(cx.get_metadata_value(activity));
147 if matches!(diff_activity, DiffActivity::Dualv) {
148 let next_outer_arg = outer_args[outer_pos + 1];
149 let elem_bytes_size: u64 = match inputs[activity_pos + 1] {
150 DiffActivity::FakeActivitySize(Some(s)) => s.into(),
151 _ => bug!("incorrect Dualv handling recognized."),
152 };
153 // stride: sizeof(T) * n_elems.
154 // n_elems is the next integer.
155 // Now we multiply `4 * next_outer_arg` to get the stride.
156 let mul = unsafe {
157 llvm::LLVMBuildMul(
158 builder.llbuilder,
159 cx.get_const_int(cx.type_i64(), elem_bytes_size),
160 next_outer_arg,
161 UNNAMED,
162 )
163 };
164 args.push(mul);
165 }
166 args.push(outer_arg);
167 if duplicated {
168 // We know that duplicated args by construction have a following argument,
169 // so this can not be out of bounds.
170 let next_outer_arg = outer_args[outer_pos + 1];
171 let next_outer_ty = cx.val_ty(next_outer_arg);
172 // FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
173 // vectors behind references (&Vec<T>) are already supported. Users can not pass a
174 // Vec by value for reverse mode, so this would only help forward mode autodiff.
175 let slice = {
176 if activity_pos + 1 >= inputs.len() {
177 // If there is no arg following our ptr, it also can't be a slice,
178 // since that would lead to a ptr, int pair.
179 false
180 } else {
181 let next_activity = inputs[activity_pos + 1];
182 // We analyze the MIR types and add this dummy activity if we visit a slice.
183 matches!(next_activity, DiffActivity::FakeActivitySize(_))
184 }
185 };
186 if slice {
187 // A duplicated slice will have the following two outer_fn arguments:
188 // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
189 // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
190 // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
191 // int2 >= int1, which means the shadow vector is large enough to store the gradient.
192 assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Integer);
193
194 let iterations =
195 if matches!(diff_activity, DiffActivity::Dualv) { 1 } else { width as usize };
196
197 for i in 0..iterations {
198 let next_outer_arg2 = outer_args[outer_pos + 2 * (i + 1)];
199 let next_outer_ty2 = cx.val_ty(next_outer_arg2);
200 assert_eq!(cx.type_kind(next_outer_ty2), TypeKind::Pointer);
201 let next_outer_arg3 = outer_args[outer_pos + 2 * (i + 1) + 1];
202 let next_outer_ty3 = cx.val_ty(next_outer_arg3);
203 assert_eq!(cx.type_kind(next_outer_ty3), TypeKind::Integer);
204 args.push(next_outer_arg2);
205 }
206 args.push(cx.get_metadata_value(enzyme_const));
207 args.push(next_outer_arg);
208 outer_pos += 2 + 2 * iterations;
209 activity_pos += 2;
210 } else {
211 // A duplicated pointer will have the following two outer_fn arguments:
212 // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
213 // (..., metadata! enzyme_dup, ptr, ptr, ...).
214 if matches!(diff_activity, DiffActivity::Duplicated | DiffActivity::DuplicatedOnly)
215 {
216 assert_eq!(cx.type_kind(next_outer_ty), TypeKind::Pointer);
217 }
218 // In the case of Dual we don't have assumptions, e.g. f32 would be valid.
219 args.push(next_outer_arg);
220 outer_pos += 2;
221 activity_pos += 1;
222
223 // Now, if width > 1, we need to account for that
224 for _ in 1..width {
225 let next_outer_arg = outer_args[outer_pos];
226 args.push(next_outer_arg);
227 outer_pos += 1;
228 }
229 }
230 } else {
231 // We do not differentiate with resprect to this argument.
232 // We already added the metadata and argument above, so just increase the counters.
233 outer_pos += 1;
234 activity_pos += 1;
235 }
236 }
237}
238
239/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
240/// function with expected naming and calling conventions[^1] which will be
241/// discovered by the enzyme LLVM pass and its body populated with the differentiated
242/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
243/// function and handle the differences between the Rust calling convention and
244/// Enzyme.
245/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
246// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
247// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
248pub(crate) fn generate_enzyme_call<'ll, 'tcx>(
249 builder: &mut Builder<'_, 'll, 'tcx>,
250 cx: &SimpleCx<'ll>,
251 fn_to_diff: &'ll Value,
252 outer_name: &str,
253 ret_ty: &'ll Type,
254 fn_args: &[&'ll Value],
255 attrs: AutoDiffAttrs,
256 dest: PlaceRef<'tcx, &'ll Value>,
257) {
258 // We have to pick the name depending on whether we want forward or reverse mode autodiff.
259 let mut ad_name: String = match attrs.mode {
260 DiffMode::Forward => "__enzyme_fwddiff",
261 DiffMode::Reverse => "__enzyme_autodiff",
262 _ => panic!("logic bug in autodiff, unrecognized mode"),
263 }
264 .to_string();
265
266 // add outer_name to ad_name to make it unique, in case users apply autodiff to multiple
267 // functions. Unwrap will only panic, if LLVM gave us an invalid string.
268 ad_name.push_str(outer_name);
269
270 // Let us assume the user wrote the following function square:
271 //
272 // ```llvm
273 // define double @square(double %x) {
274 // entry:
275 // %0 = fmul double %x, %x
276 // ret double %0
277 // }
278 //
279 // define double @dsquare(double %x) {
280 // return 0.0;
281 // }
282 // ```
283 //
284 // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
285 // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
286 // Again, the arguments to all functions are slightly simplified.
287 // ```llvm
288 // declare double @__enzyme_autodiff_square(...)
289 //
290 // define double @dsquare(double %x) {
291 // entry:
292 // %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
293 // ret double %0
294 // }
295 // ```
296 let enzyme_ty = unsafe { llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, TRUE) };
297
298 // FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
299 // think a bit more about what should go here.
300 let cc = unsafe { llvm::LLVMGetFunctionCallConv(fn_to_diff) };
301 let ad_fn = declare_simple_fn(
302 cx,
303 &ad_name,
304 llvm::CallConv::try_from(cc).expect("invalid callconv"),
305 llvm::UnnamedAddr::No,
306 llvm::Visibility::Default,
307 enzyme_ty,
308 );
309
310 let num_args = llvm::LLVMCountParams(&fn_to_diff);
311 let mut args = Vec::with_capacity(num_args as usize + 1);
312 args.push(fn_to_diff);
313
314 let enzyme_primal_ret = cx.create_metadata(b"enzyme_primal_return");
315 if matches!(attrs.ret_activity, DiffActivity::Dual | DiffActivity::Active) {
316 args.push(cx.get_metadata_value(enzyme_primal_ret));
317 }
318 if attrs.width > 1 {
319 let enzyme_width = cx.create_metadata(b"enzyme_width");
320 args.push(cx.get_metadata_value(enzyme_width));
321 args.push(cx.get_const_int(cx.type_i64(), attrs.width as u64));
322 }
323
324 match_args_from_caller_to_enzyme(
325 &cx,
326 builder,
327 attrs.width,
328 &mut args,
329 &attrs.input_activity,
330 fn_args,
331 );
332
333 let call = builder.call(enzyme_ty, None, None, ad_fn, &args, None, None);
334
335 builder.store_to_place(call, dest.val);
336}