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