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