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;
16 use rustc::middle::const_val::ConstEvalErr;
17 use {debuginfo, machine};
19 use trans_item::{TransItem, TransItemExt};
20 use common::{self, CrateContext, val_ty};
22 use monomorphize::Instance;
30 use std::ffi::{CStr, CString};
34 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
36 llvm::LLVMConstPointerCast(val, ty.to_ref())
40 pub fn bitcast(val: ValueRef, ty: Type) -> ValueRef {
42 llvm::LLVMConstBitCast(val, ty.to_ref())
46 fn set_global_alignment(ccx: &CrateContext,
48 mut align: machine::llalign) {
49 // The target may require greater alignment for globals than the type does.
50 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
51 // which can force it to be smaller. Rust doesn't support this yet.
52 if let Some(min) = ccx.sess().target.target.options.min_global_align {
53 match ty::layout::Align::from_bits(min, min) {
54 Ok(min) => align = cmp::max(align, min.abi() as machine::llalign),
56 ccx.sess().err(&format!("invalid minimum global alignment: {}", err));
61 llvm::LLVMSetAlignment(gv, align);
65 pub fn addr_of_mut(ccx: &CrateContext,
67 align: machine::llalign,
71 let name = ccx.generate_local_symbol_name(kind);
72 let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
73 bug!("symbol `{}` is already defined", name);
75 llvm::LLVMSetInitializer(gv, cv);
76 set_global_alignment(ccx, gv, align);
77 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
78 SetUnnamedAddr(gv, true);
83 pub fn addr_of(ccx: &CrateContext,
85 align: machine::llalign,
88 if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
90 // Upgrade the alignment in cases where the same constant is used with different
91 // alignment requirements
92 if align > llvm::LLVMGetAlignment(gv) {
93 llvm::LLVMSetAlignment(gv, align);
98 let gv = addr_of_mut(ccx, cv, align, kind);
100 llvm::LLVMSetGlobalConstant(gv, True);
102 ccx.const_globals().borrow_mut().insert(cv, gv);
106 pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef {
107 let instance = Instance::mono(ccx.tcx(), def_id);
108 if let Some(&g) = ccx.instances().borrow().get(&instance) {
112 let ty = common::instance_ty(ccx.tcx(), &instance);
113 let g = if let Some(id) = ccx.tcx().hir.as_local_node_id(def_id) {
115 let llty = type_of::type_of(ccx, ty);
116 let (g, attrs) = match ccx.tcx().hir.get(id) {
117 hir_map::NodeItem(&hir::Item {
118 ref attrs, span, node: hir::ItemStatic(..), ..
120 let sym = TransItem::Static(id).symbol_name(ccx.tcx());
122 let defined_in_current_codegen_unit = ccx.codegen_unit()
124 .contains_key(&TransItem::Static(id));
125 assert!(!defined_in_current_codegen_unit);
127 if declare::get_declared_value(ccx, &sym[..]).is_some() {
128 span_bug!(span, "trans: Conflicting symbol names for static?");
131 let g = declare::define_global(ccx, &sym[..], llty).unwrap();
133 if !ccx.tcx().is_exported_symbol(def_id) {
135 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
142 hir_map::NodeForeignItem(&hir::ForeignItem {
143 ref attrs, span, node: hir::ForeignItemStatic(..), ..
145 let sym = ccx.tcx().symbol_name(instance);
146 let g = if let Some(name) =
147 attr::first_attr_value_str_by_name(&attrs, "linkage") {
148 // If this is a static with a linkage specified, then we need to handle
149 // it a little specially. The typesystem prevents things like &T and
150 // extern "C" fn() from being non-null, so we can't just declare a
151 // static and call it a day. Some linkages (like weak) will make it such
152 // that the static actually has a null value.
153 let linkage = match base::linkage_by_name(&name.as_str()) {
154 Some(linkage) => linkage,
156 ccx.sess().span_fatal(span, "invalid linkage specified");
159 let llty2 = match ty.sty {
160 ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
162 ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
166 // Declare a symbol `foo` with the desired linkage.
167 let g1 = declare::declare_global(ccx, &sym, llty2);
168 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
170 // Declare an internal global `extern_with_linkage_foo` which
171 // is initialized with the address of `foo`. If `foo` is
172 // discarded during linking (for example, if `foo` has weak
173 // linkage and there are no definitions), then
174 // `extern_with_linkage_foo` will instead be initialized to
176 let mut real_name = "_rust_extern_with_linkage_".to_string();
177 real_name.push_str(&sym);
178 let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
179 ccx.sess().span_fatal(span,
180 &format!("symbol `{}` is already defined", &sym))
182 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
183 llvm::LLVMSetInitializer(g2, g1);
187 // Generate an external declaration.
188 declare::declare_global(ccx, &sym, llty)
194 item => bug!("get_static: expected static, found {:?}", item)
198 if attr.check_name("thread_local") {
199 llvm::set_thread_local(g, true);
205 let sym = ccx.tcx().symbol_name(instance);
207 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
208 // FIXME(nagisa): investigate whether it can be changed into define_global
209 let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
210 // Thread-local statics in some other crate need to *always* be linked
211 // against in a thread-local fashion, so we need to be sure to apply the
212 // thread-local attribute locally if it was present remotely. If we
213 // don't do this then linker errors can be generated where the linker
214 // complains that one object files has a thread local version of the
215 // symbol and another one doesn't.
216 for attr in ccx.tcx().get_attrs(def_id).iter() {
217 if attr.check_name("thread_local") {
218 llvm::set_thread_local(g, true);
221 if ccx.use_dll_storage_attrs() && !ccx.tcx().is_foreign_item(def_id) {
222 // This item is external but not foreign, i.e. it originates from an external Rust
223 // crate. Since we don't know whether this crate will be linked dynamically or
224 // statically in the final application, we always mark such symbols as 'dllimport'.
225 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
228 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
235 // FIXME(#42293) we should actually track this, but fails too many tests
237 ccx.tcx().dep_graph.with_ignore(|| {
238 if ccx.use_dll_storage_attrs() && ccx.tcx().is_dllimport_foreign_item(def_id) {
239 // For foreign (native) libs we know the exact storage type to use.
241 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
245 ccx.instances().borrow_mut().insert(instance, g);
246 ccx.statics().borrow_mut().insert(g, def_id);
250 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
253 attrs: &[ast::Attribute])
254 -> Result<ValueRef, ConstEvalErr<'tcx>> {
256 let def_id = ccx.tcx().hir.local_def_id(id);
257 let g = get_static(ccx, def_id);
259 let v = ::mir::trans_static_initializer(ccx, def_id)?;
261 // boolean SSA values are i1, but they have to be stored in i8 slots,
262 // otherwise some LLVM optimization passes don't work as expected
263 let mut val_llty = val_ty(v);
264 let v = if val_llty == Type::i1(ccx) {
265 val_llty = Type::i8(ccx);
266 llvm::LLVMConstZExt(v, val_llty.to_ref())
271 let instance = Instance::mono(ccx.tcx(), def_id);
272 let ty = common::instance_ty(ccx.tcx(), &instance);
273 let llty = type_of::type_of(ccx, ty);
274 let g = if val_llty == llty {
277 // If we created the global with the wrong type,
279 let empty_string = CString::new("").unwrap();
280 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
281 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
282 llvm::LLVMSetValueName(g, empty_string.as_ptr());
284 let linkage = llvm::LLVMRustGetLinkage(g);
285 let visibility = llvm::LLVMRustGetVisibility(g);
287 let new_g = llvm::LLVMRustGetOrInsertGlobal(
288 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
290 llvm::LLVMRustSetLinkage(new_g, linkage);
291 llvm::LLVMRustSetVisibility(new_g, visibility);
293 // To avoid breaking any invariants, we leave around the old
294 // global for the moment; we'll replace all references to it
295 // with the new global later. (See base::trans_crate.)
296 ccx.statics_to_rauw().borrow_mut().push((g, new_g));
299 set_global_alignment(ccx, g, ccx.align_of(ty));
300 llvm::LLVMSetInitializer(g, v);
302 // As an optimization, all shared statics which do not have interior
303 // mutability are placed into read-only memory.
304 if m != hir::MutMutable {
305 if ccx.shared().type_is_freeze(ty) {
306 llvm::LLVMSetGlobalConstant(g, llvm::True);
310 debuginfo::create_global_var_metadata(ccx, id, g);
312 if attr::contains_name(attrs,
314 llvm::set_thread_local(g, true);
317 base::set_link_section(ccx, g, attrs);
319 if attr::contains_name(attrs, "used") {
320 // This static will be stored in the llvm.used variable which is an array of i8*
321 let cast = llvm::LLVMConstPointerCast(g, Type::i8p(ccx).to_ref());
322 ccx.used_statics().borrow_mut().push(cast);