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.
13 use llvm::{SetUnnamedAddr};
14 use llvm::{ValueRef, True};
15 use rustc_const_eval::ConstEvalErr;
16 use rustc::hir::def_id::DefId;
17 use rustc::hir::map as hir_map;
18 use {debuginfo, machine};
19 use base::{self, push_ctxt};
20 use trans_item::TransItem;
21 use common::{CrateContext, val_ty};
23 use monomorphize::{Instance};
30 use std::ffi::{CStr, CString};
33 use syntax::parse::token;
35 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
37 llvm::LLVMConstPointerCast(val, ty.to_ref())
41 pub fn addr_of_mut(ccx: &CrateContext,
43 align: machine::llalign,
47 // FIXME: this totally needs a better name generation scheme, perhaps a simple global
48 // counter? Also most other uses of gensym in trans.
49 let gsym = token::gensym("_");
50 let name = format!("{}{}", kind, gsym.0);
51 let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
52 bug!("symbol `{}` is already defined", name);
54 llvm::LLVMSetInitializer(gv, cv);
55 llvm::LLVMSetAlignment(gv, align);
56 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
57 SetUnnamedAddr(gv, true);
62 pub fn addr_of(ccx: &CrateContext,
64 align: machine::llalign,
67 if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
69 // Upgrade the alignment in cases where the same constant is used with different
70 // alignment requirements
71 if align > llvm::LLVMGetAlignment(gv) {
72 llvm::LLVMSetAlignment(gv, align);
77 let gv = addr_of_mut(ccx, cv, align, kind);
79 llvm::LLVMSetGlobalConstant(gv, True);
81 ccx.const_globals().borrow_mut().insert(cv, gv);
85 pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef {
86 let instance = Instance::mono(ccx.shared(), def_id);
87 if let Some(&g) = ccx.instances().borrow().get(&instance) {
91 let ty = ccx.tcx().lookup_item_type(def_id).ty;
92 let g = if let Some(id) = ccx.tcx().map.as_local_node_id(def_id) {
94 let llty = type_of::type_of(ccx, ty);
95 let (g, attrs) = match ccx.tcx().map.get(id) {
96 hir_map::NodeItem(&hir::Item {
97 ref attrs, span, node: hir::ItemStatic(..), ..
99 let sym = ccx.symbol_map()
100 .get(TransItem::Static(id))
101 .expect("Local statics should always be in the SymbolMap");
102 // Make sure that this is never executed for something inlined.
103 assert!(!ccx.tcx().map.is_inlined_node_id(id));
105 let defined_in_current_codegen_unit = ccx.codegen_unit()
107 .contains_key(&TransItem::Static(id));
108 assert!(!defined_in_current_codegen_unit);
110 if declare::get_declared_value(ccx, sym).is_some() {
111 span_bug!(span, "trans: Conflicting symbol names for static?");
114 let g = declare::define_global(ccx, sym, llty).unwrap();
119 hir_map::NodeForeignItem(&hir::ForeignItem {
120 ref attrs, span, node: hir::ForeignItemStatic(..), ..
122 let sym = instance.symbol_name(ccx.shared());
123 let g = if let Some(name) =
124 attr::first_attr_value_str_by_name(&attrs, "linkage") {
125 // If this is a static with a linkage specified, then we need to handle
126 // it a little specially. The typesystem prevents things like &T and
127 // extern "C" fn() from being non-null, so we can't just declare a
128 // static and call it a day. Some linkages (like weak) will make it such
129 // that the static actually has a null value.
130 let linkage = match base::llvm_linkage_by_name(&name) {
131 Some(linkage) => linkage,
133 ccx.sess().span_fatal(span, "invalid linkage specified");
136 let llty2 = match ty.sty {
137 ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
139 ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
143 // Declare a symbol `foo` with the desired linkage.
144 let g1 = declare::declare_global(ccx, &sym, llty2);
145 llvm::LLVMRustSetLinkage(g1, linkage);
147 // Declare an internal global `extern_with_linkage_foo` which
148 // is initialized with the address of `foo`. If `foo` is
149 // discarded during linking (for example, if `foo` has weak
150 // linkage and there are no definitions), then
151 // `extern_with_linkage_foo` will instead be initialized to
153 let mut real_name = "_rust_extern_with_linkage_".to_string();
154 real_name.push_str(&sym);
155 let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
156 ccx.sess().span_fatal(span,
157 &format!("symbol `{}` is already defined", &sym))
159 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
160 llvm::LLVMSetInitializer(g2, g1);
164 // Generate an external declaration.
165 declare::declare_global(ccx, &sym, llty)
171 item => bug!("get_static: expected static, found {:?}", item)
175 if attr.check_name("thread_local") {
176 llvm::set_thread_local(g, true);
182 let sym = instance.symbol_name(ccx.shared());
184 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
185 // FIXME(nagisa): investigate whether it can be changed into define_global
186 let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
187 // Thread-local statics in some other crate need to *always* be linked
188 // against in a thread-local fashion, so we need to be sure to apply the
189 // thread-local attribute locally if it was present remotely. If we
190 // don't do this then linker errors can be generated where the linker
191 // complains that one object files has a thread local version of the
192 // symbol and another one doesn't.
193 for attr in ccx.tcx().get_attrs(def_id).iter() {
194 if attr.check_name("thread_local") {
195 llvm::set_thread_local(g, true);
198 if ccx.use_dll_storage_attrs() {
200 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
206 ccx.instances().borrow_mut().insert(instance, g);
207 ccx.statics().borrow_mut().insert(g, def_id);
211 pub fn trans_static(ccx: &CrateContext,
214 attrs: &[ast::Attribute])
215 -> Result<ValueRef, ConstEvalErr> {
217 let _icx = push_ctxt("trans_static");
218 let def_id = ccx.tcx().map.local_def_id(id);
219 let g = get_static(ccx, def_id);
221 let v = ::mir::trans_static_initializer(ccx, def_id)?;
223 // boolean SSA values are i1, but they have to be stored in i8 slots,
224 // otherwise some LLVM optimization passes don't work as expected
225 let mut val_llty = val_ty(v);
226 let v = if val_llty == Type::i1(ccx) {
227 val_llty = Type::i8(ccx);
228 llvm::LLVMConstZExt(v, val_llty.to_ref())
233 let ty = ccx.tcx().lookup_item_type(def_id).ty;
234 let llty = type_of::type_of(ccx, ty);
235 let g = if val_llty == llty {
238 // If we created the global with the wrong type,
240 let empty_string = CString::new("").unwrap();
241 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
242 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
243 llvm::LLVMSetValueName(g, empty_string.as_ptr());
244 let new_g = llvm::LLVMRustGetOrInsertGlobal(
245 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
246 // To avoid breaking any invariants, we leave around the old
247 // global for the moment; we'll replace all references to it
248 // with the new global later. (See base::trans_crate.)
249 ccx.statics_to_rauw().borrow_mut().push((g, new_g));
252 llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
253 llvm::LLVMSetInitializer(g, v);
255 // As an optimization, all shared statics which do not have interior
256 // mutability are placed into read-only memory.
257 if m != hir::MutMutable {
258 let tcontents = ty.type_contents(ccx.tcx());
259 if !tcontents.interior_unsafe() {
260 llvm::LLVMSetGlobalConstant(g, llvm::True);
264 debuginfo::create_global_var_metadata(ccx, id, g);
266 if attr::contains_name(attrs,
268 llvm::set_thread_local(g, true);
271 base::set_link_section(ccx, g, attrs);