]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_gcc/src/consts.rs
Rollup merge of #104148 - fmease:fix-104140, r=petrochenkov
[rust.git] / compiler / rustc_codegen_gcc / src / consts.rs
1 use gccjit::{GlobalKind, LValue, RValue, ToRValue, Type};
2 use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods, DerivedTypeMethods, StaticMethods};
3 use rustc_hir as hir;
4 use rustc_hir::Node;
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::Span;
12 use rustc_span::def_id::DefId;
13 use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange};
14
15 use crate::base;
16 use crate::context::CodegenCx;
17 use crate::errors::LinkageConstOrMutType;
18 use crate::type_of::LayoutGccExt;
19
20 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
21     pub fn const_bitcast(&self, value: RValue<'gcc>, typ: Type<'gcc>) -> RValue<'gcc> {
22         if value.get_type() == self.bool_type.make_pointer() {
23             if let Some(pointee) = typ.get_pointee() {
24                 if pointee.dyncast_vector().is_some() {
25                     panic!()
26                 }
27             }
28         }
29         // NOTE: since bitcast makes a value non-constant, don't bitcast if not necessary as some
30         // SIMD builtins require a constant value.
31         self.bitcast_if_needed(value, typ)
32     }
33 }
34
35 impl<'gcc, 'tcx> StaticMethods for CodegenCx<'gcc, 'tcx> {
36     fn static_addr_of(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
37         // TODO(antoyo): implement a proper rvalue comparison in libgccjit instead of doing the
38         // following:
39         for (value, variable) in &*self.const_globals.borrow() {
40             if format!("{:?}", value) == format!("{:?}", cv) {
41                 if let Some(global_variable) = self.global_lvalues.borrow().get(variable) {
42                     let alignment = align.bits() as i32;
43                     if alignment > global_variable.get_alignment() {
44                         global_variable.set_alignment(alignment);
45                     }
46                 }
47                 return *variable;
48             }
49         }
50         let global_value = self.static_addr_of_mut(cv, align, kind);
51         #[cfg(feature = "master")]
52         self.global_lvalues.borrow().get(&global_value)
53             .expect("`static_addr_of_mut` did not add the global to `self.global_lvalues`")
54             .global_set_readonly();
55         self.const_globals.borrow_mut().insert(cv, global_value);
56         global_value
57     }
58
59     fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
60         let attrs = self.tcx.codegen_fn_attrs(def_id);
61
62         let value =
63             match codegen_static_initializer(&self, def_id) {
64                 Ok((value, _)) => value,
65                 // Error has already been reported
66                 Err(_) => return,
67             };
68
69         let global = self.get_static(def_id);
70
71         // boolean SSA values are i1, but they have to be stored in i8 slots,
72         // otherwise some LLVM optimization passes don't work as expected
73         let val_llty = self.val_ty(value);
74         let value =
75             if val_llty == self.type_i1() {
76                 unimplemented!();
77             }
78             else {
79                 value
80             };
81
82         let instance = Instance::mono(self.tcx, def_id);
83         let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
84         let gcc_type = self.layout_of(ty).gcc_type(self, true);
85
86         // TODO(antoyo): set alignment.
87
88         let value = self.bitcast_if_needed(value, gcc_type);
89         global.global_set_initializer_rvalue(value);
90
91         // As an optimization, all shared statics which do not have interior
92         // mutability are placed into read-only memory.
93         if !is_mutable {
94             if self.type_is_freeze(ty) {
95                 #[cfg(feature = "master")]
96                 global.global_set_readonly();
97             }
98         }
99
100         if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
101             // Do not allow LLVM to change the alignment of a TLS on macOS.
102             //
103             // By default a global's alignment can be freely increased.
104             // This allows LLVM to generate more performant instructions
105             // e.g., using load-aligned into a SIMD register.
106             //
107             // However, on macOS 10.10 or below, the dynamic linker does not
108             // respect any alignment given on the TLS (radar 24221680).
109             // This will violate the alignment assumption, and causing segfault at runtime.
110             //
111             // This bug is very easy to trigger. In `println!` and `panic!`,
112             // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
113             // which the values would be `mem::replace`d on initialization.
114             // The implementation of `mem::replace` will use SIMD
115             // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
116             // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
117             // which macOS's dyld disregarded and causing crashes
118             // (see issues #51794, #51758, #50867, #48866 and #44056).
119             //
120             // To workaround the bug, we trick LLVM into not increasing
121             // the global's alignment by explicitly assigning a section to it
122             // (equivalent to automatically generating a `#[link_section]` attribute).
123             // See the comment in the `GlobalValue::canIncreaseAlignment()` function
124             // of `lib/IR/Globals.cpp` for why this works.
125             //
126             // When the alignment is not increased, the optimized `mem::replace`
127             // will use load-unaligned instructions instead, and thus avoiding the crash.
128             //
129             // We could remove this hack whenever we decide to drop macOS 10.10 support.
130             if self.tcx.sess.target.options.is_like_osx {
131                 // The `inspect` method is okay here because we checked for provenance, and
132                 // because we are doing this access to inspect the final interpreter state
133                 // (not as part of the interpreter execution).
134                 //
135                 // FIXME: This check requires that the (arbitrary) value of undefined bytes
136                 // happens to be zero. Instead, we should only check the value of defined bytes
137                 // and set all undefined bytes to zero if this allocation is headed for the
138                 // BSS.
139                 unimplemented!();
140             }
141         }
142
143         // Wasm statics with custom link sections get special treatment as they
144         // go into custom sections of the wasm executable.
145         if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
146             if let Some(_section) = attrs.link_section {
147                 unimplemented!();
148             }
149         } else {
150             // TODO(antoyo): set link section.
151         }
152
153         if attrs.flags.contains(CodegenFnAttrFlags::USED) || attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
154             self.add_used_global(global.to_rvalue());
155         }
156     }
157
158     /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*.
159     fn add_used_global(&self, _global: RValue<'gcc>) {
160         // TODO(antoyo)
161     }
162
163     fn add_compiler_used_global(&self, _global: RValue<'gcc>) {
164         // TODO(antoyo)
165     }
166 }
167
168 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
169     pub fn static_addr_of_mut(&self, cv: RValue<'gcc>, align: Align, kind: Option<&str>) -> RValue<'gcc> {
170         let global =
171             match kind {
172                 Some(kind) if !self.tcx.sess.fewer_names() => {
173                     let name = self.generate_local_symbol_name(kind);
174                     // TODO(antoyo): check if it's okay that no link_section is set.
175
176                     let typ = self.val_ty(cv).get_aligned(align.bytes());
177                     let global = self.declare_private_global(&name[..], typ);
178                     global
179                 }
180                 _ => {
181                     let typ = self.val_ty(cv).get_aligned(align.bytes());
182                     let global = self.declare_unnamed_global(typ);
183                     global
184                 },
185             };
186         global.global_set_initializer_rvalue(cv);
187         // TODO(antoyo): set unnamed address.
188         let rvalue = global.get_address(None);
189         self.global_lvalues.borrow_mut().insert(rvalue, global);
190         rvalue
191     }
192
193     pub fn get_static(&self, def_id: DefId) -> LValue<'gcc> {
194         let instance = Instance::mono(self.tcx, def_id);
195         let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
196         if let Some(&global) = self.instances.borrow().get(&instance) {
197             return global;
198         }
199
200         let defined_in_current_codegen_unit =
201             self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
202         assert!(
203             !defined_in_current_codegen_unit,
204             "consts::get_static() should always hit the cache for \
205                  statics defined in the same CGU, but did not for `{:?}`",
206             def_id
207         );
208
209         let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
210         let sym = self.tcx.symbol_name(instance).name;
211
212         let global =
213             if let Some(def_id) = def_id.as_local() {
214                 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
215                 let llty = self.layout_of(ty).gcc_type(self, true);
216                 // FIXME: refactor this to work without accessing the HIR
217                 let global = match self.tcx.hir().get(id) {
218                     Node::Item(&hir::Item { span, kind: hir::ItemKind::Static(..), .. }) => {
219                         if let Some(global) = self.get_declared_value(&sym) {
220                             if self.val_ty(global) != self.type_ptr_to(llty) {
221                                 span_bug!(span, "Conflicting types for static");
222                             }
223                         }
224
225                         let is_tls = fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
226                         let global = self.declare_global(
227                             &sym,
228                             llty,
229                             GlobalKind::Exported,
230                             is_tls,
231                             fn_attrs.link_section,
232                         );
233
234                         if !self.tcx.is_reachable_non_generic(def_id) {
235                             // TODO(antoyo): set visibility.
236                         }
237
238                         global
239                     }
240
241                     Node::ForeignItem(&hir::ForeignItem {
242                         span,
243                         kind: hir::ForeignItemKind::Static(..),
244                         ..
245                     }) => {
246                         let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
247                         check_and_apply_linkage(&self, &fn_attrs, ty, sym, span)
248                     }
249
250                     item => bug!("get_static: expected static, found {:?}", item),
251                 };
252
253                 global
254             }
255             else {
256                 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
257                 //debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
258
259                 let attrs = self.tcx.codegen_fn_attrs(def_id);
260                 let span = self.tcx.def_span(def_id);
261                 let global = check_and_apply_linkage(&self, &attrs, ty, sym, span);
262
263                 let needs_dll_storage_attr = false; // TODO(antoyo)
264
265                 // If this assertion triggers, there's something wrong with commandline
266                 // argument validation.
267                 debug_assert!(
268                     !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
269                         && self.tcx.sess.target.options.is_like_msvc
270                         && self.tcx.sess.opts.cg.prefer_dynamic)
271                 );
272
273                 if needs_dll_storage_attr {
274                     // This item is external but not foreign, i.e., it originates from an external Rust
275                     // crate. Since we don't know whether this crate will be linked dynamically or
276                     // statically in the final application, we always mark such symbols as 'dllimport'.
277                     // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
278                     // to make things work.
279                     //
280                     // However, in some scenarios we defer emission of statics to downstream
281                     // crates, so there are cases where a static with an upstream DefId
282                     // is actually present in the current crate. We can find out via the
283                     // is_codegened_item query.
284                     if !self.tcx.is_codegened_item(def_id) {
285                         unimplemented!();
286                     }
287                 }
288                 global
289             };
290
291         // TODO(antoyo): set dll storage class.
292
293         self.instances.borrow_mut().insert(instance, global);
294         global
295     }
296 }
297
298 pub fn const_alloc_to_gcc<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, alloc: ConstAllocation<'tcx>) -> RValue<'gcc> {
299     let alloc = alloc.inner();
300     let mut llvals = Vec::with_capacity(alloc.provenance().len() + 1);
301     let dl = cx.data_layout();
302     let pointer_size = dl.pointer_size.bytes() as usize;
303
304     let mut next_offset = 0;
305     for &(offset, alloc_id) in alloc.provenance().iter() {
306         let offset = offset.bytes();
307         assert_eq!(offset as usize as u64, offset);
308         let offset = offset as usize;
309         if offset > next_offset {
310             // This `inspect` is okay since we have checked that it is not within a pointer with provenance, it
311             // is within the bounds of the allocation, and it doesn't affect interpreter execution
312             // (we inspect the result after interpreter execution). Any undef byte is replaced with
313             // some arbitrary byte value.
314             //
315             // FIXME: relay undef bytes to codegen as undef const bytes
316             let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(next_offset..offset);
317             llvals.push(cx.const_bytes(bytes));
318         }
319         let ptr_offset =
320             read_target_uint( dl.endian,
321                 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
322                 // affect interpreter execution (we inspect the result after interpreter execution),
323                 // and we properly interpret the provenance as a relocation pointer offset.
324                 alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
325             )
326             .expect("const_alloc_to_llvm: could not read relocation pointer")
327             as u64;
328         llvals.push(cx.scalar_to_backend(
329             InterpScalar::from_pointer(
330                 interpret::Pointer::new(alloc_id, Size::from_bytes(ptr_offset)),
331                 &cx.tcx,
332             ),
333             abi::Scalar::Initialized { value: Primitive::Pointer, valid_range: WrappingRange::full(dl.pointer_size) },
334             cx.type_i8p(),
335         ));
336         next_offset = offset + pointer_size;
337     }
338     if alloc.len() >= next_offset {
339         let range = next_offset..alloc.len();
340         // This `inspect` is okay since we have check that it is after all provenance, it is
341         // within the bounds of the allocation, and it doesn't affect interpreter execution (we
342         // inspect the result after interpreter execution). Any undef byte is replaced with some
343         // arbitrary byte value.
344         //
345         // FIXME: relay undef bytes to codegen as undef const bytes
346         let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
347         llvals.push(cx.const_bytes(bytes));
348     }
349
350     cx.const_struct(&llvals, true)
351 }
352
353 pub fn codegen_static_initializer<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, def_id: DefId) -> Result<(RValue<'gcc>, ConstAllocation<'tcx>), ErrorHandled> {
354     let alloc = cx.tcx.eval_static_initializer(def_id)?;
355     Ok((const_alloc_to_gcc(cx, alloc), alloc))
356 }
357
358 fn check_and_apply_linkage<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: &str, span: Span) -> LValue<'gcc> {
359     let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
360     let llty = cx.layout_of(ty).gcc_type(cx, true);
361     if let Some(linkage) = attrs.linkage {
362         // If this is a static with a linkage specified, then we need to handle
363         // it a little specially. The typesystem prevents things like &T and
364         // extern "C" fn() from being non-null, so we can't just declare a
365         // static and call it a day. Some linkages (like weak) will make it such
366         // that the static actually has a null value.
367         let llty2 =
368             if let ty::RawPtr(ref mt) = ty.kind() {
369                 cx.layout_of(mt.ty).gcc_type(cx, true)
370             }
371             else {
372                 cx.sess().emit_fatal(LinkageConstOrMutType { span: span })
373             };
374         // Declare a symbol `foo` with the desired linkage.
375         let global1 = cx.declare_global_with_linkage(&sym, llty2, base::global_linkage_to_gcc(linkage));
376
377         // Declare an internal global `extern_with_linkage_foo` which
378         // is initialized with the address of `foo`.  If `foo` is
379         // discarded during linking (for example, if `foo` has weak
380         // linkage and there are no definitions), then
381         // `extern_with_linkage_foo` will instead be initialized to
382         // zero.
383         let mut real_name = "_rust_extern_with_linkage_".to_string();
384         real_name.push_str(&sym);
385         let global2 = cx.define_global(&real_name, llty, is_tls, attrs.link_section);
386         // TODO(antoyo): set linkage.
387         global2.global_set_initializer_rvalue(global1.get_address(None));
388         // TODO(antoyo): use global_set_initializer() when it will work.
389         global2
390     }
391     else {
392         // Generate an external declaration.
393         // FIXME(nagisa): investigate whether it can be changed into define_global
394
395         // Thread-local statics in some other crate need to *always* be linked
396         // against in a thread-local fashion, so we need to be sure to apply the
397         // thread-local attribute locally if it was present remotely. If we
398         // don't do this then linker errors can be generated where the linker
399         // complains that one object files has a thread local version of the
400         // symbol and another one doesn't.
401         cx.declare_global(&sym, llty, GlobalKind::Imported, is_tls, attrs.link_section)
402     }
403 }