]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/consts.rs
Rollup merge of #67955 - ollie27:rustdoc_cfg_dupes, r=GuillaumeGomez
[rust.git] / src / librustc_codegen_llvm / consts.rs
1 use crate::base;
2 use crate::common::CodegenCx;
3 use crate::debuginfo;
4 use crate::llvm::{self, SetUnnamedAddr, True};
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
8 use libc::c_uint;
9 use log::debug;
10 use rustc::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
11 use rustc::mir::interpret::{read_target_uint, Allocation, ConstValue, ErrorHandled, Pointer};
12 use rustc::mir::mono::MonoItem;
13 use rustc::ty::layout::{self, Align, LayoutOf, Size};
14 use rustc::ty::{self, Instance, Ty};
15 use rustc::{bug, span_bug};
16 use rustc_codegen_ssa::traits::*;
17 use rustc_hir as hir;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::Node;
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_span::Span;
22 use rustc_target::abi::HasDataLayout;
23
24 use std::ffi::CStr;
25
26 pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll Value {
27     let mut llvals = Vec::with_capacity(alloc.relocations().len() + 1);
28     let dl = cx.data_layout();
29     let pointer_size = dl.pointer_size.bytes() as usize;
30
31     let mut next_offset = 0;
32     for &(offset, ((), alloc_id)) in alloc.relocations().iter() {
33         let offset = offset.bytes();
34         assert_eq!(offset as usize as u64, offset);
35         let offset = offset as usize;
36         if offset > next_offset {
37             // This `inspect` is okay since we have checked that it is not within a relocation, it
38             // is within the bounds of the allocation, and it doesn't affect interpreter execution
39             // (we inspect the result after interpreter execution). Any undef byte is replaced with
40             // some arbitrary byte value.
41             //
42             // FIXME: relay undef bytes to codegen as undef const bytes
43             let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(next_offset..offset);
44             llvals.push(cx.const_bytes(bytes));
45         }
46         let ptr_offset = read_target_uint(
47             dl.endian,
48             // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
49             // affect interpreter execution (we inspect the result after interpreter execution),
50             // and we properly interpret the relocation as a relocation pointer offset.
51             alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
52         )
53         .expect("const_alloc_to_llvm: could not read relocation pointer")
54             as u64;
55         llvals.push(cx.scalar_to_backend(
56             Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(),
57             &layout::Scalar { value: layout::Primitive::Pointer, valid_range: 0..=!0 },
58             cx.type_i8p(),
59         ));
60         next_offset = offset + pointer_size;
61     }
62     if alloc.len() >= next_offset {
63         let range = next_offset..alloc.len();
64         // This `inspect` is okay since we have check that it is after all relocations, it is
65         // within the bounds of the allocation, and it doesn't affect interpreter execution (we
66         // inspect the result after interpreter execution). Any undef byte is replaced with some
67         // arbitrary byte value.
68         //
69         // FIXME: relay undef bytes to codegen as undef const bytes
70         let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(range);
71         llvals.push(cx.const_bytes(bytes));
72     }
73
74     cx.const_struct(&llvals, true)
75 }
76
77 pub fn codegen_static_initializer(
78     cx: &CodegenCx<'ll, 'tcx>,
79     def_id: DefId,
80 ) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
81     let static_ = cx.tcx.const_eval_poly(def_id)?;
82
83     let alloc = match static_.val {
84         ty::ConstKind::Value(ConstValue::ByRef { alloc, offset }) if offset.bytes() == 0 => alloc,
85         _ => bug!("static const eval returned {:#?}", static_),
86     };
87     Ok((const_alloc_to_llvm(cx, alloc), alloc))
88 }
89
90 fn set_global_alignment(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
91     // The target may require greater alignment for globals than the type does.
92     // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
93     // which can force it to be smaller.  Rust doesn't support this yet.
94     if let Some(min) = cx.sess().target.target.options.min_global_align {
95         match Align::from_bits(min) {
96             Ok(min) => align = align.max(min),
97             Err(err) => {
98                 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
99             }
100         }
101     }
102     unsafe {
103         llvm::LLVMSetAlignment(gv, align.bytes() as u32);
104     }
105 }
106
107 fn check_and_apply_linkage(
108     cx: &CodegenCx<'ll, 'tcx>,
109     attrs: &CodegenFnAttrs,
110     ty: Ty<'tcx>,
111     sym: Symbol,
112     span: Span,
113 ) -> &'ll Value {
114     let llty = cx.layout_of(ty).llvm_type(cx);
115     let sym = sym.as_str();
116     if let Some(linkage) = attrs.linkage {
117         debug!("get_static: sym={} linkage={:?}", sym, linkage);
118
119         // If this is a static with a linkage specified, then we need to handle
120         // it a little specially. The typesystem prevents things like &T and
121         // extern "C" fn() from being non-null, so we can't just declare a
122         // static and call it a day. Some linkages (like weak) will make it such
123         // that the static actually has a null value.
124         let llty2 = if let ty::RawPtr(ref mt) = ty.kind {
125             cx.layout_of(mt.ty).llvm_type(cx)
126         } else {
127             cx.sess().span_fatal(
128                 span,
129                 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
130             )
131         };
132         unsafe {
133             // Declare a symbol `foo` with the desired linkage.
134             let g1 = cx.declare_global(&sym, llty2);
135             llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
136
137             // Declare an internal global `extern_with_linkage_foo` which
138             // is initialized with the address of `foo`.  If `foo` is
139             // discarded during linking (for example, if `foo` has weak
140             // linkage and there are no definitions), then
141             // `extern_with_linkage_foo` will instead be initialized to
142             // zero.
143             let mut real_name = "_rust_extern_with_linkage_".to_string();
144             real_name.push_str(&sym);
145             let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
146                 cx.sess().span_fatal(span, &format!("symbol `{}` is already defined", &sym))
147             });
148             llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
149             llvm::LLVMSetInitializer(g2, g1);
150             g2
151         }
152     } else {
153         // Generate an external declaration.
154         // FIXME(nagisa): investigate whether it can be changed into define_global
155         cx.declare_global(&sym, llty)
156     }
157 }
158
159 pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
160     unsafe { llvm::LLVMConstPointerCast(val, ty) }
161 }
162
163 impl CodegenCx<'ll, 'tcx> {
164     crate fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
165         unsafe { llvm::LLVMConstBitCast(val, ty) }
166     }
167
168     crate fn static_addr_of_mut(
169         &self,
170         cv: &'ll Value,
171         align: Align,
172         kind: Option<&str>,
173     ) -> &'ll Value {
174         unsafe {
175             let gv = match kind {
176                 Some(kind) if !self.tcx.sess.fewer_names() => {
177                     let name = self.generate_local_symbol_name(kind);
178                     let gv = self.define_global(&name[..], self.val_ty(cv)).unwrap_or_else(|| {
179                         bug!("symbol `{}` is already defined", name);
180                     });
181                     llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
182                     gv
183                 }
184                 _ => self.define_private_global(self.val_ty(cv)),
185             };
186             llvm::LLVMSetInitializer(gv, cv);
187             set_global_alignment(&self, gv, align);
188             SetUnnamedAddr(gv, true);
189             gv
190         }
191     }
192
193     crate fn get_static(&self, def_id: DefId) -> &'ll Value {
194         let instance = Instance::mono(self.tcx, def_id);
195         if let Some(&g) = self.instances.borrow().get(&instance) {
196             return g;
197         }
198
199         let defined_in_current_codegen_unit =
200             self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
201         assert!(
202             !defined_in_current_codegen_unit,
203             "consts::get_static() should always hit the cache for \
204                  statics defined in the same CGU, but did not for `{:?}`",
205             def_id
206         );
207
208         let ty = instance.monomorphic_ty(self.tcx);
209         let sym = self.tcx.symbol_name(instance).name;
210
211         debug!("get_static: sym={} instance={:?}", sym, instance);
212
213         let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
214             let llty = self.layout_of(ty).llvm_type(self);
215             let (g, attrs) = match self.tcx.hir().get(id) {
216                 Node::Item(&hir::Item { attrs, span, kind: hir::ItemKind::Static(..), .. }) => {
217                     let sym_str = sym.as_str();
218                     if let Some(g) = self.get_declared_value(&sym_str) {
219                         if self.val_ty(g) != self.type_ptr_to(llty) {
220                             span_bug!(span, "Conflicting types for static");
221                         }
222                     }
223
224                     let g = self.declare_global(&sym_str, llty);
225
226                     if !self.tcx.is_reachable_non_generic(def_id) {
227                         unsafe {
228                             llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
229                         }
230                     }
231
232                     (g, attrs)
233                 }
234
235                 Node::ForeignItem(&hir::ForeignItem {
236                     ref attrs,
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), &**attrs)
243                 }
244
245                 item => bug!("get_static: expected static, found {:?}", item),
246             };
247
248             debug!("get_static: sym={} attrs={:?}", sym, attrs);
249
250             for attr in attrs {
251                 if attr.check_name(sym::thread_local) {
252                     llvm::set_thread_local_mode(g, self.tls_model);
253                 }
254             }
255
256             g
257         } else {
258             // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
259             debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
260
261             let attrs = self.tcx.codegen_fn_attrs(def_id);
262             let span = self.tcx.def_span(def_id);
263             let g = check_and_apply_linkage(&self, &attrs, ty, sym, span);
264
265             // Thread-local statics in some other crate need to *always* be linked
266             // against in a thread-local fashion, so we need to be sure to apply the
267             // thread-local attribute locally if it was present remotely. If we
268             // don't do this then linker errors can be generated where the linker
269             // complains that one object files has a thread local version of the
270             // symbol and another one doesn't.
271             if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
272                 llvm::set_thread_local_mode(g, self.tls_model);
273             }
274
275             let needs_dll_storage_attr = self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
276                 // ThinLTO can't handle this workaround in all cases, so we don't
277                 // emit the attrs. Instead we make them unnecessary by disallowing
278                 // dynamic linking when linker plugin based LTO is enabled.
279                 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
280
281             // If this assertion triggers, there's something wrong with commandline
282             // argument validation.
283             debug_assert!(
284                 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
285                     && self.tcx.sess.target.target.options.is_like_msvc
286                     && self.tcx.sess.opts.cg.prefer_dynamic)
287             );
288
289             if needs_dll_storage_attr {
290                 // This item is external but not foreign, i.e., it originates from an external Rust
291                 // crate. Since we don't know whether this crate will be linked dynamically or
292                 // statically in the final application, we always mark such symbols as 'dllimport'.
293                 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
294                 // to make things work.
295                 //
296                 // However, in some scenarios we defer emission of statics to downstream
297                 // crates, so there are cases where a static with an upstream DefId
298                 // is actually present in the current crate. We can find out via the
299                 // is_codegened_item query.
300                 if !self.tcx.is_codegened_item(def_id) {
301                     unsafe {
302                         llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
303                     }
304                 }
305             }
306             g
307         };
308
309         if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
310             // For foreign (native) libs we know the exact storage type to use.
311             unsafe {
312                 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
313             }
314         }
315
316         self.instances.borrow_mut().insert(instance, g);
317         g
318     }
319 }
320
321 impl StaticMethods for CodegenCx<'ll, 'tcx> {
322     fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value {
323         if let Some(&gv) = self.const_globals.borrow().get(&cv) {
324             unsafe {
325                 // Upgrade the alignment in cases where the same constant is used with different
326                 // alignment requirements
327                 let llalign = align.bytes() as u32;
328                 if llalign > llvm::LLVMGetAlignment(gv) {
329                     llvm::LLVMSetAlignment(gv, llalign);
330                 }
331             }
332             return gv;
333         }
334         let gv = self.static_addr_of_mut(cv, align, kind);
335         unsafe {
336             llvm::LLVMSetGlobalConstant(gv, True);
337         }
338         self.const_globals.borrow_mut().insert(cv, gv);
339         gv
340     }
341
342     fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
343         unsafe {
344             let attrs = self.tcx.codegen_fn_attrs(def_id);
345
346             let (v, alloc) = match codegen_static_initializer(&self, def_id) {
347                 Ok(v) => v,
348                 // Error has already been reported
349                 Err(_) => return,
350             };
351
352             let g = self.get_static(def_id);
353
354             // boolean SSA values are i1, but they have to be stored in i8 slots,
355             // otherwise some LLVM optimization passes don't work as expected
356             let mut val_llty = self.val_ty(v);
357             let v = if val_llty == self.type_i1() {
358                 val_llty = self.type_i8();
359                 llvm::LLVMConstZExt(v, val_llty)
360             } else {
361                 v
362             };
363
364             let instance = Instance::mono(self.tcx, def_id);
365             let ty = instance.monomorphic_ty(self.tcx);
366             let llty = self.layout_of(ty).llvm_type(self);
367             let g = if val_llty == llty {
368                 g
369             } else {
370                 // If we created the global with the wrong type,
371                 // correct the type.
372                 let name = llvm::get_value_name(g).to_vec();
373                 llvm::set_value_name(g, b"");
374
375                 let linkage = llvm::LLVMRustGetLinkage(g);
376                 let visibility = llvm::LLVMRustGetVisibility(g);
377
378                 let new_g = llvm::LLVMRustGetOrInsertGlobal(
379                     self.llmod,
380                     name.as_ptr().cast(),
381                     name.len(),
382                     val_llty,
383                 );
384
385                 llvm::LLVMRustSetLinkage(new_g, linkage);
386                 llvm::LLVMRustSetVisibility(new_g, visibility);
387
388                 // To avoid breaking any invariants, we leave around the old
389                 // global for the moment; we'll replace all references to it
390                 // with the new global later. (See base::codegen_backend.)
391                 self.statics_to_rauw.borrow_mut().push((g, new_g));
392                 new_g
393             };
394             set_global_alignment(&self, g, self.align_of(ty));
395             llvm::LLVMSetInitializer(g, v);
396
397             // As an optimization, all shared statics which do not have interior
398             // mutability are placed into read-only memory.
399             if !is_mutable {
400                 if self.type_is_freeze(ty) {
401                     llvm::LLVMSetGlobalConstant(g, llvm::True);
402                 }
403             }
404
405             debuginfo::create_global_var_metadata(&self, def_id, g);
406
407             if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
408                 llvm::set_thread_local_mode(g, self.tls_model);
409
410                 // Do not allow LLVM to change the alignment of a TLS on macOS.
411                 //
412                 // By default a global's alignment can be freely increased.
413                 // This allows LLVM to generate more performant instructions
414                 // e.g., using load-aligned into a SIMD register.
415                 //
416                 // However, on macOS 10.10 or below, the dynamic linker does not
417                 // respect any alignment given on the TLS (radar 24221680).
418                 // This will violate the alignment assumption, and causing segfault at runtime.
419                 //
420                 // This bug is very easy to trigger. In `println!` and `panic!`,
421                 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
422                 // which the values would be `mem::replace`d on initialization.
423                 // The implementation of `mem::replace` will use SIMD
424                 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
425                 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
426                 // which macOS's dyld disregarded and causing crashes
427                 // (see issues #51794, #51758, #50867, #48866 and #44056).
428                 //
429                 // To workaround the bug, we trick LLVM into not increasing
430                 // the global's alignment by explicitly assigning a section to it
431                 // (equivalent to automatically generating a `#[link_section]` attribute).
432                 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
433                 // of `lib/IR/Globals.cpp` for why this works.
434                 //
435                 // When the alignment is not increased, the optimized `mem::replace`
436                 // will use load-unaligned instructions instead, and thus avoiding the crash.
437                 //
438                 // We could remove this hack whenever we decide to drop macOS 10.10 support.
439                 if self.tcx.sess.target.target.options.is_like_osx {
440                     assert_eq!(alloc.relocations().len(), 0);
441
442                     let is_zeroed = {
443                         // Treats undefined bytes as if they were defined with the byte value that
444                         // happens to be currently assigned in mir. This is valid since reading
445                         // undef bytes may yield arbitrary values.
446                         //
447                         // FIXME: ignore undef bytes even with representation `!= 0`.
448                         //
449                         // The `inspect` method is okay here because we checked relocations, and
450                         // because we are doing this access to inspect the final interpreter state
451                         // (not as part of the interpreter execution).
452                         alloc
453                             .inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len())
454                             .iter()
455                             .all(|b| *b == 0)
456                     };
457                     let sect_name = if is_zeroed {
458                         CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
459                     } else {
460                         CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
461                     };
462                     llvm::LLVMSetSection(g, sect_name.as_ptr());
463                 }
464             }
465
466             // Wasm statics with custom link sections get special treatment as they
467             // go into custom sections of the wasm executable.
468             if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
469                 if let Some(section) = attrs.link_section {
470                     let section = llvm::LLVMMDStringInContext(
471                         self.llcx,
472                         section.as_str().as_ptr().cast(),
473                         section.as_str().len() as c_uint,
474                     );
475                     assert!(alloc.relocations().is_empty());
476
477                     // The `inspect` method is okay here because we checked relocations, and
478                     // because we are doing this access to inspect the final interpreter state (not
479                     // as part of the interpreter execution).
480                     let bytes =
481                         alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len());
482                     let alloc = llvm::LLVMMDStringInContext(
483                         self.llcx,
484                         bytes.as_ptr().cast(),
485                         bytes.len() as c_uint,
486                     );
487                     let data = [section, alloc];
488                     let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
489                     llvm::LLVMAddNamedMetadataOperand(
490                         self.llmod,
491                         "wasm.custom_sections\0".as_ptr().cast(),
492                         meta,
493                     );
494                 }
495             } else {
496                 base::set_link_section(g, &attrs);
497             }
498
499             if attrs.flags.contains(CodegenFnAttrFlags::USED) {
500                 // This static will be stored in the llvm.used variable which is an array of i8*
501                 let cast = llvm::LLVMConstPointerCast(g, self.type_i8p());
502                 self.used_statics.borrow_mut().push(cast);
503             }
504         }
505     }
506 }