]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/callee.rs
e64dedac55a247e343d0c86f5962bd104c323301
[rust.git] / src / librustc_codegen_llvm / callee.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 //! Handles codegen of callees as well as other call-related
12 //! things.  Callees are a superset of normal rust values and sometimes
13 //! have different representations.  In particular, top-level fn items
14 //! and methods are represented as just a fn ptr and not a full
15 //! closure.
16
17 use attributes;
18 use common::{self, CodegenCx};
19 use consts;
20 use declare;
21 use llvm;
22 use monomorphize::Instance;
23 use type_of::LayoutLlvmExt;
24 use value::Value;
25
26 use rustc::hir::def_id::DefId;
27 use rustc::ty::{self, TypeFoldable};
28 use rustc::ty::layout::LayoutOf;
29 use rustc::ty::subst::Substs;
30
31 /// Codegens a reference to a fn/method item, monomorphizing and
32 /// inlining as it goes.
33 ///
34 /// # Parameters
35 ///
36 /// - `cx`: the crate context
37 /// - `instance`: the instance to be instantiated
38 pub fn get_fn(
39     cx: &CodegenCx<'ll, 'tcx>,
40     instance: Instance<'tcx>,
41 ) -> &'ll Value {
42     let tcx = cx.tcx;
43
44     debug!("get_fn(instance={:?})", instance);
45
46     assert!(!instance.substs.needs_infer());
47     assert!(!instance.substs.has_escaping_regions());
48     assert!(!instance.substs.has_param_types());
49
50     let fn_ty = instance.ty(cx.tcx);
51     if let Some(&llfn) = cx.instances.borrow().get(&instance) {
52         return llfn;
53     }
54
55     let sym = tcx.symbol_name(instance).as_str();
56     debug!("get_fn({:?}: {:?}) => {}", instance, fn_ty, sym);
57
58     // Create a fn pointer with the substituted signature.
59     let fn_ptr_ty = tcx.mk_fn_ptr(common::ty_fn_sig(cx, fn_ty));
60     let llptrty = cx.layout_of(fn_ptr_ty).llvm_type(cx);
61
62     let llfn = if let Some(llfn) = declare::get_declared_value(cx, &sym) {
63         // This is subtle and surprising, but sometimes we have to bitcast
64         // the resulting fn pointer.  The reason has to do with external
65         // functions.  If you have two crates that both bind the same C
66         // library, they may not use precisely the same types: for
67         // example, they will probably each declare their own structs,
68         // which are distinct types from LLVM's point of view (nominal
69         // types).
70         //
71         // Now, if those two crates are linked into an application, and
72         // they contain inlined code, you can wind up with a situation
73         // where both of those functions wind up being loaded into this
74         // application simultaneously. In that case, the same function
75         // (from LLVM's point of view) requires two types. But of course
76         // LLVM won't allow one function to have two types.
77         //
78         // What we currently do, therefore, is declare the function with
79         // one of the two types (whichever happens to come first) and then
80         // bitcast as needed when the function is referenced to make sure
81         // it has the type we expect.
82         //
83         // This can occur on either a crate-local or crate-external
84         // reference. It also occurs when testing libcore and in some
85         // other weird situations. Annoying.
86         if common::val_ty(llfn) != llptrty {
87             debug!("get_fn: casting {:?} to {:?}", llfn, llptrty);
88             consts::ptrcast(llfn, llptrty)
89         } else {
90             debug!("get_fn: not casting pointer!");
91             llfn
92         }
93     } else {
94         let llfn = declare::declare_fn(cx, &sym, fn_ty);
95         assert_eq!(common::val_ty(llfn), llptrty);
96         debug!("get_fn: not casting pointer!");
97
98         if instance.def.is_inline(tcx) {
99             attributes::inline(llfn, attributes::InlineAttr::Hint);
100         }
101         attributes::from_fn_attrs(cx, llfn, instance.def.def_id());
102
103         let instance_def_id = instance.def_id();
104
105         // Apply an appropriate linkage/visibility value to our item that we
106         // just declared.
107         //
108         // This is sort of subtle. Inside our codegen unit we started off
109         // compilation by predefining all our own `MonoItem` instances. That
110         // is, everything we're codegenning ourselves is already defined. That
111         // means that anything we're actually codegenning in this codegen unit
112         // will have hit the above branch in `get_declared_value`. As a result,
113         // we're guaranteed here that we're declaring a symbol that won't get
114         // defined, or in other words we're referencing a value from another
115         // codegen unit or even another crate.
116         //
117         // So because this is a foreign value we blanket apply an external
118         // linkage directive because it's coming from a different object file.
119         // The visibility here is where it gets tricky. This symbol could be
120         // referencing some foreign crate or foreign library (an `extern`
121         // block) in which case we want to leave the default visibility. We may
122         // also, though, have multiple codegen units. It could be a
123         // monomorphization, in which case its expected visibility depends on
124         // whether we are sharing generics or not. The important thing here is
125         // that the visibility we apply to the declaration is the same one that
126         // has been applied to the definition (wherever that definition may be).
127         unsafe {
128             llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage);
129
130             let is_generic = instance.substs.types().next().is_some();
131
132             if is_generic {
133                 // This is a monomorphization. Its expected visibility depends
134                 // on whether we are in share-generics mode.
135
136                 if cx.tcx.share_generics() {
137                     // We are in share_generics mode.
138
139                     if instance_def_id.is_local() {
140                         // This is a definition from the current crate. If the
141                         // definition is unreachable for downstream crates or
142                         // the current crate does not re-export generics, the
143                         // definition of the instance will have been declared
144                         // as `hidden`.
145                         if cx.tcx.is_unreachable_local_definition(instance_def_id) ||
146                            !cx.tcx.local_crate_exports_generics() {
147                             llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
148                         }
149                     } else {
150                         // This is a monomorphization of a generic function
151                         // defined in an upstream crate.
152                         if cx.tcx.upstream_monomorphizations_for(instance_def_id)
153                                  .map(|set| set.contains_key(instance.substs))
154                                  .unwrap_or(false) {
155                             // This is instantiated in another crate. It cannot
156                             // be `hidden`.
157                         } else {
158                             // This is a local instantiation of an upstream definition.
159                             // If the current crate does not re-export it
160                             // (because it is a C library or an executable), it
161                             // will have been declared `hidden`.
162                             if !cx.tcx.local_crate_exports_generics() {
163                                 llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
164                             }
165                         }
166                     }
167                 } else {
168                     // When not sharing generics, all instances are in the same
169                     // crate and have hidden visibility
170                     llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
171                 }
172             } else {
173                 // This is a non-generic function
174                 if cx.tcx.is_codegened_item(instance_def_id) {
175                     // This is a function that is instantiated in the local crate
176
177                     if instance_def_id.is_local() {
178                         // This is function that is defined in the local crate.
179                         // If it is not reachable, it is hidden.
180                         if !cx.tcx.is_reachable_non_generic(instance_def_id) {
181                             llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
182                         }
183                     } else {
184                         // This is a function from an upstream crate that has
185                         // been instantiated here. These are always hidden.
186                         llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
187                     }
188                 }
189             }
190         }
191
192         if cx.use_dll_storage_attrs &&
193             tcx.is_dllimport_foreign_item(instance_def_id)
194         {
195             unsafe {
196                 llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport);
197             }
198         }
199
200         llfn
201     };
202
203     cx.instances.borrow_mut().insert(instance, llfn);
204
205     llfn
206 }
207
208 pub fn resolve_and_get_fn(
209     cx: &CodegenCx<'ll, 'tcx>,
210     def_id: DefId,
211     substs: &'tcx Substs<'tcx>,
212 ) -> &'ll Value {
213     get_fn(
214         cx,
215         ty::Instance::resolve(
216             cx.tcx,
217             ty::ParamEnv::reveal_all(),
218             def_id,
219             substs
220         ).unwrap()
221     )
222 }