]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/consts.rs
Don't ICE on tuple struct ctor with incorrect arg count
[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 debuginfo;
17 use base;
18 use monomorphize::MonoItem;
19 use common::{CodegenCx, val_ty};
20 use declare;
21 use monomorphize::Instance;
22 use type_::Type;
23 use type_of::LayoutLlvmExt;
24 use rustc::ty;
25 use rustc::ty::layout::{Align, LayoutOf};
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 bitcast(val: ValueRef, ty: Type) -> ValueRef {
40     unsafe {
41         llvm::LLVMConstBitCast(val, ty.to_ref())
42     }
43 }
44
45 fn set_global_alignment(cx: &CodegenCx,
46                         gv: ValueRef,
47                         mut align: Align) {
48     // The target may require greater alignment for globals than the type does.
49     // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
50     // which can force it to be smaller.  Rust doesn't support this yet.
51     if let Some(min) = cx.sess().target.target.options.min_global_align {
52         match ty::layout::Align::from_bits(min, min) {
53             Ok(min) => align = align.max(min),
54             Err(err) => {
55                 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
56             }
57         }
58     }
59     unsafe {
60         llvm::LLVMSetAlignment(gv, align.abi() as u32);
61     }
62 }
63
64 pub fn addr_of_mut(cx: &CodegenCx,
65                    cv: ValueRef,
66                    align: Align,
67                    kind: &str)
68                     -> ValueRef {
69     unsafe {
70         let name = cx.generate_local_symbol_name(kind);
71         let gv = declare::define_global(cx, &name[..], val_ty(cv)).unwrap_or_else(||{
72             bug!("symbol `{}` is already defined", name);
73         });
74         llvm::LLVMSetInitializer(gv, cv);
75         set_global_alignment(cx, gv, align);
76         llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
77         SetUnnamedAddr(gv, true);
78         gv
79     }
80 }
81
82 pub fn addr_of(cx: &CodegenCx,
83                cv: ValueRef,
84                align: Align,
85                kind: &str)
86                -> ValueRef {
87     if let Some(&gv) = cx.const_globals.borrow().get(&cv) {
88         unsafe {
89             // Upgrade the alignment in cases where the same constant is used with different
90             // alignment requirements
91             let llalign = align.abi() as u32;
92             if llalign > llvm::LLVMGetAlignment(gv) {
93                 llvm::LLVMSetAlignment(gv, llalign);
94             }
95         }
96         return gv;
97     }
98     let gv = addr_of_mut(cx, cv, align, kind);
99     unsafe {
100         llvm::LLVMSetGlobalConstant(gv, True);
101     }
102     cx.const_globals.borrow_mut().insert(cv, gv);
103     gv
104 }
105
106 pub fn get_static(cx: &CodegenCx, def_id: DefId) -> ValueRef {
107     let instance = Instance::mono(cx.tcx, def_id);
108     if let Some(&g) = cx.instances.borrow().get(&instance) {
109         return g;
110     }
111
112     let defined_in_current_codegen_unit = cx.codegen_unit
113                                             .items()
114                                             .contains_key(&MonoItem::Static(def_id));
115     assert!(!defined_in_current_codegen_unit,
116             "consts::get_static() should always hit the cache for \
117              statics defined in the same CGU, but did not for `{:?}`",
118              def_id);
119
120     let ty = instance.ty(cx.tcx);
121     let sym = cx.tcx.symbol_name(instance);
122
123     let g = if let Some(id) = cx.tcx.hir.as_local_node_id(def_id) {
124
125         let llty = cx.layout_of(ty).llvm_type(cx);
126         let (g, attrs) = match cx.tcx.hir.get(id) {
127             hir_map::NodeItem(&hir::Item {
128                 ref attrs, span, node: hir::ItemStatic(..), ..
129             }) => {
130                 if declare::get_declared_value(cx, &sym[..]).is_some() {
131                     span_bug!(span, "trans: Conflicting symbol names for static?");
132                 }
133
134                 let g = declare::define_global(cx, &sym[..], llty).unwrap();
135
136                 if !cx.tcx.is_reachable_non_generic(def_id) {
137                     unsafe {
138                         llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
139                     }
140                 }
141
142                 (g, attrs)
143             }
144
145             hir_map::NodeForeignItem(&hir::ForeignItem {
146                 ref attrs, span, node: hir::ForeignItemStatic(..), ..
147             }) => {
148                 let g = if let Some(linkage) = cx.tcx.trans_fn_attrs(def_id).linkage {
149                     // If this is a static with a linkage specified, then we need to handle
150                     // it a little specially. The typesystem prevents things like &T and
151                     // extern "C" fn() from being non-null, so we can't just declare a
152                     // static and call it a day. Some linkages (like weak) will make it such
153                     // that the static actually has a null value.
154                     let llty2 = match ty.sty {
155                         ty::TyRawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx),
156                         _ => {
157                             cx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
158                         }
159                     };
160                     unsafe {
161                         // Declare a symbol `foo` with the desired linkage.
162                         let g1 = declare::declare_global(cx, &sym, llty2);
163                         llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
164
165                         // Declare an internal global `extern_with_linkage_foo` which
166                         // is initialized with the address of `foo`.  If `foo` is
167                         // discarded during linking (for example, if `foo` has weak
168                         // linkage and there are no definitions), then
169                         // `extern_with_linkage_foo` will instead be initialized to
170                         // zero.
171                         let mut real_name = "_rust_extern_with_linkage_".to_string();
172                         real_name.push_str(&sym);
173                         let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{
174                             cx.sess().span_fatal(span,
175                                 &format!("symbol `{}` is already defined", &sym))
176                         });
177                         llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
178                         llvm::LLVMSetInitializer(g2, g1);
179                         g2
180                     }
181                 } else {
182                     // Generate an external declaration.
183                     declare::declare_global(cx, &sym, llty)
184                 };
185
186                 (g, attrs)
187             }
188
189             item => bug!("get_static: expected static, found {:?}", item)
190         };
191
192         for attr in attrs {
193             if attr.check_name("thread_local") {
194                 llvm::set_thread_local_mode(g, cx.tls_model);
195             }
196         }
197
198         g
199     } else {
200         // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
201         // FIXME(nagisa): investigate whether it can be changed into define_global
202         let g = declare::declare_global(cx, &sym, cx.layout_of(ty).llvm_type(cx));
203         // Thread-local statics in some other crate need to *always* be linked
204         // against in a thread-local fashion, so we need to be sure to apply the
205         // thread-local attribute locally if it was present remotely. If we
206         // don't do this then linker errors can be generated where the linker
207         // complains that one object files has a thread local version of the
208         // symbol and another one doesn't.
209         for attr in cx.tcx.get_attrs(def_id).iter() {
210             if attr.check_name("thread_local") {
211                 llvm::set_thread_local_mode(g, cx.tls_model);
212             }
213         }
214         if cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) {
215             // This item is external but not foreign, i.e. it originates from an external Rust
216             // crate. Since we don't know whether this crate will be linked dynamically or
217             // statically in the final application, we always mark such symbols as 'dllimport'.
218             // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs to
219             // make things work.
220             //
221             // However, in some scenarios we defer emission of statics to downstream
222             // crates, so there are cases where a static with an upstream DefId
223             // is actually present in the current crate. We can find out via the
224             // is_translated_item query.
225             if !cx.tcx.is_translated_item(def_id) {
226                 unsafe {
227                     llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
228                 }
229             }
230         }
231         g
232     };
233
234     if cx.use_dll_storage_attrs && cx.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     cx.instances.borrow_mut().insert(instance, g);
242     cx.statics.borrow_mut().insert(g, def_id);
243     g
244 }
245
246 pub fn trans_static<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
247                               def_id: DefId,
248                               is_mutable: bool,
249                               attrs: &[ast::Attribute]) {
250     unsafe {
251         let g = get_static(cx, def_id);
252
253         let v = match ::mir::trans_static_initializer(cx, def_id) {
254             Ok(v) => v,
255             // Error has already been reported
256             Err(_) => return,
257         };
258
259         // boolean SSA values are i1, but they have to be stored in i8 slots,
260         // otherwise some LLVM optimization passes don't work as expected
261         let mut val_llty = val_ty(v);
262         let v = if val_llty == Type::i1(cx) {
263             val_llty = Type::i8(cx);
264             llvm::LLVMConstZExt(v, val_llty.to_ref())
265         } else {
266             v
267         };
268
269         let instance = Instance::mono(cx.tcx, def_id);
270         let ty = instance.ty(cx.tcx);
271         let llty = cx.layout_of(ty).llvm_type(cx);
272         let g = if val_llty == llty {
273             g
274         } else {
275             // If we created the global with the wrong type,
276             // correct the type.
277             let empty_string = CString::new("").unwrap();
278             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
279             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
280             llvm::LLVMSetValueName(g, empty_string.as_ptr());
281
282             let linkage = llvm::LLVMRustGetLinkage(g);
283             let visibility = llvm::LLVMRustGetVisibility(g);
284
285             let new_g = llvm::LLVMRustGetOrInsertGlobal(
286                 cx.llmod, name_string.as_ptr(), val_llty.to_ref());
287
288             llvm::LLVMRustSetLinkage(new_g, linkage);
289             llvm::LLVMRustSetVisibility(new_g, visibility);
290
291             // To avoid breaking any invariants, we leave around the old
292             // global for the moment; we'll replace all references to it
293             // with the new global later. (See base::trans_crate.)
294             cx.statics_to_rauw.borrow_mut().push((g, new_g));
295             new_g
296         };
297         set_global_alignment(cx, g, cx.align_of(ty));
298         llvm::LLVMSetInitializer(g, v);
299
300         // As an optimization, all shared statics which do not have interior
301         // mutability are placed into read-only memory.
302         if !is_mutable {
303             if cx.type_is_freeze(ty) {
304                 llvm::LLVMSetGlobalConstant(g, llvm::True);
305             }
306         }
307
308         debuginfo::create_global_var_metadata(cx, def_id, g);
309
310         if attr::contains_name(attrs, "thread_local") {
311             llvm::set_thread_local_mode(g, cx.tls_model);
312         }
313
314         base::set_link_section(cx, g, attrs);
315
316         if attr::contains_name(attrs, "used") {
317             // This static will be stored in the llvm.used variable which is an array of i8*
318             let cast = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
319             cx.used_statics.borrow_mut().push(cast);
320         }
321     }
322 }