rustc_codegen_llvm/builder/
autodiff.rs

1use std::ptr;
2
3use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, AutoDiffItem, DiffActivity, DiffMode};
4use rustc_codegen_ssa::ModuleCodegen;
5use rustc_codegen_ssa::back::write::ModuleConfig;
6use rustc_errors::FatalError;
7use tracing::{debug, trace};
8
9use crate::back::write::llvm_err;
10use crate::builder::SBuilder;
11use crate::context::SimpleCx;
12use crate::declare::declare_simple_fn;
13use crate::errors::LlvmError;
14use crate::llvm::AttributePlace::Function;
15use crate::llvm::{Metadata, True};
16use crate::value::Value;
17use crate::{CodegenContext, LlvmCodegenBackend, ModuleLlvm, attributes, llvm};
18
19fn get_params(fnc: &Value) -> Vec<&Value> {
20    unsafe {
21        let param_num = llvm::LLVMCountParams(fnc) as usize;
22        let mut fnc_args: Vec<&Value> = vec![];
23        fnc_args.reserve(param_num);
24        llvm::LLVMGetParams(fnc, fnc_args.as_mut_ptr());
25        fnc_args.set_len(param_num);
26        fnc_args
27    }
28}
29
30/// When differentiating `fn_to_diff`, take a `outer_fn` and generate another
31/// function with expected naming and calling conventions[^1] which will be
32/// discovered by the enzyme LLVM pass and its body populated with the differentiated
33/// `fn_to_diff`. `outer_fn` is then modified to have a call to the generated
34/// function and handle the differences between the Rust calling convention and
35/// Enzyme.
36/// [^1]: <https://enzyme.mit.edu/getting_started/CallingConvention/>
37// FIXME(ZuseZ4): `outer_fn` should include upstream safety checks to
38// cover some assumptions of enzyme/autodiff, which could lead to UB otherwise.
39fn generate_enzyme_call<'ll>(
40    cx: &SimpleCx<'ll>,
41    fn_to_diff: &'ll Value,
42    outer_fn: &'ll Value,
43    attrs: AutoDiffAttrs,
44) {
45    let inputs = attrs.input_activity;
46    let output = attrs.ret_activity;
47
48    // We have to pick the name depending on whether we want forward or reverse mode autodiff.
49    // FIXME(ZuseZ4): The new pass based approach should not need the {Forward/Reverse}First method anymore, since
50    // it will handle higher-order derivatives correctly automatically (in theory). Currently
51    // higher-order derivatives fail, so we should debug that before adjusting this code.
52    let mut ad_name: String = match attrs.mode {
53        DiffMode::Forward => "__enzyme_fwddiff",
54        DiffMode::Reverse => "__enzyme_autodiff",
55        _ => panic!("logic bug in autodiff, unrecognized mode"),
56    }
57    .to_string();
58
59    // add outer_fn name to ad_name to make it unique, in case users apply autodiff to multiple
60    // functions. Unwrap will only panic, if LLVM gave us an invalid string.
61    let name = llvm::get_value_name(outer_fn);
62    let outer_fn_name = std::str::from_utf8(name).unwrap();
63    ad_name.push_str(outer_fn_name);
64
65    // Let us assume the user wrote the following function square:
66    //
67    // ```llvm
68    // define double @square(double %x) {
69    // entry:
70    //  %0 = fmul double %x, %x
71    //  ret double %0
72    // }
73    // ```
74    //
75    // The user now applies autodiff to the function square, in which case fn_to_diff will be `square`.
76    // Our macro generates the following placeholder code (slightly simplified):
77    //
78    // ```llvm
79    // define double @dsquare(double %x) {
80    //  ; placeholder code
81    //  return 0.0;
82    // }
83    // ```
84    //
85    // so our `outer_fn` will be `dsquare`. The unsafe code section below now removes the placeholder
86    // code and inserts an autodiff call. We also add a declaration for the __enzyme_autodiff call.
87    // Again, the arguments to all functions are slightly simplified.
88    // ```llvm
89    // declare double @__enzyme_autodiff_square(...)
90    //
91    // define double @dsquare(double %x) {
92    // entry:
93    //   %0 = tail call double (...) @__enzyme_autodiff_square(double (double)* nonnull @square, double %x)
94    //   ret double %0
95    // }
96    // ```
97    unsafe {
98        // On LLVM-IR, we can luckily declare __enzyme_ functions without specifying the input
99        // arguments. We do however need to declare them with their correct return type.
100        // We already figured the correct return type out in our frontend, when generating the outer_fn,
101        // so we can now just go ahead and use that. FIXME(ZuseZ4): This doesn't handle sret yet.
102        let fn_ty = llvm::LLVMGlobalGetValueType(outer_fn);
103        let ret_ty = llvm::LLVMGetReturnType(fn_ty);
104
105        // LLVM can figure out the input types on it's own, so we take a shortcut here.
106        let enzyme_ty = llvm::LLVMFunctionType(ret_ty, ptr::null(), 0, True);
107
108        //FIXME(ZuseZ4): the CC/Addr/Vis values are best effort guesses, we should look at tests and
109        // think a bit more about what should go here.
110        let cc = llvm::LLVMGetFunctionCallConv(outer_fn);
111        let ad_fn = declare_simple_fn(
112            cx,
113            &ad_name,
114            llvm::CallConv::try_from(cc).expect("invalid callconv"),
115            llvm::UnnamedAddr::No,
116            llvm::Visibility::Default,
117            enzyme_ty,
118        );
119
120        // Otherwise LLVM might inline our temporary code before the enzyme pass has a chance to
121        // do it's work.
122        let attr = llvm::AttributeKind::NoInline.create_attr(cx.llcx);
123        attributes::apply_to_llfn(ad_fn, Function, &[attr]);
124
125        // first, remove all calls from fnc
126        let entry = llvm::LLVMGetFirstBasicBlock(outer_fn);
127        let br = llvm::LLVMRustGetTerminator(entry);
128        llvm::LLVMRustEraseInstFromParent(br);
129
130        let last_inst = llvm::LLVMRustGetLastInstruction(entry).unwrap();
131        let mut builder = SBuilder::build(cx, entry);
132
133        let num_args = llvm::LLVMCountParams(&fn_to_diff);
134        let mut args = Vec::with_capacity(num_args as usize + 1);
135        args.push(fn_to_diff);
136
137        let enzyme_const = cx.create_metadata("enzyme_const".to_string()).unwrap();
138        let enzyme_out = cx.create_metadata("enzyme_out".to_string()).unwrap();
139        let enzyme_dup = cx.create_metadata("enzyme_dup".to_string()).unwrap();
140        let enzyme_dupnoneed = cx.create_metadata("enzyme_dupnoneed".to_string()).unwrap();
141        let enzyme_primal_ret = cx.create_metadata("enzyme_primal_return".to_string()).unwrap();
142
143        match output {
144            DiffActivity::Dual => {
145                args.push(cx.get_metadata_value(enzyme_primal_ret));
146            }
147            DiffActivity::Active => {
148                args.push(cx.get_metadata_value(enzyme_primal_ret));
149            }
150            _ => {}
151        }
152
153        debug!("matching autodiff arguments");
154        // We now handle the issue that Rust level arguments not always match the llvm-ir level
155        // arguments. A slice, `&[f32]`, for example, is represented as a pointer and a length on
156        // llvm-ir level. The number of activities matches the number of Rust level arguments, so we
157        // need to match those.
158        // FIXME(ZuseZ4): This logic is a bit more complicated than it should be, can we simplify it
159        // using iterators and peek()?
160        let mut outer_pos: usize = 0;
161        let mut activity_pos = 0;
162        let outer_args: Vec<&llvm::Value> = get_params(outer_fn);
163        while activity_pos < inputs.len() {
164            let diff_activity = inputs[activity_pos as usize];
165            // Duplicated arguments received a shadow argument, into which enzyme will write the
166            // gradient.
167            let (activity, duplicated): (&Metadata, bool) = match diff_activity {
168                DiffActivity::None => panic!("not a valid input activity"),
169                DiffActivity::Const => (enzyme_const, false),
170                DiffActivity::Active => (enzyme_out, false),
171                DiffActivity::ActiveOnly => (enzyme_out, false),
172                DiffActivity::Dual => (enzyme_dup, true),
173                DiffActivity::DualOnly => (enzyme_dupnoneed, true),
174                DiffActivity::Duplicated => (enzyme_dup, true),
175                DiffActivity::DuplicatedOnly => (enzyme_dupnoneed, true),
176                DiffActivity::FakeActivitySize => (enzyme_const, false),
177            };
178            let outer_arg = outer_args[outer_pos];
179            args.push(cx.get_metadata_value(activity));
180            args.push(outer_arg);
181            if duplicated {
182                // We know that duplicated args by construction have a following argument,
183                // so this can not be out of bounds.
184                let next_outer_arg = outer_args[outer_pos + 1];
185                let next_outer_ty = cx.val_ty(next_outer_arg);
186                // FIXME(ZuseZ4): We should add support for Vec here too, but it's less urgent since
187                // vectors behind references (&Vec<T>) are already supported. Users can not pass a
188                // Vec by value for reverse mode, so this would only help forward mode autodiff.
189                let slice = {
190                    if activity_pos + 1 >= inputs.len() {
191                        // If there is no arg following our ptr, it also can't be a slice,
192                        // since that would lead to a ptr, int pair.
193                        false
194                    } else {
195                        let next_activity = inputs[activity_pos + 1];
196                        // We analyze the MIR types and add this dummy activity if we visit a slice.
197                        next_activity == DiffActivity::FakeActivitySize
198                    }
199                };
200                if slice {
201                    // A duplicated slice will have the following two outer_fn arguments:
202                    // (..., ptr1, int1, ptr2, int2, ...). We add the following llvm-ir to our __enzyme call:
203                    // (..., metadata! enzyme_dup, ptr, ptr, int1, ...).
204                    // FIXME(ZuseZ4): We will upstream a safety check later which asserts that
205                    // int2 >= int1, which means the shadow vector is large enough to store the gradient.
206                    assert!(llvm::LLVMRustGetTypeKind(next_outer_ty) == llvm::TypeKind::Integer);
207                    let next_outer_arg2 = outer_args[outer_pos + 2];
208                    let next_outer_ty2 = cx.val_ty(next_outer_arg2);
209                    assert!(llvm::LLVMRustGetTypeKind(next_outer_ty2) == llvm::TypeKind::Pointer);
210                    let next_outer_arg3 = outer_args[outer_pos + 3];
211                    let next_outer_ty3 = cx.val_ty(next_outer_arg3);
212                    assert!(llvm::LLVMRustGetTypeKind(next_outer_ty3) == llvm::TypeKind::Integer);
213                    args.push(next_outer_arg2);
214                    args.push(cx.get_metadata_value(enzyme_const));
215                    args.push(next_outer_arg);
216                    outer_pos += 4;
217                    activity_pos += 2;
218                } else {
219                    // A duplicated pointer will have the following two outer_fn arguments:
220                    // (..., ptr, ptr, ...). We add the following llvm-ir to our __enzyme call:
221                    // (..., metadata! enzyme_dup, ptr, ptr, ...).
222                    if matches!(
223                        diff_activity,
224                        DiffActivity::Duplicated | DiffActivity::DuplicatedOnly
225                    ) {
226                        assert!(
227                            llvm::LLVMRustGetTypeKind(next_outer_ty) == llvm::TypeKind::Pointer
228                        );
229                    }
230                    // In the case of Dual we don't have assumptions, e.g. f32 would be valid.
231                    args.push(next_outer_arg);
232                    outer_pos += 2;
233                    activity_pos += 1;
234                }
235            } else {
236                // We do not differentiate with resprect to this argument.
237                // We already added the metadata and argument above, so just increase the counters.
238                outer_pos += 1;
239                activity_pos += 1;
240            }
241        }
242
243        let call = builder.call(enzyme_ty, ad_fn, &args, None);
244
245        // This part is a bit iffy. LLVM requires that a call to an inlineable function has some
246        // metadata attachted to it, but we just created this code oota. Given that the
247        // differentiated function already has partly confusing metadata, and given that this
248        // affects nothing but the auttodiff IR, we take a shortcut and just steal metadata from the
249        // dummy code which we inserted at a higher level.
250        // FIXME(ZuseZ4): Work with Enzyme core devs to clarify what debug metadata issues we have,
251        // and how to best improve it for enzyme core and rust-enzyme.
252        let md_ty = cx.get_md_kind_id("dbg");
253        if llvm::LLVMRustHasMetadata(last_inst, md_ty) {
254            let md = llvm::LLVMRustDIGetInstMetadata(last_inst)
255                .expect("failed to get instruction metadata");
256            let md_todiff = cx.get_metadata_value(md);
257            llvm::LLVMSetMetadata(call, md_ty, md_todiff);
258        } else {
259            // We don't panic, since depending on whether we are in debug or release mode, we might
260            // have no debug info to copy, which would then be ok.
261            trace!("no dbg info");
262        }
263
264        // Now that we copied the metadata, get rid of dummy code.
265        llvm::LLVMRustEraseInstUntilInclusive(entry, last_inst);
266
267        if cx.val_ty(call) == cx.type_void() {
268            builder.ret_void();
269        } else {
270            builder.ret(call);
271        }
272
273        // Let's crash in case that we messed something up above and generated invalid IR.
274        llvm::LLVMRustVerifyFunction(
275            outer_fn,
276            llvm::LLVMRustVerifierFailureAction::LLVMAbortProcessAction,
277        );
278    }
279}
280
281pub(crate) fn differentiate<'ll>(
282    module: &'ll ModuleCodegen<ModuleLlvm>,
283    cgcx: &CodegenContext<LlvmCodegenBackend>,
284    diff_items: Vec<AutoDiffItem>,
285    _config: &ModuleConfig,
286) -> Result<(), FatalError> {
287    for item in &diff_items {
288        trace!("{}", item);
289    }
290
291    let diag_handler = cgcx.create_dcx();
292    let cx = SimpleCx { llmod: module.module_llvm.llmod(), llcx: module.module_llvm.llcx };
293
294    // Before dumping the module, we want all the TypeTrees to become part of the module.
295    for item in diff_items.iter() {
296        let name = item.source.clone();
297        let fn_def: Option<&llvm::Value> = cx.get_function(&name);
298        let Some(fn_def) = fn_def else {
299            return Err(llvm_err(
300                diag_handler.handle(),
301                LlvmError::PrepareAutoDiff {
302                    src: item.source.clone(),
303                    target: item.target.clone(),
304                    error: "could not find source function".to_owned(),
305                },
306            ));
307        };
308        debug!(?item.target);
309        let fn_target: Option<&llvm::Value> = cx.get_function(&item.target);
310        let Some(fn_target) = fn_target else {
311            return Err(llvm_err(
312                diag_handler.handle(),
313                LlvmError::PrepareAutoDiff {
314                    src: item.source.clone(),
315                    target: item.target.clone(),
316                    error: "could not find target function".to_owned(),
317                },
318            ));
319        };
320
321        generate_enzyme_call(&cx, fn_def, fn_target, item.attrs.clone());
322    }
323
324    // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
325
326    trace!("done with differentiate()");
327
328    Ok(())
329}