]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mono_item.rs
Preparing the generalization of base:compile_coodegen_unit
[rust.git] / src / librustc_codegen_llvm / mono_item.rs
1 // Copyright 2016 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 //! Walks the crate looking for items/impl-items/trait-items that have
12 //! either a `rustc_symbol_name` or `rustc_item_path` attribute and
13 //! generates an error giving, respectively, the symbol name or
14 //! item-path. This is used for unit testing the code that generates
15 //! paths etc in all kinds of annoying scenarios.
16
17 use attributes;
18 use base;
19 use context::CodegenCx;
20 use llvm;
21 use monomorphize::Instance;
22 use type_of::LayoutLlvmExt;
23 use rustc::hir;
24 use rustc::hir::def::Def;
25 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
26 use rustc::mir::mono::{Linkage, Visibility};
27 use rustc::ty::TypeFoldable;
28 use rustc::ty::layout::{LayoutOf, HasTyCtxt};
29 use std::fmt;
30 use interfaces::*;
31
32 pub use rustc::mir::mono::MonoItem;
33
34 pub use rustc_mir::monomorphize::item::MonoItemExt as BaseMonoItemExt;
35
36 pub trait MonoItemExt<'a, 'tcx: 'a>: fmt::Debug + BaseMonoItemExt<'a, 'tcx> {
37     fn define<Bx: BuilderMethods<'a, 'tcx>>(&self, cx: &'a Bx::CodegenCx) {
38         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
39                self.to_string(cx.tcx()),
40                self.to_raw_string(),
41                cx.codegen_unit().name());
42
43         match *self.as_mono_item() {
44             MonoItem::Static(def_id) => {
45                 let tcx = cx.tcx();
46                 let is_mutable = match tcx.describe_def(def_id) {
47                     Some(Def::Static(_, is_mutable)) => is_mutable,
48                     Some(other) => {
49                         bug!("Expected Def::Static, found {:?}", other)
50                     }
51                     None => {
52                         bug!("Expected Def::Static for {:?}, found nothing", def_id)
53                     }
54                 };
55                 cx.codegen_static(def_id, is_mutable);
56             }
57             MonoItem::GlobalAsm(node_id) => {
58                 let item = cx.tcx().hir.expect_item(node_id);
59                 if let hir::ItemKind::GlobalAsm(ref ga) = item.node {
60                     cx.codegen_global_asm(ga);
61                 } else {
62                     span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
63                 }
64             }
65             MonoItem::Fn(instance) => {
66                 base::codegen_instance::<Bx>(&cx, instance);
67             }
68         }
69
70         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
71                self.to_string(cx.tcx()),
72                self.to_raw_string(),
73                cx.codegen_unit().name());
74     }
75
76     fn predefine<Bx: BuilderMethods<'a, 'tcx>>(
77         &self,
78         cx: &'a Bx::CodegenCx,
79         linkage: Linkage,
80         visibility: Visibility
81     ) {
82         debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
83                self.to_string(cx.tcx()),
84                self.to_raw_string(),
85                cx.codegen_unit().name());
86
87         let symbol_name = self.symbol_name(cx.tcx()).as_str();
88
89         debug!("symbol {}", &symbol_name);
90
91         match *self.as_mono_item() {
92             MonoItem::Static(def_id) => {
93                 cx.predefine_static(def_id, linkage, visibility, &symbol_name);
94             }
95             MonoItem::Fn(instance) => {
96                 cx.predefine_fn(instance, linkage, visibility, &symbol_name);
97             }
98             MonoItem::GlobalAsm(..) => {}
99         }
100
101         debug!("END PREDEFINING '{} ({})' in cgu {}",
102                self.to_string(cx.tcx()),
103                self.to_raw_string(),
104                cx.codegen_unit().name());
105     }
106
107     fn to_raw_string(&self) -> String {
108         match *self.as_mono_item() {
109             MonoItem::Fn(instance) => {
110                 format!("Fn({:?}, {})",
111                         instance.def,
112                         instance.substs.as_ptr() as usize)
113             }
114             MonoItem::Static(id) => {
115                 format!("Static({:?})", id)
116             }
117             MonoItem::GlobalAsm(id) => {
118                 format!("GlobalAsm({:?})", id)
119             }
120         }
121     }
122 }
123
124 impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {}
125
126 impl PreDefineMethods<'tcx> for CodegenCx<'ll, 'tcx> {
127     fn predefine_static(&self,
128                                   def_id: DefId,
129                                   linkage: Linkage,
130                                   visibility: Visibility,
131                                   symbol_name: &str) {
132         let instance = Instance::mono(self.tcx, def_id);
133         let ty = instance.ty(self.tcx);
134         let llty = self.layout_of(ty).llvm_type(self);
135
136         let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
137             self.sess().span_fatal(self.tcx.def_span(def_id),
138                 &format!("symbol `{}` is already defined", symbol_name))
139         });
140
141         unsafe {
142             llvm::LLVMRustSetLinkage(g, base::linkage_to_llvm(linkage));
143             llvm::LLVMRustSetVisibility(g, base::visibility_to_llvm(visibility));
144         }
145
146         self.instances.borrow_mut().insert(instance, g);
147     }
148
149     fn predefine_fn(&self,
150                               instance: Instance<'tcx>,
151                               linkage: Linkage,
152                               visibility: Visibility,
153                               symbol_name: &str) {
154         assert!(!instance.substs.needs_infer() &&
155                 !instance.substs.has_param_types());
156
157         let mono_sig = instance.fn_sig(self.tcx());
158         let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
159         let lldecl = self.declare_fn(symbol_name, mono_sig);
160         unsafe { llvm::LLVMRustSetLinkage(lldecl, base::linkage_to_llvm(linkage)) };
161         base::set_link_section(lldecl, &attrs);
162         if linkage == Linkage::LinkOnceODR ||
163             linkage == Linkage::WeakODR {
164             llvm::SetUniqueComdat(self.llmod, lldecl);
165         }
166
167         // If we're compiling the compiler-builtins crate, e.g. the equivalent of
168         // compiler-rt, then we want to implicitly compile everything with hidden
169         // visibility as we're going to link this object all over the place but
170         // don't want the symbols to get exported.
171         if linkage != Linkage::Internal && linkage != Linkage::Private &&
172            self.tcx.is_compiler_builtins(LOCAL_CRATE) {
173             unsafe {
174                 llvm::LLVMRustSetVisibility(lldecl, llvm::Visibility::Hidden);
175             }
176         } else {
177             unsafe {
178                 llvm::LLVMRustSetVisibility(lldecl, base::visibility_to_llvm(visibility));
179             }
180         }
181
182         debug!("predefine_fn: mono_sig = {:?} instance = {:?}", mono_sig, instance);
183         if instance.def.is_inline(self.tcx) {
184             attributes::inline(self, lldecl, attributes::InlineAttr::Hint);
185         }
186         attributes::from_fn_attrs(self, lldecl, Some(instance.def.def_id()));
187
188         self.instances.borrow_mut().insert(instance, lldecl);
189     }
190 }