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