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.
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.
12 use llvm::{SetUnnamedAddr};
13 use llvm::{ValueRef, True};
14 use rustc::hir::def_id::DefId;
15 use rustc::hir::map as hir_map;
18 use monomorphize::MonoItem;
19 use common::{CodegenCx, val_ty};
21 use monomorphize::Instance;
23 use type_of::LayoutLlvmExt;
25 use rustc::ty::layout::{Align, LayoutOf};
29 use std::ffi::{CStr, CString};
33 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
35 llvm::LLVMConstPointerCast(val, ty.to_ref())
39 pub fn bitcast(val: ValueRef, ty: Type) -> ValueRef {
41 llvm::LLVMConstBitCast(val, ty.to_ref())
45 fn set_global_alignment(cx: &CodegenCx,
48 // The target may require greater alignment for globals than the type does.
49 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
50 // which can force it to be smaller. Rust doesn't support this yet.
51 if let Some(min) = cx.sess().target.target.options.min_global_align {
52 match ty::layout::Align::from_bits(min, min) {
53 Ok(min) => align = align.max(min),
55 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
60 llvm::LLVMSetAlignment(gv, align.abi() as u32);
64 pub fn addr_of_mut(cx: &CodegenCx,
70 let name = cx.generate_local_symbol_name(kind);
71 let gv = declare::define_global(cx, &name[..], val_ty(cv)).unwrap_or_else(||{
72 bug!("symbol `{}` is already defined", name);
74 llvm::LLVMSetInitializer(gv, cv);
75 set_global_alignment(cx, gv, align);
76 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
77 SetUnnamedAddr(gv, true);
82 pub fn addr_of(cx: &CodegenCx,
87 if let Some(&gv) = cx.const_globals.borrow().get(&cv) {
89 // Upgrade the alignment in cases where the same constant is used with different
90 // alignment requirements
91 let llalign = align.abi() as u32;
92 if llalign > llvm::LLVMGetAlignment(gv) {
93 llvm::LLVMSetAlignment(gv, llalign);
98 let gv = addr_of_mut(cx, cv, align, kind);
100 llvm::LLVMSetGlobalConstant(gv, True);
102 cx.const_globals.borrow_mut().insert(cv, gv);
106 pub fn get_static(cx: &CodegenCx, def_id: DefId) -> ValueRef {
107 let instance = Instance::mono(cx.tcx, def_id);
108 if let Some(&g) = cx.instances.borrow().get(&instance) {
112 let defined_in_current_codegen_unit = cx.codegen_unit
114 .contains_key(&MonoItem::Static(def_id));
115 assert!(!defined_in_current_codegen_unit,
116 "consts::get_static() should always hit the cache for \
117 statics defined in the same CGU, but did not for `{:?}`",
120 let ty = instance.ty(cx.tcx);
121 let sym = cx.tcx.symbol_name(instance);
123 let g = if let Some(id) = cx.tcx.hir.as_local_node_id(def_id) {
125 let llty = cx.layout_of(ty).llvm_type(cx);
126 let (g, attrs) = match cx.tcx.hir.get(id) {
127 hir_map::NodeItem(&hir::Item {
128 ref attrs, span, node: hir::ItemStatic(..), ..
130 if declare::get_declared_value(cx, &sym[..]).is_some() {
131 span_bug!(span, "trans: Conflicting symbol names for static?");
134 let g = declare::define_global(cx, &sym[..], llty).unwrap();
136 if !cx.tcx.is_reachable_non_generic(def_id) {
138 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
145 hir_map::NodeForeignItem(&hir::ForeignItem {
146 ref attrs, span, node: hir::ForeignItemStatic(..), ..
148 let g = if let Some(linkage) = cx.tcx.trans_fn_attrs(def_id).linkage {
149 // If this is a static with a linkage specified, then we need to handle
150 // it a little specially. The typesystem prevents things like &T and
151 // extern "C" fn() from being non-null, so we can't just declare a
152 // static and call it a day. Some linkages (like weak) will make it such
153 // that the static actually has a null value.
154 let llty2 = match ty.sty {
155 ty::TyRawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx),
157 cx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
161 // Declare a symbol `foo` with the desired linkage.
162 let g1 = declare::declare_global(cx, &sym, llty2);
163 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
165 // Declare an internal global `extern_with_linkage_foo` which
166 // is initialized with the address of `foo`. If `foo` is
167 // discarded during linking (for example, if `foo` has weak
168 // linkage and there are no definitions), then
169 // `extern_with_linkage_foo` will instead be initialized to
171 let mut real_name = "_rust_extern_with_linkage_".to_string();
172 real_name.push_str(&sym);
173 let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{
174 cx.sess().span_fatal(span,
175 &format!("symbol `{}` is already defined", &sym))
177 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
178 llvm::LLVMSetInitializer(g2, g1);
182 // Generate an external declaration.
183 declare::declare_global(cx, &sym, llty)
189 item => bug!("get_static: expected static, found {:?}", item)
193 if attr.check_name("thread_local") {
194 llvm::set_thread_local_mode(g, cx.tls_model);
200 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
201 // FIXME(nagisa): investigate whether it can be changed into define_global
202 let g = declare::declare_global(cx, &sym, cx.layout_of(ty).llvm_type(cx));
203 // Thread-local statics in some other crate need to *always* be linked
204 // against in a thread-local fashion, so we need to be sure to apply the
205 // thread-local attribute locally if it was present remotely. If we
206 // don't do this then linker errors can be generated where the linker
207 // complains that one object files has a thread local version of the
208 // symbol and another one doesn't.
209 for attr in cx.tcx.get_attrs(def_id).iter() {
210 if attr.check_name("thread_local") {
211 llvm::set_thread_local_mode(g, cx.tls_model);
214 if cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) {
215 // This item is external but not foreign, i.e. it originates from an external Rust
216 // crate. Since we don't know whether this crate will be linked dynamically or
217 // statically in the final application, we always mark such symbols as 'dllimport'.
218 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
221 // However, in some scenarios we defer emission of statics to downstream
222 // crates, so there are cases where a static with an upstream DefId
223 // is actually present in the current crate. We can find out via the
224 // is_translated_item query.
225 if !cx.tcx.is_translated_item(def_id) {
227 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
234 if cx.use_dll_storage_attrs && cx.tcx.is_dllimport_foreign_item(def_id) {
235 // For foreign (native) libs we know the exact storage type to use.
237 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
241 cx.instances.borrow_mut().insert(instance, g);
242 cx.statics.borrow_mut().insert(g, def_id);
246 pub fn trans_static<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
249 attrs: &[ast::Attribute]) {
251 let g = get_static(cx, def_id);
253 let v = match ::mir::trans_static_initializer(cx, def_id) {
255 // Error has already been reported
259 // boolean SSA values are i1, but they have to be stored in i8 slots,
260 // otherwise some LLVM optimization passes don't work as expected
261 let mut val_llty = val_ty(v);
262 let v = if val_llty == Type::i1(cx) {
263 val_llty = Type::i8(cx);
264 llvm::LLVMConstZExt(v, val_llty.to_ref())
269 let instance = Instance::mono(cx.tcx, def_id);
270 let ty = instance.ty(cx.tcx);
271 let llty = cx.layout_of(ty).llvm_type(cx);
272 let g = if val_llty == llty {
275 // If we created the global with the wrong type,
277 let empty_string = CString::new("").unwrap();
278 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
279 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
280 llvm::LLVMSetValueName(g, empty_string.as_ptr());
282 let linkage = llvm::LLVMRustGetLinkage(g);
283 let visibility = llvm::LLVMRustGetVisibility(g);
285 let new_g = llvm::LLVMRustGetOrInsertGlobal(
286 cx.llmod, name_string.as_ptr(), val_llty.to_ref());
288 llvm::LLVMRustSetLinkage(new_g, linkage);
289 llvm::LLVMRustSetVisibility(new_g, visibility);
291 // To avoid breaking any invariants, we leave around the old
292 // global for the moment; we'll replace all references to it
293 // with the new global later. (See base::trans_crate.)
294 cx.statics_to_rauw.borrow_mut().push((g, new_g));
297 set_global_alignment(cx, g, cx.align_of(ty));
298 llvm::LLVMSetInitializer(g, v);
300 // As an optimization, all shared statics which do not have interior
301 // mutability are placed into read-only memory.
303 if cx.type_is_freeze(ty) {
304 llvm::LLVMSetGlobalConstant(g, llvm::True);
308 debuginfo::create_global_var_metadata(cx, def_id, g);
310 if attr::contains_name(attrs, "thread_local") {
311 llvm::set_thread_local_mode(g, cx.tls_model);
314 base::set_link_section(cx, g, attrs);
316 if attr::contains_name(attrs, "used") {
317 // This static will be stored in the llvm.used variable which is an array of i8*
318 let cast = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
319 cx.used_statics.borrow_mut().push(cast);