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