1 use gccjit::{Function, FunctionType, GlobalKind, LValue, RValue, Type};
2 use rustc_codegen_ssa::traits::BaseTypeMethods;
3 use rustc_middle::ty::Ty;
4 use rustc_span::Symbol;
5 use rustc_target::abi::call::FnAbi;
7 use crate::abi::FnAbiGccExt;
8 use crate::context::{CodegenCx, unit_name};
9 use crate::intrinsic::llvm;
10 use crate::mangled_std_symbols::{ARGV_INIT_ARRAY, ARGV_INIT_WRAPPER};
12 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
13 pub fn get_or_insert_global(&self, name: &str, ty: Type<'gcc>, is_tls: bool, link_section: Option<Symbol>) -> RValue<'gcc> {
14 if self.globals.borrow().contains_key(name) {
15 let typ = self.globals.borrow().get(name).expect("global").get_type();
16 let global = self.context.new_global(None, GlobalKind::Imported, typ, name);
18 global.set_tls_model(self.tls_model);
20 if let Some(link_section) = link_section {
21 global.set_link_section(&link_section.as_str());
23 global.get_address(None)
26 self.declare_global(name, ty, is_tls, link_section)
30 pub fn declare_unnamed_global(&self, ty: Type<'gcc>) -> LValue<'gcc> {
31 let index = self.global_gen_sym_counter.get();
32 self.global_gen_sym_counter.set(index + 1);
33 let name = format!("global_{}_{}", index, unit_name(&self.codegen_unit));
34 self.context.new_global(None, GlobalKind::Exported, ty, &name)
37 pub fn declare_global_with_linkage(&self, name: &str, ty: Type<'gcc>, linkage: GlobalKind) -> RValue<'gcc> {
38 //debug!("declare_global_with_linkage(name={:?})", name);
39 let global = self.context.new_global(None, linkage, ty, name)
41 self.globals.borrow_mut().insert(name.to_string(), global);
42 // NOTE: global seems to only be global in a module. So save the name instead of the value
43 // to import it later.
44 self.global_names.borrow_mut().insert(global, name.to_string());
48 pub fn declare_func(&self, name: &str, return_type: Type<'gcc>, params: &[Type<'gcc>], variadic: bool) -> RValue<'gcc> {
49 self.linkage.set(FunctionType::Exported);
50 let func = declare_raw_fn(self, name, () /*llvm::CCallConv*/, return_type, params, variadic);
51 // FIXME: this is a wrong cast. That requires changing the compiler API.
52 unsafe { std::mem::transmute(func) }
55 pub fn declare_global(&self, name: &str, ty: Type<'gcc>, is_tls: bool, link_section: Option<Symbol>) -> RValue<'gcc> {
56 //debug!("declare_global(name={:?})", name);
57 // FIXME: correctly support global variable initialization.
58 if name.starts_with(ARGV_INIT_ARRAY) {
59 // NOTE: hack to avoid having to update the names in mangled_std_symbols: we save the
60 // name of the variable now to actually declare it later.
61 *self.init_argv_var.borrow_mut() = name.to_string();
63 let global = self.context.new_global(None, GlobalKind::Imported, ty, name);
64 if let Some(link_section) = link_section {
65 global.set_link_section(&link_section.as_str());
67 return global.get_address(None);
69 let global = self.context.new_global(None, GlobalKind::Exported, ty, name);
71 global.set_tls_model(self.tls_model);
73 if let Some(link_section) = link_section {
74 global.set_link_section(&link_section.as_str());
76 let global = global.get_address(None);
77 self.globals.borrow_mut().insert(name.to_string(), global);
78 // NOTE: global seems to only be global in a module. So save the name instead of the value
79 // to import it later.
80 self.global_names.borrow_mut().insert(global, name.to_string());
84 pub fn declare_cfn(&self, name: &str, _fn_type: Type<'gcc>) -> RValue<'gcc> {
85 // TODO: use the fn_type parameter.
86 let const_string = self.context.new_type::<u8>().make_pointer().make_pointer();
87 let return_type = self.type_i32();
89 self.linkage.set(FunctionType::Exported);
90 let func = declare_raw_fn(self, name, () /*llvm::CCallConv*/, return_type, &[self.type_i32(), const_string], variadic);
91 // NOTE: it is needed to set the current_func here as well, because get_fn() is not called
92 // for the main function.
93 *self.current_func.borrow_mut() = Some(func);
94 // FIXME: this is a wrong cast. That requires changing the compiler API.
95 unsafe { std::mem::transmute(func) }
98 pub fn declare_fn(&self, name: &str, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> RValue<'gcc> {
99 // NOTE: hack to avoid having to update the names in mangled_std_symbols: we found the name
100 // of the variable earlier, so we declare it now.
101 // Since we don't correctly support initializers yet, we initialize this variable manually
103 if name.starts_with(ARGV_INIT_WRAPPER) && !self.argv_initialized.get() {
104 let global_name = &*self.init_argv_var.borrow();
105 let return_type = self.type_void();
107 self.context.new_parameter(None, self.int_type, "argc"),
108 self.context.new_parameter(None, self.u8_type.make_pointer().make_pointer(), "argv"),
109 self.context.new_parameter(None, self.u8_type.make_pointer().make_pointer(), "envp"),
111 let function = self.context.new_function(None, FunctionType::Extern, return_type, ¶ms, name, false);
112 let initializer = function.get_address(None);
116 self.u8_type.make_pointer().make_pointer(),
117 self.u8_type.make_pointer().make_pointer(),
119 let ty = self.context.new_function_pointer_type(None, return_type, ¶m_types, false);
121 let global = self.context.new_global(None, GlobalKind::Exported, ty, global_name);
122 global.set_link_section(".init_array.00099");
123 global.global_set_initializer_value(initializer);
124 let global = global.get_address(None);
125 self.globals.borrow_mut().insert(global_name.to_string(), global);
126 // NOTE: global seems to only be global in a module. So save the name instead of the value
127 // to import it later.
128 self.global_names.borrow_mut().insert(global, global_name.to_string());
129 self.argv_initialized.set(true);
131 //debug!("declare_rust_fn(name={:?}, fn_abi={:?})", name, fn_abi);
132 let (return_type, params, variadic) = fn_abi.gcc_type(self);
133 let func = declare_raw_fn(self, name, () /*fn_abi.llvm_cconv()*/, return_type, ¶ms, variadic);
134 //fn_abi.apply_attrs_llfn(self, func);
135 // FIXME: this is a wrong cast. That requires changing the compiler API.
136 unsafe { std::mem::transmute(func) }
139 pub fn define_global(&self, name: &str, ty: Type<'gcc>, is_tls: bool, link_section: Option<Symbol>) -> Option<RValue<'gcc>> {
140 Some(self.get_or_insert_global(name, ty, is_tls, link_section))
143 pub fn define_private_global(&self, ty: Type<'gcc>) -> RValue<'gcc> {
144 let global = self.declare_unnamed_global(ty);
145 global.get_address(None)
148 pub fn get_declared_value(&self, name: &str) -> Option<RValue<'gcc>> {
149 //debug!("get_declared_value(name={:?})", name);
150 // TODO: use a different field than globals, because this seems to return a function?
151 self.globals.borrow().get(name).cloned()
154 /*fn get_defined_value(&self, name: &str) -> Option<RValue<'gcc>> {
155 // TODO: gcc does not allow global initialization.
157 /*self.get_declared_value(name).and_then(|val| {
158 let declaration = unsafe { llvm::LLVMIsDeclaration(val) != 0 };
159 if !declaration { Some(val) } else { None }
164 /// Declare a function.
166 /// If there’s a value with the same name already declared, the function will
167 /// update the declaration and return existing Value instead.
168 fn declare_raw_fn<'gcc>(cx: &CodegenCx<'gcc, '_>, name: &str, _callconv: () /*llvm::CallConv*/, return_type: Type<'gcc>, param_types: &[Type<'gcc>], variadic: bool) -> Function<'gcc> {
169 //debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
170 /*let llfn = unsafe {
171 llvm::LLVMRustGetOrInsertFunction(cx.llmod, name.as_ptr().cast(), name.len(), ty)
174 if name.starts_with("llvm.") {
175 return llvm::intrinsic(name, cx);
178 if cx.functions.borrow().contains_key(name) {
179 *cx.functions.borrow().get(name).expect("function")
182 let params: Vec<_> = param_types.into_iter().enumerate()
183 .map(|(index, param)| cx.context.new_parameter(None, *param, &format!("param{}", index))) // TODO: set name.
185 let func = cx.context.new_function(None, cx.linkage.get(), return_type, ¶ms, mangle_name(name), variadic);
186 cx.functions.borrow_mut().insert(name.to_string(), func);
190 //llvm::SetFunctionCallConv(llfn, callconv); // TODO
191 // Function addresses in Rust are never significant, allowing functions to
193 //llvm::SetUnnamedAddress(llfn, llvm::UnnamedAddr::Global); // TODO
195 /*if cx.tcx.sess.opts.cg.no_redzone.unwrap_or(cx.tcx.sess.target.target.options.disable_redzone) {
196 llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
199 //attributes::default_optimisation_attrs(cx.tcx.sess, llfn);
200 //attributes::non_lazy_bind(cx.sess(), llfn);
202 // FIXME: invalid cast.
203 // TODO: is this line useful?
204 //cx.globals.borrow_mut().insert(name.to_string(), unsafe { std::mem::transmute(func) });
208 // FIXME: this is a hack because libgccjit currently only supports alpha, num and _.
209 // Unsupported characters: `$` and `.`.
210 pub fn mangle_name(name: &str) -> String {
211 name.replace(|char: char| {
212 if !char.is_alphanumeric() && char != '_' {
213 debug_assert!("$.".contains(char), "Unsupported char in function name: {}", char);