1 use gccjit::{GlobalKind, LValue, RValue, ToRValue, Type};
2 use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods, DerivedTypeMethods, StaticMethods};
5 use rustc_middle::{bug, span_bug};
6 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
7 use rustc_middle::mir::mono::MonoItem;
8 use rustc_middle::ty::{self, Instance, Ty};
9 use rustc_middle::ty::layout::LayoutOf;
10 use rustc_middle::mir::interpret::{self, ConstAllocation, ErrorHandled, Scalar as InterpScalar, read_target_uint};
11 use rustc_span::def_id::DefId;
12 use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange};
15 use crate::context::CodegenCx;
16 use crate::type_of::LayoutGccExt;
18 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
19 pub fn const_bitcast(&self, value: RValue<'gcc>, typ: Type<'gcc>) -> RValue<'gcc> {
20 if value.get_type() == self.bool_type.make_pointer() {
21 if let Some(pointee) = typ.get_pointee() {
22 if pointee.dyncast_vector().is_some() {
27 // NOTE: since bitcast makes a value non-constant, don't bitcast if not necessary as some
28 // SIMD builtins require a constant value.
29 self.bitcast_if_needed(value, typ)
33 impl<'gcc, 'tcx> StaticMethods for CodegenCx<'gcc, 'tcx> {
34 fn static_addr_of(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
35 // TODO(antoyo): implement a proper rvalue comparison in libgccjit instead of doing the
37 for (value, variable) in &*self.const_globals.borrow() {
38 if format!("{:?}", value) == format!("{:?}", cv) {
39 if let Some(global_variable) = self.global_lvalues.borrow().get(variable) {
40 let alignment = align.bits() as i32;
41 if alignment > global_variable.get_alignment() {
42 global_variable.set_alignment(alignment);
48 let global_value = self.static_addr_of_mut(cv, align, kind);
49 #[cfg(feature = "master")]
50 self.global_lvalues.borrow().get(&global_value)
51 .expect("`static_addr_of_mut` did not add the global to `self.global_lvalues`")
52 .global_set_readonly();
53 self.const_globals.borrow_mut().insert(cv, global_value);
57 fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
58 let attrs = self.tcx.codegen_fn_attrs(def_id);
61 match codegen_static_initializer(&self, def_id) {
62 Ok((value, _)) => value,
63 // Error has already been reported
67 let global = self.get_static(def_id);
69 // boolean SSA values are i1, but they have to be stored in i8 slots,
70 // otherwise some LLVM optimization passes don't work as expected
71 let val_llty = self.val_ty(value);
73 if val_llty == self.type_i1() {
80 let instance = Instance::mono(self.tcx, def_id);
81 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
82 let gcc_type = self.layout_of(ty).gcc_type(self, true);
84 // TODO(antoyo): set alignment.
86 let value = self.bitcast_if_needed(value, gcc_type);
87 global.global_set_initializer_rvalue(value);
89 // As an optimization, all shared statics which do not have interior
90 // mutability are placed into read-only memory.
92 if self.type_is_freeze(ty) {
93 #[cfg(feature = "master")]
94 global.global_set_readonly();
98 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
99 // Do not allow LLVM to change the alignment of a TLS on macOS.
101 // By default a global's alignment can be freely increased.
102 // This allows LLVM to generate more performant instructions
103 // e.g., using load-aligned into a SIMD register.
105 // However, on macOS 10.10 or below, the dynamic linker does not
106 // respect any alignment given on the TLS (radar 24221680).
107 // This will violate the alignment assumption, and causing segfault at runtime.
109 // This bug is very easy to trigger. In `println!` and `panic!`,
110 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
111 // which the values would be `mem::replace`d on initialization.
112 // The implementation of `mem::replace` will use SIMD
113 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
114 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
115 // which macOS's dyld disregarded and causing crashes
116 // (see issues #51794, #51758, #50867, #48866 and #44056).
118 // To workaround the bug, we trick LLVM into not increasing
119 // the global's alignment by explicitly assigning a section to it
120 // (equivalent to automatically generating a `#[link_section]` attribute).
121 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
122 // of `lib/IR/Globals.cpp` for why this works.
124 // When the alignment is not increased, the optimized `mem::replace`
125 // will use load-unaligned instructions instead, and thus avoiding the crash.
127 // We could remove this hack whenever we decide to drop macOS 10.10 support.
128 if self.tcx.sess.target.options.is_like_osx {
129 // The `inspect` method is okay here because we checked for provenance, and
130 // because we are doing this access to inspect the final interpreter state
131 // (not as part of the interpreter execution).
133 // FIXME: This check requires that the (arbitrary) value of undefined bytes
134 // happens to be zero. Instead, we should only check the value of defined bytes
135 // and set all undefined bytes to zero if this allocation is headed for the
141 // Wasm statics with custom link sections get special treatment as they
142 // go into custom sections of the wasm executable.
143 if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
144 if let Some(_section) = attrs.link_section {
148 // TODO(antoyo): set link section.
151 if attrs.flags.contains(CodegenFnAttrFlags::USED) || attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
152 self.add_used_global(global.to_rvalue());
156 /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*.
157 fn add_used_global(&self, _global: RValue<'gcc>) {
161 fn add_compiler_used_global(&self, _global: RValue<'gcc>) {
166 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
167 pub fn static_addr_of_mut(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
170 Some(kind) if !self.tcx.sess.fewer_names() => {
171 let name = self.generate_local_symbol_name(kind);
172 // TODO(antoyo): check if it's okay that no link_section is set.
174 let typ = self.val_ty(cv).get_aligned(align.bytes());
175 let global = self.declare_private_global(&name[..], typ);
179 let typ = self.val_ty(cv).get_aligned(align.bytes());
180 let global = self.declare_unnamed_global(typ);
184 global.global_set_initializer_rvalue(cv);
185 // TODO(antoyo): set unnamed address.
186 let rvalue = global.get_address(None);
187 self.global_lvalues.borrow_mut().insert(rvalue, global);
191 pub fn get_static(&self, def_id: DefId) -> LValue<'gcc> {
192 let instance = Instance::mono(self.tcx, def_id);
193 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
194 if let Some(&global) = self.instances.borrow().get(&instance) {
198 let defined_in_current_codegen_unit =
199 self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
201 !defined_in_current_codegen_unit,
202 "consts::get_static() should always hit the cache for \
203 statics defined in the same CGU, but did not for `{:?}`",
207 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
208 let sym = self.tcx.symbol_name(instance).name;
211 if let Some(def_id) = def_id.as_local() {
212 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
213 let llty = self.layout_of(ty).gcc_type(self, true);
214 // FIXME: refactor this to work without accessing the HIR
215 let global = match self.tcx.hir().get(id) {
216 Node::Item(&hir::Item { span, kind: hir::ItemKind::Static(..), .. }) => {
217 if let Some(global) = self.get_declared_value(&sym) {
218 if self.val_ty(global) != self.type_ptr_to(llty) {
219 span_bug!(span, "Conflicting types for static");
223 let is_tls = fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
224 let global = self.declare_global(
227 GlobalKind::Exported,
229 fn_attrs.link_section,
232 if !self.tcx.is_reachable_non_generic(def_id) {
233 // TODO(antoyo): set visibility.
239 Node::ForeignItem(&hir::ForeignItem {
241 kind: hir::ForeignItemKind::Static(..),
244 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
245 check_and_apply_linkage(&self, &fn_attrs, ty, sym)
248 item => bug!("get_static: expected static, found {:?}", item),
254 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
255 //debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
257 let attrs = self.tcx.codegen_fn_attrs(def_id);
258 let global = check_and_apply_linkage(&self, &attrs, ty, sym);
260 let needs_dll_storage_attr = false; // TODO(antoyo)
262 // If this assertion triggers, there's something wrong with commandline
263 // argument validation.
265 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
266 && self.tcx.sess.target.options.is_like_msvc
267 && self.tcx.sess.opts.cg.prefer_dynamic)
270 if needs_dll_storage_attr {
271 // This item is external but not foreign, i.e., it originates from an external Rust
272 // crate. Since we don't know whether this crate will be linked dynamically or
273 // statically in the final application, we always mark such symbols as 'dllimport'.
274 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
275 // to make things work.
277 // However, in some scenarios we defer emission of statics to downstream
278 // crates, so there are cases where a static with an upstream DefId
279 // is actually present in the current crate. We can find out via the
280 // is_codegened_item query.
281 if !self.tcx.is_codegened_item(def_id) {
288 // TODO(antoyo): set dll storage class.
290 self.instances.borrow_mut().insert(instance, global);
295 pub fn const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAllocation<'tcx>) -> RValue<'gcc> {
296 let alloc = alloc.inner();
297 let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
298 let dl = cx.data_layout();
299 let pointer_size = dl.pointer_size.bytes() as usize;
301 let mut next_offset = 0;
302 for &(offset, alloc_id) in alloc.provenance().ptrs().iter() {
303 let offset = offset.bytes();
304 assert_eq!(offset as usize as u64, offset);
305 let offset = offset as usize;
306 if offset > next_offset {
307 // This `inspect` is okay since we have checked that it is not within a pointer with provenance, it
308 // is within the bounds of the allocation, and it doesn't affect interpreter execution
309 // (we inspect the result after interpreter execution). Any undef byte is replaced with
310 // some arbitrary byte value.
312 // FIXME: relay undef bytes to codegen as undef const bytes
313 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(next_offset..offset);
314 llvals.push(cx.const_bytes(bytes));
317 read_target_uint( dl.endian,
318 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
319 // affect interpreter execution (we inspect the result after interpreter execution),
320 // and we properly interpret the provenance as a relocation pointer offset.
321 alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
323 .expect("const_alloc_to_llvm: could not read relocation pointer")
325 llvals.push(cx.scalar_to_backend(
326 InterpScalar::from_pointer(
327 interpret::Pointer::new(alloc_id, Size::from_bytes(ptr_offset)),
330 abi::Scalar::Initialized { value: Primitive::Pointer, valid_range: WrappingRange::full(dl.pointer_size) },
333 next_offset = offset + pointer_size;
335 if alloc.len() >= next_offset {
336 let range = next_offset..alloc.len();
337 // This `inspect` is okay since we have check that it is after all provenance, it is
338 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
339 // inspect the result after interpreter execution). Any undef byte is replaced with some
340 // arbitrary byte value.
342 // FIXME: relay undef bytes to codegen as undef const bytes
343 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
344 llvals.push(cx.const_bytes(bytes));
347 cx.const_struct(&llvals, true)
350 pub fn codegen_static_initializer<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, def_id: DefId) -> Result<(RValue<'gcc>, ConstAllocation<'tcx>), ErrorHandled> {
351 let alloc = cx.tcx.eval_static_initializer(def_id)?;
352 Ok((const_alloc_to_gcc(cx, alloc), alloc))
355 fn check_and_apply_linkage<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: &str) -> LValue<'gcc> {
356 let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
357 let llty = cx.layout_of(ty).gcc_type(cx, true);
358 if let Some(linkage) = attrs.import_linkage {
359 // Declare a symbol `foo` with the desired linkage.
360 let global1 = cx.declare_global_with_linkage(&sym, cx.type_i8(), base::global_linkage_to_gcc(linkage));
362 // Declare an internal global `extern_with_linkage_foo` which
363 // is initialized with the address of `foo`. If `foo` is
364 // discarded during linking (for example, if `foo` has weak
365 // linkage and there are no definitions), then
366 // `extern_with_linkage_foo` will instead be initialized to
368 let mut real_name = "_rust_extern_with_linkage_".to_string();
369 real_name.push_str(&sym);
370 let global2 = cx.define_global(&real_name, llty, is_tls, attrs.link_section);
371 // TODO(antoyo): set linkage.
372 global2.global_set_initializer_rvalue(global1.get_address(None));
373 // TODO(antoyo): use global_set_initializer() when it will work.
377 // Generate an external declaration.
378 // FIXME(nagisa): investigate whether it can be changed into define_global
380 // Thread-local statics in some other crate need to *always* be linked
381 // against in a thread-local fashion, so we need to be sure to apply the
382 // thread-local attribute locally if it was present remotely. If we
383 // don't do this then linker errors can be generated where the linker
384 // complains that one object files has a thread local version of the
385 // symbol and another one doesn't.
386 cx.declare_global(&sym, llty, GlobalKind::Imported, is_tls, attrs.link_section)