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