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