]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/consts.rs
incr.comp.: Use red/green tracking for CGU re-use.
[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, TransItemExt};
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::cmp;
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 bitcast(val: ValueRef, ty: Type) -> ValueRef {
41     unsafe {
42         llvm::LLVMConstBitCast(val, ty.to_ref())
43     }
44 }
45
46 fn set_global_alignment(ccx: &CrateContext,
47                         gv: ValueRef,
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),
55             Err(err) => {
56                 ccx.sess().err(&format!("invalid minimum global alignment: {}", err));
57             }
58         }
59     }
60     unsafe {
61         llvm::LLVMSetAlignment(gv, align);
62     }
63 }
64
65 pub fn addr_of_mut(ccx: &CrateContext,
66                    cv: ValueRef,
67                    align: machine::llalign,
68                    kind: &str)
69                     -> ValueRef {
70     unsafe {
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);
74         });
75         llvm::LLVMSetInitializer(gv, cv);
76         set_global_alignment(ccx, gv, align);
77         llvm::LLVMRustSetLinkage(gv, llvm::Linkage::InternalLinkage);
78         SetUnnamedAddr(gv, true);
79         gv
80     }
81 }
82
83 pub fn addr_of(ccx: &CrateContext,
84                cv: ValueRef,
85                align: machine::llalign,
86                kind: &str)
87                -> ValueRef {
88     if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
89         unsafe {
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);
94             }
95         }
96         return gv;
97     }
98     let gv = addr_of_mut(ccx, cv, align, kind);
99     unsafe {
100         llvm::LLVMSetGlobalConstant(gv, True);
101     }
102     ccx.const_globals().borrow_mut().insert(cv, gv);
103     gv
104 }
105
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) {
109         return g;
110     }
111
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) {
114
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(..), ..
119             }) => {
120                 let sym = TransItem::Static(id).symbol_name(ccx.tcx());
121
122                 let defined_in_current_codegen_unit = ccx.codegen_unit()
123                                                          .items()
124                                                          .contains_key(&TransItem::Static(id));
125                 assert!(!defined_in_current_codegen_unit);
126
127                 if declare::get_declared_value(ccx, &sym[..]).is_some() {
128                     span_bug!(span, "trans: Conflicting symbol names for static?");
129                 }
130
131                 let g = declare::define_global(ccx, &sym[..], llty).unwrap();
132
133                 if !ccx.tcx().is_exported_symbol(def_id) {
134                     unsafe {
135                         llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
136                     }
137                 }
138
139                 (g, attrs)
140             }
141
142             hir_map::NodeForeignItem(&hir::ForeignItem {
143                 ref attrs, span, node: hir::ForeignItemStatic(..), ..
144             }) => {
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,
155                         None => {
156                             ccx.sess().span_fatal(span, "invalid linkage specified");
157                         }
158                     };
159                     let llty2 = match ty.sty {
160                         ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
161                         _ => {
162                             ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
163                         }
164                     };
165                     unsafe {
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));
169
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
175                         // zero.
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))
181                         });
182                         llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
183                         llvm::LLVMSetInitializer(g2, g1);
184                         g2
185                     }
186                 } else {
187                     // Generate an external declaration.
188                     declare::declare_global(ccx, &sym, llty)
189                 };
190
191                 (g, attrs)
192             }
193
194             item => bug!("get_static: expected static, found {:?}", item)
195         };
196
197         for attr in attrs {
198             if attr.check_name("thread_local") {
199                 llvm::set_thread_local(g, true);
200             }
201         }
202
203         g
204     } else {
205         let sym = ccx.tcx().symbol_name(instance);
206
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);
219             }
220         }
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
226             // make things work.
227             unsafe {
228                 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
229             }
230         }
231         g
232     };
233
234     if ccx.use_dll_storage_attrs() && ccx.tcx().is_dllimport_foreign_item(def_id) {
235         // For foreign (native) libs we know the exact storage type to use.
236         unsafe {
237             llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
238         }
239     }
240
241     ccx.instances().borrow_mut().insert(instance, g);
242     ccx.statics().borrow_mut().insert(g, def_id);
243     g
244 }
245
246 pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
247                               m: hir::Mutability,
248                               id: ast::NodeId,
249                               attrs: &[ast::Attribute])
250                               -> Result<ValueRef, ConstEvalErr<'tcx>> {
251     unsafe {
252         let def_id = ccx.tcx().hir.local_def_id(id);
253         let g = get_static(ccx, def_id);
254
255         let v = ::mir::trans_static_initializer(ccx, def_id)?;
256
257         // boolean SSA values are i1, but they have to be stored in i8 slots,
258         // otherwise some LLVM optimization passes don't work as expected
259         let mut val_llty = val_ty(v);
260         let v = if val_llty == Type::i1(ccx) {
261             val_llty = Type::i8(ccx);
262             llvm::LLVMConstZExt(v, val_llty.to_ref())
263         } else {
264             v
265         };
266
267         let instance = Instance::mono(ccx.tcx(), def_id);
268         let ty = common::instance_ty(ccx.tcx(), &instance);
269         let llty = type_of::type_of(ccx, ty);
270         let g = if val_llty == llty {
271             g
272         } else {
273             // If we created the global with the wrong type,
274             // correct the type.
275             let empty_string = CString::new("").unwrap();
276             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
277             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
278             llvm::LLVMSetValueName(g, empty_string.as_ptr());
279
280             let linkage = llvm::LLVMRustGetLinkage(g);
281             let visibility = llvm::LLVMRustGetVisibility(g);
282
283             let new_g = llvm::LLVMRustGetOrInsertGlobal(
284                 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
285
286             llvm::LLVMRustSetLinkage(new_g, linkage);
287             llvm::LLVMRustSetVisibility(new_g, visibility);
288
289             // To avoid breaking any invariants, we leave around the old
290             // global for the moment; we'll replace all references to it
291             // with the new global later. (See base::trans_crate.)
292             ccx.statics_to_rauw().borrow_mut().push((g, new_g));
293             new_g
294         };
295         set_global_alignment(ccx, g, ccx.align_of(ty));
296         llvm::LLVMSetInitializer(g, v);
297
298         // As an optimization, all shared statics which do not have interior
299         // mutability are placed into read-only memory.
300         if m != hir::MutMutable {
301             if ccx.shared().type_is_freeze(ty) {
302                 llvm::LLVMSetGlobalConstant(g, llvm::True);
303             }
304         }
305
306         debuginfo::create_global_var_metadata(ccx, id, g);
307
308         if attr::contains_name(attrs,
309                                "thread_local") {
310             llvm::set_thread_local(g, true);
311         }
312
313         base::set_link_section(ccx, g, attrs);
314
315         if attr::contains_name(attrs, "used") {
316             // This static will be stored in the llvm.used variable which is an array of i8*
317             let cast = llvm::LLVMConstPointerCast(g, Type::i8p(ccx).to_ref());
318             ccx.used_statics().borrow_mut().push(cast);
319         }
320
321         Ok(g)
322     }
323 }