1 use crate::llvm::{self, SetUnnamedAddr, True};
3 use crate::common::CodegenCx;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
9 use rustc::hir::def_id::DefId;
10 use rustc::mir::interpret::{ConstValue, Allocation, read_target_uint,
11 Pointer, ErrorHandled, GlobalId};
12 use rustc::mir::mono::MonoItem;
15 use rustc_target::abi::HasDataLayout;
16 use syntax::symbol::sym;
17 use syntax_pos::symbol::LocalInternedString;
18 use rustc::ty::{self, Ty, Instance};
19 use rustc_codegen_ssa::traits::*;
21 use rustc::ty::layout::{self, Size, Align, LayoutOf};
23 use rustc::hir::{self, CodegenFnAttrs, CodegenFnAttrFlags};
25 use std::ffi::{CStr, CString};
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 llvals.push(cx.const_bytes(&alloc.bytes[next_offset..offset]));
40 let ptr_offset = read_target_uint(
42 &alloc.bytes[offset..(offset + pointer_size)],
43 ).expect("const_alloc_to_llvm: could not read relocation pointer") as u64;
44 llvals.push(cx.scalar_to_backend(
45 Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(),
47 value: layout::Primitive::Pointer,
52 next_offset = offset + pointer_size;
54 if alloc.bytes.len() >= next_offset {
55 llvals.push(cx.const_bytes(&alloc.bytes[next_offset ..]));
58 cx.const_struct(&llvals, true)
61 pub fn codegen_static_initializer(
62 cx: &CodegenCx<'ll, 'tcx>,
64 ) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
65 let instance = ty::Instance::mono(cx.tcx, def_id);
70 let param_env = ty::ParamEnv::reveal_all();
71 let static_ = cx.tcx.const_eval(param_env.and(cid))?;
73 let alloc = match static_.val {
74 ConstValue::ByRef(ptr, alloc) if ptr.offset.bytes() == 0 => alloc,
75 _ => bug!("static const eval returned {:#?}", static_),
77 Ok((const_alloc_to_llvm(cx, alloc), alloc))
80 fn set_global_alignment(cx: &CodegenCx<'ll, '_>,
83 // The target may require greater alignment for globals than the type does.
84 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
85 // which can force it to be smaller. Rust doesn't support this yet.
86 if let Some(min) = cx.sess().target.target.options.min_global_align {
87 match Align::from_bits(min) {
88 Ok(min) => align = align.max(min),
90 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
95 llvm::LLVMSetAlignment(gv, align.bytes() as u32);
99 fn check_and_apply_linkage(
100 cx: &CodegenCx<'ll, 'tcx>,
101 attrs: &CodegenFnAttrs,
103 sym: LocalInternedString,
106 let llty = cx.layout_of(ty).llvm_type(cx);
107 if let Some(linkage) = attrs.linkage {
108 debug!("get_static: sym={} linkage={:?}", sym, linkage);
110 // If this is a static with a linkage specified, then we need to handle
111 // it a little specially. The typesystem prevents things like &T and
112 // extern "C" fn() from being non-null, so we can't just declare a
113 // static and call it a day. Some linkages (like weak) will make it such
114 // that the static actually has a null value.
115 let llty2 = if let ty::RawPtr(ref mt) = ty.sty {
116 cx.layout_of(mt.ty).llvm_type(cx)
118 cx.sess().span_fatal(
119 span, "must have type `*const T` or `*mut T` due to `#[linkage]` attribute")
122 // Declare a symbol `foo` with the desired linkage.
123 let g1 = cx.declare_global(&sym, llty2);
124 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
126 // Declare an internal global `extern_with_linkage_foo` which
127 // is initialized with the address of `foo`. If `foo` is
128 // discarded during linking (for example, if `foo` has weak
129 // linkage and there are no definitions), then
130 // `extern_with_linkage_foo` will instead be initialized to
132 let mut real_name = "_rust_extern_with_linkage_".to_string();
133 real_name.push_str(&sym);
134 let g2 = cx.define_global(&real_name, llty).unwrap_or_else(||{
135 cx.sess().span_fatal(span, &format!("symbol `{}` is already defined", &sym))
137 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
138 llvm::LLVMSetInitializer(g2, g1);
142 // Generate an external declaration.
143 // FIXME(nagisa): investigate whether it can be changed into define_global
144 cx.declare_global(&sym, llty)
148 pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
150 llvm::LLVMConstPointerCast(val, ty)
154 impl CodegenCx<'ll, 'tcx> {
155 crate fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
157 llvm::LLVMConstBitCast(val, ty)
161 crate fn static_addr_of_mut(
168 let gv = match kind {
169 Some(kind) if !self.tcx.sess.fewer_names() => {
170 let name = self.generate_local_symbol_name(kind);
171 let gv = self.define_global(&name[..],
172 self.val_ty(cv)).unwrap_or_else(||{
173 bug!("symbol `{}` is already defined", name);
175 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
178 _ => self.define_private_global(self.val_ty(cv)),
180 llvm::LLVMSetInitializer(gv, cv);
181 set_global_alignment(&self, gv, align);
182 SetUnnamedAddr(gv, true);
187 crate fn get_static(&self, def_id: DefId) -> &'ll Value {
188 let instance = Instance::mono(self.tcx, def_id);
189 if let Some(&g) = self.instances.borrow().get(&instance) {
193 let defined_in_current_codegen_unit = self.codegen_unit
195 .contains_key(&MonoItem::Static(def_id));
196 assert!(!defined_in_current_codegen_unit,
197 "consts::get_static() should always hit the cache for \
198 statics defined in the same CGU, but did not for `{:?}`",
201 let ty = instance.ty(self.tcx);
202 let sym = self.tcx.symbol_name(instance).as_str();
204 debug!("get_static: sym={} instance={:?}", sym, instance);
206 let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
208 let llty = self.layout_of(ty).llvm_type(self);
209 let (g, attrs) = match self.tcx.hir().get_by_hir_id(id) {
210 Node::Item(&hir::Item {
211 ref attrs, span, node: hir::ItemKind::Static(..), ..
213 if self.get_declared_value(&sym[..]).is_some() {
214 span_bug!(span, "Conflicting symbol names for static?");
217 let g = self.define_global(&sym[..], llty).unwrap();
219 if !self.tcx.is_reachable_non_generic(def_id) {
221 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
228 Node::ForeignItem(&hir::ForeignItem {
229 ref attrs, span, node: hir::ForeignItemKind::Static(..), ..
231 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
232 (check_and_apply_linkage(&self, &fn_attrs, ty, sym, span), attrs)
235 item => bug!("get_static: expected static, found {:?}", item)
238 debug!("get_static: sym={} attrs={:?}", sym, attrs);
241 if attr.check_name(sym::thread_local) {
242 llvm::set_thread_local_mode(g, self.tls_model);
248 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
249 debug!("get_static: sym={} item_attr={:?}", sym, self.tcx.item_attrs(def_id));
251 let attrs = self.tcx.codegen_fn_attrs(def_id);
252 let span = self.tcx.def_span(def_id);
253 let g = check_and_apply_linkage(&self, &attrs, ty, sym, span);
255 // Thread-local statics in some other crate need to *always* be linked
256 // against in a thread-local fashion, so we need to be sure to apply the
257 // thread-local attribute locally if it was present remotely. If we
258 // don't do this then linker errors can be generated where the linker
259 // complains that one object files has a thread local version of the
260 // symbol and another one doesn't.
261 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
262 llvm::set_thread_local_mode(g, self.tls_model);
265 let needs_dll_storage_attr =
266 self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
267 // ThinLTO can't handle this workaround in all cases, so we don't
268 // emit the attrs. Instead we make them unnecessary by disallowing
269 // dynamic linking when linker plugin based LTO is enabled.
270 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
272 // If this assertion triggers, there's something wrong with commandline
273 // argument validation.
274 debug_assert!(!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
275 self.tcx.sess.target.target.options.is_like_msvc &&
276 self.tcx.sess.opts.cg.prefer_dynamic));
278 if needs_dll_storage_attr {
279 // This item is external but not foreign, i.e., it originates from an external Rust
280 // crate. Since we don't know whether this crate will be linked dynamically or
281 // statically in the final application, we always mark such symbols as 'dllimport'.
282 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
283 // to make things work.
285 // However, in some scenarios we defer emission of statics to downstream
286 // crates, so there are cases where a static with an upstream DefId
287 // is actually present in the current crate. We can find out via the
288 // is_codegened_item query.
289 if !self.tcx.is_codegened_item(def_id) {
291 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
298 if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
299 // For foreign (native) libs we know the exact storage type to use.
301 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
305 self.instances.borrow_mut().insert(instance, g);
310 impl StaticMethods for CodegenCx<'ll, 'tcx> {
317 if let Some(&gv) = self.const_globals.borrow().get(&cv) {
319 // Upgrade the alignment in cases where the same constant is used with different
320 // alignment requirements
321 let llalign = align.bytes() as u32;
322 if llalign > llvm::LLVMGetAlignment(gv) {
323 llvm::LLVMSetAlignment(gv, llalign);
328 let gv = self.static_addr_of_mut(cv, align, kind);
330 llvm::LLVMSetGlobalConstant(gv, True);
332 self.const_globals.borrow_mut().insert(cv, gv);
342 let attrs = self.tcx.codegen_fn_attrs(def_id);
344 let (v, alloc) = match codegen_static_initializer(&self, def_id) {
346 // Error has already been reported
350 let g = self.get_static(def_id);
352 // boolean SSA values are i1, but they have to be stored in i8 slots,
353 // otherwise some LLVM optimization passes don't work as expected
354 let mut val_llty = self.val_ty(v);
355 let v = if val_llty == self.type_i1() {
356 val_llty = self.type_i8();
357 llvm::LLVMConstZExt(v, val_llty)
362 let instance = Instance::mono(self.tcx, def_id);
363 let ty = instance.ty(self.tcx);
364 let llty = self.layout_of(ty).llvm_type(self);
365 let g = if val_llty == llty {
368 // If we created the global with the wrong type,
370 let empty_string = const_cstr!("");
371 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
372 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
373 llvm::LLVMSetValueName(g, empty_string.as_ptr());
375 let linkage = llvm::LLVMRustGetLinkage(g);
376 let visibility = llvm::LLVMRustGetVisibility(g);
378 let new_g = llvm::LLVMRustGetOrInsertGlobal(
379 self.llmod, name_string.as_ptr(), val_llty);
381 llvm::LLVMRustSetLinkage(new_g, linkage);
382 llvm::LLVMRustSetVisibility(new_g, visibility);
384 // To avoid breaking any invariants, we leave around the old
385 // global for the moment; we'll replace all references to it
386 // with the new global later. (See base::codegen_backend.)
387 self.statics_to_rauw.borrow_mut().push((g, new_g));
390 set_global_alignment(&self, g, self.align_of(ty));
391 llvm::LLVMSetInitializer(g, v);
393 // As an optimization, all shared statics which do not have interior
394 // mutability are placed into read-only memory.
396 if self.type_is_freeze(ty) {
397 llvm::LLVMSetGlobalConstant(g, llvm::True);
401 debuginfo::create_global_var_metadata(&self, def_id, g);
403 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
404 llvm::set_thread_local_mode(g, self.tls_model);
406 // Do not allow LLVM to change the alignment of a TLS on macOS.
408 // By default a global's alignment can be freely increased.
409 // This allows LLVM to generate more performant instructions
410 // e.g., using load-aligned into a SIMD register.
412 // However, on macOS 10.10 or below, the dynamic linker does not
413 // respect any alignment given on the TLS (radar 24221680).
414 // This will violate the alignment assumption, and causing segfault at runtime.
416 // This bug is very easy to trigger. In `println!` and `panic!`,
417 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
418 // which the values would be `mem::replace`d on initialization.
419 // The implementation of `mem::replace` will use SIMD
420 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
421 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
422 // which macOS's dyld disregarded and causing crashes
423 // (see issues #51794, #51758, #50867, #48866 and #44056).
425 // To workaround the bug, we trick LLVM into not increasing
426 // the global's alignment by explicitly assigning a section to it
427 // (equivalent to automatically generating a `#[link_section]` attribute).
428 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
429 // of `lib/IR/Globals.cpp` for why this works.
431 // When the alignment is not increased, the optimized `mem::replace`
432 // will use load-unaligned instructions instead, and thus avoiding the crash.
434 // We could remove this hack whenever we decide to drop macOS 10.10 support.
435 if self.tcx.sess.target.target.options.is_like_osx {
436 let sect_name = if alloc.bytes.iter().all(|b| *b == 0) {
437 CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
439 CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
441 llvm::LLVMSetSection(g, sect_name.as_ptr());
446 // Wasm statics with custom link sections get special treatment as they
447 // go into custom sections of the wasm executable.
448 if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
449 if let Some(section) = attrs.link_section {
450 let section = llvm::LLVMMDStringInContext(
452 section.as_str().as_ptr() as *const _,
453 section.as_str().len() as c_uint,
455 let alloc = llvm::LLVMMDStringInContext(
457 alloc.bytes.as_ptr() as *const _,
458 alloc.bytes.len() as c_uint,
460 let data = [section, alloc];
461 let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
462 llvm::LLVMAddNamedMetadataOperand(
464 "wasm.custom_sections\0".as_ptr() as *const _,
469 base::set_link_section(g, &attrs);
472 if attrs.flags.contains(CodegenFnAttrFlags::USED) {
473 // This static will be stored in the llvm.used variable which is an array of i8*
474 let cast = llvm::LLVMConstPointerCast(g, self.type_i8p());
475 self.used_statics.borrow_mut().push(cast);