1 use gccjit::{FunctionType, RValue};
2 use rustc_codegen_ssa::traits::BaseTypeMethods;
3 use rustc_middle::ty::{Instance, TypeFoldable};
4 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
5 use rustc_target::abi::call::FnAbi;
7 use crate::abi::FnAbiGccExt;
8 use crate::context::CodegenCx;
10 /// Codegens a reference to a fn/method item, monomorphizing and
11 /// inlining as it goes.
15 /// - `cx`: the crate context
16 /// - `instance`: the instance to be instantiated
17 pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) -> RValue<'gcc> {
20 assert!(!instance.substs.needs_infer());
21 assert!(!instance.substs.has_escaping_bound_vars());
22 assert!(!instance.substs.has_param_types_or_consts());
24 if let Some(&func) = cx.instances.borrow().get(&instance) {
28 let sym = tcx.symbol_name(instance).name;
30 let fn_abi = FnAbi::of_instance(cx, instance, &[]);
33 if let Some(func) = cx.get_declared_value(&sym) {
34 // Create a fn pointer with the new signature.
35 let ptrty = fn_abi.ptr_to_gcc_type(cx);
37 // This is subtle and surprising, but sometimes we have to bitcast
38 // the resulting fn pointer. The reason has to do with external
39 // functions. If you have two crates that both bind the same C
40 // library, they may not use precisely the same types: for
41 // example, they will probably each declare their own structs,
42 // which are distinct types from LLVM's point of view (nominal
45 // Now, if those two crates are linked into an application, and
46 // they contain inlined code, you can wind up with a situation
47 // where both of those functions wind up being loaded into this
48 // application simultaneously. In that case, the same function
49 // (from LLVM's point of view) requires two types. But of course
50 // LLVM won't allow one function to have two types.
52 // What we currently do, therefore, is declare the function with
53 // one of the two types (whichever happens to come first) and then
54 // bitcast as needed when the function is referenced to make sure
55 // it has the type we expect.
57 // This can occur on either a crate-local or crate-external
58 // reference. It also occurs when testing libcore and in some
59 // other weird situations. Annoying.
60 if cx.val_ty(func) != ptrty {
61 // TODO(antoyo): cast the pointer.
69 cx.linkage.set(FunctionType::Extern);
70 let func = cx.declare_fn(&sym, &fn_abi);
72 // TODO(antoyo): set linkage and attributes.
76 cx.instances.borrow_mut().insert(instance, func);