]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/consts.rs
change the format of the linked issue number
[rust.git] / src / librustc_trans / 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
12 use back::symbol_names;
13 use llvm;
14 use llvm::{SetUnnamedAddr};
15 use llvm::{ValueRef, True};
16 use rustc_const_eval::ConstEvalErr;
17 use rustc::hir::def_id::DefId;
18 use rustc::hir::map as hir_map;
19 use {debuginfo, machine};
20 use base;
21 use trans_item::TransItem;
22 use common::{self, CrateContext, val_ty};
23 use declare;
24 use monomorphize::Instance;
25 use type_::Type;
26 use type_of;
27 use rustc::ty;
28
29 use rustc::hir;
30
31 use std::ffi::{CStr, CString};
32 use syntax::ast;
33 use syntax::attr;
34
35 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
36     unsafe {
37         llvm::LLVMConstPointerCast(val, ty.to_ref())
38     }
39 }
40
41 pub fn addr_of_mut(ccx: &CrateContext,
42                    cv: ValueRef,
43                    align: machine::llalign,
44                    kind: &str)
45                     -> ValueRef {
46     unsafe {
47         let name = ccx.generate_local_symbol_name(kind);
48         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
49             bug!("symbol `{}` is already defined", name);
50         });
51         llvm::LLVMSetInitializer(gv, cv);
52         llvm::LLVMSetAlignment(gv, align);
53         llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
54         SetUnnamedAddr(gv, true);
55         gv
56     }
57 }
58
59 pub fn addr_of(ccx: &CrateContext,
60                cv: ValueRef,
61                align: machine::llalign,
62                kind: &str)
63                -> ValueRef {
64     if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
65         unsafe {
66             // Upgrade the alignment in cases where the same constant is used with different
67             // alignment requirements
68             if align > llvm::LLVMGetAlignment(gv) {
69                 llvm::LLVMSetAlignment(gv, align);
70             }
71         }
72         return gv;
73     }
74     let gv = addr_of_mut(ccx, cv, align, kind);
75     unsafe {
76         llvm::LLVMSetGlobalConstant(gv, True);
77     }
78     ccx.const_globals().borrow_mut().insert(cv, gv);
79     gv
80 }
81
82 pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef {
83     let instance = Instance::mono(ccx.tcx(), def_id);
84     if let Some(&g) = ccx.instances().borrow().get(&instance) {
85         return g;
86     }
87
88     let ty = common::instance_ty(ccx.shared(), &instance);
89     let g = if let Some(id) = ccx.tcx().hir.as_local_node_id(def_id) {
90
91         let llty = type_of::type_of(ccx, ty);
92         let (g, attrs) = match ccx.tcx().hir.get(id) {
93             hir_map::NodeItem(&hir::Item {
94                 ref attrs, span, node: hir::ItemStatic(..), ..
95             }) => {
96                 let sym = ccx.symbol_map()
97                              .get(TransItem::Static(id))
98                              .expect("Local statics should always be in the SymbolMap");
99
100                 let defined_in_current_codegen_unit = ccx.codegen_unit()
101                                                          .items()
102                                                          .contains_key(&TransItem::Static(id));
103                 assert!(!defined_in_current_codegen_unit);
104
105                 if declare::get_declared_value(ccx, sym).is_some() {
106                     span_bug!(span, "trans: Conflicting symbol names for static?");
107                 }
108
109                 let g = declare::define_global(ccx, sym, llty).unwrap();
110
111                 (g, attrs)
112             }
113
114             hir_map::NodeForeignItem(&hir::ForeignItem {
115                 ref attrs, span, node: hir::ForeignItemStatic(..), ..
116             }) => {
117                 let sym = symbol_names::symbol_name(instance, ccx.shared());
118                 let g = if let Some(name) =
119                         attr::first_attr_value_str_by_name(&attrs, "linkage") {
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 linkage = match base::llvm_linkage_by_name(&name.as_str()) {
126                         Some(linkage) => linkage,
127                         None => {
128                             ccx.sess().span_fatal(span, "invalid linkage specified");
129                         }
130                     };
131                     let llty2 = match ty.sty {
132                         ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
133                         _ => {
134                             ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
135                         }
136                     };
137                     unsafe {
138                         // Declare a symbol `foo` with the desired linkage.
139                         let g1 = declare::declare_global(ccx, &sym, llty2);
140                         llvm::LLVMRustSetLinkage(g1, linkage);
141
142                         // Declare an internal global `extern_with_linkage_foo` which
143                         // is initialized with the address of `foo`.  If `foo` is
144                         // discarded during linking (for example, if `foo` has weak
145                         // linkage and there are no definitions), then
146                         // `extern_with_linkage_foo` will instead be initialized to
147                         // zero.
148                         let mut real_name = "_rust_extern_with_linkage_".to_string();
149                         real_name.push_str(&sym);
150                         let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
151                             ccx.sess().span_fatal(span,
152                                 &format!("symbol `{}` is already defined", &sym))
153                         });
154                         llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
155                         llvm::LLVMSetInitializer(g2, g1);
156                         g2
157                     }
158                 } else {
159                     // Generate an external declaration.
160                     declare::declare_global(ccx, &sym, llty)
161                 };
162
163                 (g, attrs)
164             }
165
166             item => bug!("get_static: expected static, found {:?}", item)
167         };
168
169         for attr in attrs {
170             if attr.check_name("thread_local") {
171                 llvm::set_thread_local(g, true);
172             }
173         }
174
175         g
176     } else {
177         let sym = symbol_names::symbol_name(instance, ccx.shared());
178
179         // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
180         // FIXME(nagisa): investigate whether it can be changed into define_global
181         let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
182         // Thread-local statics in some other crate need to *always* be linked
183         // against in a thread-local fashion, so we need to be sure to apply the
184         // thread-local attribute locally if it was present remotely. If we
185         // don't do this then linker errors can be generated where the linker
186         // complains that one object files has a thread local version of the
187         // symbol and another one doesn't.
188         for attr in ccx.tcx().get_attrs(def_id).iter() {
189             if attr.check_name("thread_local") {
190                 llvm::set_thread_local(g, true);
191             }
192         }
193         if ccx.use_dll_storage_attrs() && !ccx.sess().cstore.is_foreign_item(def_id) {
194             // This item is external but not foreign, i.e. it originates from an external Rust
195             // crate. Since we don't know whether this crate will be linked dynamically or
196             // statically in the final application, we always mark such symbols as 'dllimport'.
197             // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
198             // make things work.
199             unsafe {
200                 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
201             }
202         }
203         g
204     };
205
206     if ccx.use_dll_storage_attrs() && ccx.sess().cstore.is_dllimport_foreign_item(def_id) {
207         // For foreign (native) libs we know the exact storage type to use.
208         unsafe {
209             llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
210         }
211     }
212     ccx.instances().borrow_mut().insert(instance, g);
213     ccx.statics().borrow_mut().insert(g, def_id);
214     g
215 }
216
217 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
218                               m: hir::Mutability,
219                               id: ast::NodeId,
220                               attrs: &[ast::Attribute])
221                               -> Result<ValueRef, ConstEvalErr<'tcx>> {
222     unsafe {
223         let def_id = ccx.tcx().hir.local_def_id(id);
224         let g = get_static(ccx, def_id);
225
226         let v = ::mir::trans_static_initializer(ccx, def_id)?;
227
228         // boolean SSA values are i1, but they have to be stored in i8 slots,
229         // otherwise some LLVM optimization passes don't work as expected
230         let mut val_llty = val_ty(v);
231         let v = if val_llty == Type::i1(ccx) {
232             val_llty = Type::i8(ccx);
233             llvm::LLVMConstZExt(v, val_llty.to_ref())
234         } else {
235             v
236         };
237
238         let instance = Instance::mono(ccx.tcx(), def_id);
239         let ty = common::instance_ty(ccx.shared(), &instance);
240         let llty = type_of::type_of(ccx, ty);
241         let g = if val_llty == llty {
242             g
243         } else {
244             // If we created the global with the wrong type,
245             // correct the type.
246             let empty_string = CString::new("").unwrap();
247             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
248             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
249             llvm::LLVMSetValueName(g, empty_string.as_ptr());
250             let new_g = llvm::LLVMRustGetOrInsertGlobal(
251                 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
252             // To avoid breaking any invariants, we leave around the old
253             // global for the moment; we'll replace all references to it
254             // with the new global later. (See base::trans_crate.)
255             ccx.statics_to_rauw().borrow_mut().push((g, new_g));
256             new_g
257         };
258         llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
259         llvm::LLVMSetInitializer(g, v);
260
261         // As an optimization, all shared statics which do not have interior
262         // mutability are placed into read-only memory.
263         if m != hir::MutMutable {
264             let tcontents = ty.type_contents(ccx.tcx());
265             if !tcontents.interior_unsafe() {
266                 llvm::LLVMSetGlobalConstant(g, llvm::True);
267             }
268         }
269
270         debuginfo::create_global_var_metadata(ccx, id, g);
271
272         if attr::contains_name(attrs,
273                                "thread_local") {
274             llvm::set_thread_local(g, true);
275         }
276
277         base::set_link_section(ccx, g, attrs);
278
279         Ok(g)
280     }
281 }