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