2 use crate::common::CodegenCx;
4 use crate::llvm::{self, SetUnnamedAddr, True};
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
10 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{read_target_uint, Allocation, ConstValue, ErrorHandled, Pointer};
13 use rustc::mir::mono::MonoItem;
14 use rustc::ty::{self, Instance, Ty};
15 use rustc::{bug, span_bug};
16 use rustc_codegen_ssa::traits::*;
17 use rustc_span::symbol::{sym, Symbol};
19 use rustc_target::abi::HasDataLayout;
21 use rustc::ty::layout::{self, Align, LayoutOf, Size};
23 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs};
27 pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll Value {
28 let mut llvals = Vec::with_capacity(alloc.relocations().len() + 1);
29 let dl = cx.data_layout();
30 let pointer_size = dl.pointer_size.bytes() as usize;
32 let mut next_offset = 0;
33 for &(offset, ((), alloc_id)) in alloc.relocations().iter() {
34 let offset = offset.bytes();
35 assert_eq!(offset as usize as u64, offset);
36 let offset = offset as usize;
37 if offset > next_offset {
38 // This `inspect` is okay since we have checked that it is not within a relocation, it
39 // is within the bounds of the allocation, and it doesn't affect interpreter execution
40 // (we inspect the result after interpreter execution). Any undef byte is replaced with
41 // some arbitrary byte value.
43 // FIXME: relay undef bytes to codegen as undef const bytes
44 let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(next_offset..offset);
45 llvals.push(cx.const_bytes(bytes));
47 let ptr_offset = read_target_uint(
49 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
50 // affect interpreter execution (we inspect the result after interpreter execution),
51 // and we properly interpret the relocation as a relocation pointer offset.
52 alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
54 .expect("const_alloc_to_llvm: could not read relocation pointer")
56 llvals.push(cx.scalar_to_backend(
57 Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(),
58 &layout::Scalar { value: layout::Primitive::Pointer, valid_range: 0..=!0 },
61 next_offset = offset + pointer_size;
63 if alloc.len() >= next_offset {
64 let range = next_offset..alloc.len();
65 // This `inspect` is okay since we have check that it is after all relocations, it is
66 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
67 // inspect the result after interpreter execution). Any undef byte is replaced with some
68 // arbitrary byte value.
70 // FIXME: relay undef bytes to codegen as undef const bytes
71 let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(range);
72 llvals.push(cx.const_bytes(bytes));
75 cx.const_struct(&llvals, true)
78 pub fn codegen_static_initializer(
79 cx: &CodegenCx<'ll, 'tcx>,
81 ) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
82 let static_ = cx.tcx.const_eval_poly(def_id)?;
84 let alloc = match static_.val {
85 ty::ConstKind::Value(ConstValue::ByRef { alloc, offset }) if offset.bytes() == 0 => alloc,
86 _ => bug!("static const eval returned {:#?}", static_),
88 Ok((const_alloc_to_llvm(cx, alloc), alloc))
91 fn set_global_alignment(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
92 // The target may require greater alignment for globals than the type does.
93 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
94 // which can force it to be smaller. Rust doesn't support this yet.
95 if let Some(min) = cx.sess().target.target.options.min_global_align {
96 match Align::from_bits(min) {
97 Ok(min) => align = align.max(min),
99 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
104 llvm::LLVMSetAlignment(gv, align.bytes() as u32);
108 fn check_and_apply_linkage(
109 cx: &CodegenCx<'ll, 'tcx>,
110 attrs: &CodegenFnAttrs,
115 let llty = cx.layout_of(ty).llvm_type(cx);
116 let sym = sym.as_str();
117 if let Some(linkage) = attrs.linkage {
118 debug!("get_static: sym={} linkage={:?}", sym, linkage);
120 // If this is a static with a linkage specified, then we need to handle
121 // it a little specially. The typesystem prevents things like &T and
122 // extern "C" fn() from being non-null, so we can't just declare a
123 // static and call it a day. Some linkages (like weak) will make it such
124 // that the static actually has a null value.
125 let llty2 = if let ty::RawPtr(ref mt) = ty.kind {
126 cx.layout_of(mt.ty).llvm_type(cx)
128 cx.sess().span_fatal(
130 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
134 // Declare a symbol `foo` with the desired linkage.
135 let g1 = cx.declare_global(&sym, llty2);
136 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
138 // Declare an internal global `extern_with_linkage_foo` which
139 // is initialized with the address of `foo`. If `foo` is
140 // discarded during linking (for example, if `foo` has weak
141 // linkage and there are no definitions), then
142 // `extern_with_linkage_foo` will instead be initialized to
144 let mut real_name = "_rust_extern_with_linkage_".to_string();
145 real_name.push_str(&sym);
146 let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
147 cx.sess().span_fatal(span, &format!("symbol `{}` is already defined", &sym))
149 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
150 llvm::LLVMSetInitializer(g2, g1);
154 // Generate an external declaration.
155 // FIXME(nagisa): investigate whether it can be changed into define_global
156 cx.declare_global(&sym, llty)
160 pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
161 unsafe { llvm::LLVMConstPointerCast(val, ty) }
164 impl CodegenCx<'ll, 'tcx> {
165 crate fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
166 unsafe { llvm::LLVMConstBitCast(val, ty) }
169 crate fn static_addr_of_mut(
176 let gv = match kind {
177 Some(kind) if !self.tcx.sess.fewer_names() => {
178 let name = self.generate_local_symbol_name(kind);
179 let gv = self.define_global(&name[..], self.val_ty(cv)).unwrap_or_else(|| {
180 bug!("symbol `{}` is already defined", name);
182 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
185 _ => self.define_private_global(self.val_ty(cv)),
187 llvm::LLVMSetInitializer(gv, cv);
188 set_global_alignment(&self, gv, align);
189 SetUnnamedAddr(gv, true);
194 crate fn get_static(&self, def_id: DefId) -> &'ll Value {
195 let instance = Instance::mono(self.tcx, def_id);
196 if let Some(&g) = self.instances.borrow().get(&instance) {
200 let defined_in_current_codegen_unit =
201 self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
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 `{:?}`",
209 let ty = instance.ty(self.tcx);
210 let sym = self.tcx.symbol_name(instance).name;
212 debug!("get_static: sym={} instance={:?}", sym, instance);
214 let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
215 let llty = self.layout_of(ty).llvm_type(self);
216 let (g, attrs) = match self.tcx.hir().get(id) {
217 Node::Item(&hir::Item { attrs, span, kind: hir::ItemKind::Static(..), .. }) => {
218 let sym_str = sym.as_str();
219 if let Some(g) = self.get_declared_value(&sym_str) {
220 if self.val_ty(g) != self.type_ptr_to(llty) {
221 span_bug!(span, "Conflicting types for static");
225 let g = self.declare_global(&sym_str, llty);
227 if !self.tcx.is_reachable_non_generic(def_id) {
229 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
236 Node::ForeignItem(&hir::ForeignItem {
239 kind: hir::ForeignItemKind::Static(..),
242 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
243 (check_and_apply_linkage(&self, &fn_attrs, ty, sym, span), &**attrs)
246 item => bug!("get_static: expected static, found {:?}", item),
249 debug!("get_static: sym={} attrs={:?}", sym, attrs);
252 if attr.check_name(sym::thread_local) {
253 llvm::set_thread_local_mode(g, self.tls_model);
259 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
260 debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
262 let attrs = self.tcx.codegen_fn_attrs(def_id);
263 let span = self.tcx.def_span(def_id);
264 let g = check_and_apply_linkage(&self, &attrs, ty, sym, span);
266 // Thread-local statics in some other crate need to *always* be linked
267 // against in a thread-local fashion, so we need to be sure to apply the
268 // thread-local attribute locally if it was present remotely. If we
269 // don't do this then linker errors can be generated where the linker
270 // complains that one object files has a thread local version of the
271 // symbol and another one doesn't.
272 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
273 llvm::set_thread_local_mode(g, self.tls_model);
276 let needs_dll_storage_attr = self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
277 // ThinLTO can't handle this workaround in all cases, so we don't
278 // emit the attrs. Instead we make them unnecessary by disallowing
279 // dynamic linking when linker plugin based LTO is enabled.
280 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
282 // If this assertion triggers, there's something wrong with commandline
283 // argument validation.
285 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
286 && self.tcx.sess.target.target.options.is_like_msvc
287 && self.tcx.sess.opts.cg.prefer_dynamic)
290 if needs_dll_storage_attr {
291 // This item is external but not foreign, i.e., it originates from an external Rust
292 // crate. Since we don't know whether this crate will be linked dynamically or
293 // statically in the final application, we always mark such symbols as 'dllimport'.
294 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
295 // to make things work.
297 // However, in some scenarios we defer emission of statics to downstream
298 // crates, so there are cases where a static with an upstream DefId
299 // is actually present in the current crate. We can find out via the
300 // is_codegened_item query.
301 if !self.tcx.is_codegened_item(def_id) {
303 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
310 if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
311 // For foreign (native) libs we know the exact storage type to use.
313 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
317 self.instances.borrow_mut().insert(instance, g);
322 impl StaticMethods for CodegenCx<'ll, 'tcx> {
323 fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value {
324 if let Some(&gv) = self.const_globals.borrow().get(&cv) {
326 // Upgrade the alignment in cases where the same constant is used with different
327 // alignment requirements
328 let llalign = align.bytes() as u32;
329 if llalign > llvm::LLVMGetAlignment(gv) {
330 llvm::LLVMSetAlignment(gv, llalign);
335 let gv = self.static_addr_of_mut(cv, align, kind);
337 llvm::LLVMSetGlobalConstant(gv, True);
339 self.const_globals.borrow_mut().insert(cv, gv);
343 fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
345 let attrs = self.tcx.codegen_fn_attrs(def_id);
347 let (v, alloc) = match codegen_static_initializer(&self, def_id) {
349 // Error has already been reported
353 let g = self.get_static(def_id);
355 // boolean SSA values are i1, but they have to be stored in i8 slots,
356 // otherwise some LLVM optimization passes don't work as expected
357 let mut val_llty = self.val_ty(v);
358 let v = if val_llty == self.type_i1() {
359 val_llty = self.type_i8();
360 llvm::LLVMConstZExt(v, val_llty)
365 let instance = Instance::mono(self.tcx, def_id);
366 let ty = instance.ty(self.tcx);
367 let llty = self.layout_of(ty).llvm_type(self);
368 let g = if val_llty == llty {
371 // If we created the global with the wrong type,
373 let name = llvm::get_value_name(g).to_vec();
374 llvm::set_value_name(g, b"");
376 let linkage = llvm::LLVMRustGetLinkage(g);
377 let visibility = llvm::LLVMRustGetVisibility(g);
379 let new_g = llvm::LLVMRustGetOrInsertGlobal(
381 name.as_ptr().cast(),
386 llvm::LLVMRustSetLinkage(new_g, linkage);
387 llvm::LLVMRustSetVisibility(new_g, visibility);
389 // To avoid breaking any invariants, we leave around the old
390 // global for the moment; we'll replace all references to it
391 // with the new global later. (See base::codegen_backend.)
392 self.statics_to_rauw.borrow_mut().push((g, new_g));
395 set_global_alignment(&self, g, self.align_of(ty));
396 llvm::LLVMSetInitializer(g, v);
398 // As an optimization, all shared statics which do not have interior
399 // mutability are placed into read-only memory.
401 if self.type_is_freeze(ty) {
402 llvm::LLVMSetGlobalConstant(g, llvm::True);
406 debuginfo::create_global_var_metadata(&self, def_id, g);
408 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
409 llvm::set_thread_local_mode(g, self.tls_model);
411 // Do not allow LLVM to change the alignment of a TLS on macOS.
413 // By default a global's alignment can be freely increased.
414 // This allows LLVM to generate more performant instructions
415 // e.g., using load-aligned into a SIMD register.
417 // However, on macOS 10.10 or below, the dynamic linker does not
418 // respect any alignment given on the TLS (radar 24221680).
419 // This will violate the alignment assumption, and causing segfault at runtime.
421 // This bug is very easy to trigger. In `println!` and `panic!`,
422 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
423 // which the values would be `mem::replace`d on initialization.
424 // The implementation of `mem::replace` will use SIMD
425 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
426 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
427 // which macOS's dyld disregarded and causing crashes
428 // (see issues #51794, #51758, #50867, #48866 and #44056).
430 // To workaround the bug, we trick LLVM into not increasing
431 // the global's alignment by explicitly assigning a section to it
432 // (equivalent to automatically generating a `#[link_section]` attribute).
433 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
434 // of `lib/IR/Globals.cpp` for why this works.
436 // When the alignment is not increased, the optimized `mem::replace`
437 // will use load-unaligned instructions instead, and thus avoiding the crash.
439 // We could remove this hack whenever we decide to drop macOS 10.10 support.
440 if self.tcx.sess.target.target.options.is_like_osx {
441 assert_eq!(alloc.relocations().len(), 0);
444 // Treats undefined bytes as if they were defined with the byte value that
445 // happens to be currently assigned in mir. This is valid since reading
446 // undef bytes may yield arbitrary values.
448 // FIXME: ignore undef bytes even with representation `!= 0`.
450 // The `inspect` method is okay here because we checked relocations, and
451 // because we are doing this access to inspect the final interpreter state
452 // (not as part of the interpreter execution).
454 .inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len())
458 let sect_name = if is_zeroed {
459 CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
461 CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
463 llvm::LLVMSetSection(g, sect_name.as_ptr());
467 // Wasm statics with custom link sections get special treatment as they
468 // go into custom sections of the wasm executable.
469 if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
470 if let Some(section) = attrs.link_section {
471 let section = llvm::LLVMMDStringInContext(
473 section.as_str().as_ptr().cast(),
474 section.as_str().len() as c_uint,
476 assert!(alloc.relocations().is_empty());
478 // The `inspect` method is okay here because we checked relocations, and
479 // because we are doing this access to inspect the final interpreter state (not
480 // as part of the interpreter execution).
482 alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len());
483 let alloc = llvm::LLVMMDStringInContext(
485 bytes.as_ptr().cast(),
486 bytes.len() as c_uint,
488 let data = [section, alloc];
489 let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
490 llvm::LLVMAddNamedMetadataOperand(
492 "wasm.custom_sections\0".as_ptr().cast(),
497 base::set_link_section(g, &attrs);
500 if attrs.flags.contains(CodegenFnAttrFlags::USED) {
501 // This static will be stored in the llvm.used variable which is an array of i8*
502 let cast = llvm::LLVMConstPointerCast(g, self.type_i8p());
503 self.used_statics.borrow_mut().push(cast);