rust/src/librustc_trans/trans/monomorphize.rs

311 lines
11 KiB
Rust
Raw Normal View History

// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::link::exported_name;
use llvm::ValueRef;
use llvm;
2015-08-16 06:32:28 -04:00
use middle::def_id::DefId;
use middle::infer::normalize_associated_type;
use middle::subst;
use middle::subst::{Subst, Substs};
use middle::ty::fold::{TypeFolder, TypeFoldable};
use trans::attributes;
use trans::base::{trans_enum_variant, push_ctxt, get_item_val};
use trans::base::trans_fn;
use trans::base;
use trans::common::*;
use trans::declare;
use trans::foreign;
2016-02-29 23:36:51 +00:00
use middle::ty::{self, Ty, TyCtxt};
use trans::Disr;
2015-07-31 00:04:06 -07:00
use rustc::front::map as hir_map;
use rustc_front::hir;
use syntax::abi::Abi;
use syntax::ast;
use syntax::attr;
use syntax::errors;
std: Stabilize the std::hash module This commit aims to prepare the `std::hash` module for alpha by formalizing its current interface whileholding off on adding `#[stable]` to the new APIs. The current usage with the `HashMap` and `HashSet` types is also reconciled by separating out composable parts of the design. The primary goal of this slight redesign is to separate the concepts of a hasher's state from a hashing algorithm itself. The primary change of this commit is to separate the `Hasher` trait into a `Hasher` and a `HashState` trait. Conceptually the old `Hasher` trait was actually just a factory for various states, but hashing had very little control over how these states were used. Additionally the old `Hasher` trait was actually fairly unrelated to hashing. This commit redesigns the existing `Hasher` trait to match what the notion of a `Hasher` normally implies with the following definition: trait Hasher { type Output; fn reset(&mut self); fn finish(&self) -> Output; } This `Hasher` trait emphasizes that hashing algorithms may produce outputs other than a `u64`, so the output type is made generic. Other than that, however, very little is assumed about a particular hasher. It is left up to implementors to provide specific methods or trait implementations to feed data into a hasher. The corresponding `Hash` trait becomes: trait Hash<H: Hasher> { fn hash(&self, &mut H); } The old default of `SipState` was removed from this trait as it's not something that we're willing to stabilize until the end of time, but the type parameter is always required to implement `Hasher`. Note that the type parameter `H` remains on the trait to enable multidispatch for specialization of hashing for particular hashers. Note that `Writer` is not mentioned in either of `Hash` or `Hasher`, it is simply used as part `derive` and the implementations for all primitive types. With these definitions, the old `Hasher` trait is realized as a new `HashState` trait in the `collections::hash_state` module as an unstable addition for now. The current definition looks like: trait HashState { type Hasher: Hasher; fn hasher(&self) -> Hasher; } The purpose of this trait is to emphasize that the one piece of functionality for implementors is that new instances of `Hasher` can be created. This conceptually represents the two keys from which more instances of a `SipHasher` can be created, and a `HashState` is what's stored in a `HashMap`, not a `Hasher`. Implementors of custom hash algorithms should implement the `Hasher` trait, and only hash algorithms intended for use in hash maps need to implement or worry about the `HashState` trait. The entire module and `HashState` infrastructure remains `#[unstable]` due to it being recently redesigned, but some other stability decision made for the `std::hash` module are: * The `Writer` trait remains `#[experimental]` as it's intended to be replaced with an `io::Writer` (more details soon). * The top-level `hash` function is `#[unstable]` as it is intended to be generic over the hashing algorithm instead of hardwired to `SipHasher` * The inner `sip` module is now private as its one export, `SipHasher` is reexported in the `hash` module. And finally, a few changes were made to the default parameters on `HashMap`. * The `RandomSipHasher` default type parameter was renamed to `RandomState`. This renaming emphasizes that it is not a hasher, but rather just state to generate hashers. It also moves away from the name "sip" as it may not always be implemented as `SipHasher`. This type lives in the `std::collections::hash_map` module as `#[unstable]` * The associated `Hasher` type of `RandomState` is creatively called... `Hasher`! This concrete structure lives next to `RandomState` as an implemenation of the "default hashing algorithm" used for a `HashMap`. Under the hood this is currently implemented as `SipHasher`, but it draws an explicit interface for now and allows us to modify the implementation over time if necessary. There are many breaking changes outlined above, and as a result this commit is a: [breaking-change]
2014-12-09 12:37:23 -08:00
use std::hash::{Hasher, Hash, SipHasher};
pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2015-08-16 06:32:28 -04:00
fn_id: DefId,
psubsts: &'tcx subst::Substs<'tcx>)
-> (ValueRef, Ty<'tcx>, bool) {
debug!("monomorphic_fn(fn_id={:?}, real_substs={:?})", fn_id, psubsts);
assert!(!psubsts.types.needs_infer() && !psubsts.types.has_param_types());
// we can only monomorphize things in this crate (or inlined into it)
let fn_node_id = ccx.tcx().map.as_local_node_id(fn_id).unwrap();
let _icx = push_ctxt("monomorphic_fn");
2014-04-20 19:29:56 +03:00
let hash_id = MonoId {
def: fn_id,
params: &psubsts.types
};
let item_ty = ccx.tcx().lookup_item_type(fn_id).ty;
2015-06-18 20:25:05 +03:00
debug!("monomorphic_fn about to subst into {:?}", item_ty);
let mono_ty = apply_param_substs(ccx.tcx(), psubsts, &item_ty);
debug!("mono_ty = {:?} (post-substitution)", mono_ty);
2014-11-06 12:25:16 -05:00
match ccx.monomorphized().borrow().get(&hash_id) {
Some(&val) => {
debug!("leaving monomorphic fn {}",
ccx.tcx().item_path_str(fn_id));
return (val, mono_ty, false);
}
None => ()
}
debug!("monomorphic_fn(\
2015-06-18 20:25:05 +03:00
fn_id={:?}, \
psubsts={:?}, \
hash_id={:?})",
2015-06-18 20:25:05 +03:00
fn_id,
psubsts,
hash_id);
let map_node = errors::expect(
ccx.sess().diagnostic(),
ccx.tcx().map.find(fn_node_id),
|| {
format!("while monomorphizing {:?}, couldn't find it in \
the item map (may have attempted to monomorphize \
an item defined in a different crate?)",
fn_id)
});
2013-12-27 16:09:29 -08:00
2015-07-31 00:04:06 -07:00
if let hir_map::NodeForeignItem(_) = map_node {
let abi = ccx.tcx().map.get_foreign_abi(fn_node_id);
if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
// Foreign externs don't have to be monomorphized.
return (get_item_val(ccx, fn_node_id), mono_ty, true);
}
}
2014-09-05 09:18:53 -07:00
ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
let depth;
{
2014-09-05 09:18:53 -07:00
let mut monomorphizing = ccx.monomorphizing().borrow_mut();
2014-11-06 12:25:16 -05:00
depth = match monomorphizing.get(&fn_id) {
Some(&d) => d, None => 0
};
debug!("monomorphic_fn: depth for fn_id={:?} is {:?}", fn_id, depth+1);
// Random cut-off -- code that needs to instantiate the same function
// recursively more than thirty times can probably safely be assumed
// to be causing an infinite expansion.
2014-03-05 16:36:01 +02:00
if depth > ccx.sess().recursion_limit.get() {
ccx.sess().span_fatal(ccx.tcx().map.span(fn_node_id),
"reached the recursion limit during monomorphization");
}
2014-03-20 19:49:20 -07:00
monomorphizing.insert(fn_id, depth + 1);
}
let hash;
let s = {
std: Stabilize the std::hash module This commit aims to prepare the `std::hash` module for alpha by formalizing its current interface whileholding off on adding `#[stable]` to the new APIs. The current usage with the `HashMap` and `HashSet` types is also reconciled by separating out composable parts of the design. The primary goal of this slight redesign is to separate the concepts of a hasher's state from a hashing algorithm itself. The primary change of this commit is to separate the `Hasher` trait into a `Hasher` and a `HashState` trait. Conceptually the old `Hasher` trait was actually just a factory for various states, but hashing had very little control over how these states were used. Additionally the old `Hasher` trait was actually fairly unrelated to hashing. This commit redesigns the existing `Hasher` trait to match what the notion of a `Hasher` normally implies with the following definition: trait Hasher { type Output; fn reset(&mut self); fn finish(&self) -> Output; } This `Hasher` trait emphasizes that hashing algorithms may produce outputs other than a `u64`, so the output type is made generic. Other than that, however, very little is assumed about a particular hasher. It is left up to implementors to provide specific methods or trait implementations to feed data into a hasher. The corresponding `Hash` trait becomes: trait Hash<H: Hasher> { fn hash(&self, &mut H); } The old default of `SipState` was removed from this trait as it's not something that we're willing to stabilize until the end of time, but the type parameter is always required to implement `Hasher`. Note that the type parameter `H` remains on the trait to enable multidispatch for specialization of hashing for particular hashers. Note that `Writer` is not mentioned in either of `Hash` or `Hasher`, it is simply used as part `derive` and the implementations for all primitive types. With these definitions, the old `Hasher` trait is realized as a new `HashState` trait in the `collections::hash_state` module as an unstable addition for now. The current definition looks like: trait HashState { type Hasher: Hasher; fn hasher(&self) -> Hasher; } The purpose of this trait is to emphasize that the one piece of functionality for implementors is that new instances of `Hasher` can be created. This conceptually represents the two keys from which more instances of a `SipHasher` can be created, and a `HashState` is what's stored in a `HashMap`, not a `Hasher`. Implementors of custom hash algorithms should implement the `Hasher` trait, and only hash algorithms intended for use in hash maps need to implement or worry about the `HashState` trait. The entire module and `HashState` infrastructure remains `#[unstable]` due to it being recently redesigned, but some other stability decision made for the `std::hash` module are: * The `Writer` trait remains `#[experimental]` as it's intended to be replaced with an `io::Writer` (more details soon). * The top-level `hash` function is `#[unstable]` as it is intended to be generic over the hashing algorithm instead of hardwired to `SipHasher` * The inner `sip` module is now private as its one export, `SipHasher` is reexported in the `hash` module. And finally, a few changes were made to the default parameters on `HashMap`. * The `RandomSipHasher` default type parameter was renamed to `RandomState`. This renaming emphasizes that it is not a hasher, but rather just state to generate hashers. It also moves away from the name "sip" as it may not always be implemented as `SipHasher`. This type lives in the `std::collections::hash_map` module as `#[unstable]` * The associated `Hasher` type of `RandomState` is creatively called... `Hasher`! This concrete structure lives next to `RandomState` as an implemenation of the "default hashing algorithm" used for a `HashMap`. Under the hood this is currently implemented as `SipHasher`, but it draws an explicit interface for now and allows us to modify the implementation over time if necessary. There are many breaking changes outlined above, and as a result this commit is a: [breaking-change]
2014-12-09 12:37:23 -08:00
let mut state = SipHasher::new();
2014-04-20 19:29:56 +03:00
hash_id.hash(&mut state);
mono_ty.hash(&mut state);
std: Stabilize the std::hash module This commit aims to prepare the `std::hash` module for alpha by formalizing its current interface whileholding off on adding `#[stable]` to the new APIs. The current usage with the `HashMap` and `HashSet` types is also reconciled by separating out composable parts of the design. The primary goal of this slight redesign is to separate the concepts of a hasher's state from a hashing algorithm itself. The primary change of this commit is to separate the `Hasher` trait into a `Hasher` and a `HashState` trait. Conceptually the old `Hasher` trait was actually just a factory for various states, but hashing had very little control over how these states were used. Additionally the old `Hasher` trait was actually fairly unrelated to hashing. This commit redesigns the existing `Hasher` trait to match what the notion of a `Hasher` normally implies with the following definition: trait Hasher { type Output; fn reset(&mut self); fn finish(&self) -> Output; } This `Hasher` trait emphasizes that hashing algorithms may produce outputs other than a `u64`, so the output type is made generic. Other than that, however, very little is assumed about a particular hasher. It is left up to implementors to provide specific methods or trait implementations to feed data into a hasher. The corresponding `Hash` trait becomes: trait Hash<H: Hasher> { fn hash(&self, &mut H); } The old default of `SipState` was removed from this trait as it's not something that we're willing to stabilize until the end of time, but the type parameter is always required to implement `Hasher`. Note that the type parameter `H` remains on the trait to enable multidispatch for specialization of hashing for particular hashers. Note that `Writer` is not mentioned in either of `Hash` or `Hasher`, it is simply used as part `derive` and the implementations for all primitive types. With these definitions, the old `Hasher` trait is realized as a new `HashState` trait in the `collections::hash_state` module as an unstable addition for now. The current definition looks like: trait HashState { type Hasher: Hasher; fn hasher(&self) -> Hasher; } The purpose of this trait is to emphasize that the one piece of functionality for implementors is that new instances of `Hasher` can be created. This conceptually represents the two keys from which more instances of a `SipHasher` can be created, and a `HashState` is what's stored in a `HashMap`, not a `Hasher`. Implementors of custom hash algorithms should implement the `Hasher` trait, and only hash algorithms intended for use in hash maps need to implement or worry about the `HashState` trait. The entire module and `HashState` infrastructure remains `#[unstable]` due to it being recently redesigned, but some other stability decision made for the `std::hash` module are: * The `Writer` trait remains `#[experimental]` as it's intended to be replaced with an `io::Writer` (more details soon). * The top-level `hash` function is `#[unstable]` as it is intended to be generic over the hashing algorithm instead of hardwired to `SipHasher` * The inner `sip` module is now private as its one export, `SipHasher` is reexported in the `hash` module. And finally, a few changes were made to the default parameters on `HashMap`. * The `RandomSipHasher` default type parameter was renamed to `RandomState`. This renaming emphasizes that it is not a hasher, but rather just state to generate hashers. It also moves away from the name "sip" as it may not always be implemented as `SipHasher`. This type lives in the `std::collections::hash_map` module as `#[unstable]` * The associated `Hasher` type of `RandomState` is creatively called... `Hasher`! This concrete structure lives next to `RandomState` as an implemenation of the "default hashing algorithm" used for a `HashMap`. Under the hood this is currently implemented as `SipHasher`, but it draws an explicit interface for now and allows us to modify the implementation over time if necessary. There are many breaking changes outlined above, and as a result this commit is a: [breaking-change]
2014-12-09 12:37:23 -08:00
hash = format!("h{}", state.finish());
let path = ccx.tcx().map.def_path_from_id(fn_node_id);
exported_name(path, &hash[..])
};
debug!("monomorphize_fn mangled to {}", s);
2014-04-20 19:29:56 +03:00
// This shouldn't need to option dance.
let mut hash_id = Some(hash_id);
let mut mk_lldecl = |abi: Abi| {
let lldecl = if abi != Abi::Rust {
foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, &s)
} else {
// FIXME(nagisa): perhaps needs a more fine grained selection? See
// setup_lldecl below.
declare::define_internal_rust_fn(ccx, &s, mono_ty)
};
2014-09-05 09:18:53 -07:00
ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl);
lldecl
};
let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| {
base::update_linkage(ccx, lldecl, None, base::OriginalTranslation);
attributes::from_fn_attrs(ccx, attrs, lldecl);
let is_first = !ccx.available_monomorphizations().borrow().contains(&s);
if is_first {
ccx.available_monomorphizations().borrow_mut().insert(s.clone());
}
let trans_everywhere = attr::requests_inline(attrs);
if trans_everywhere && !is_first {
llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage);
}
// If `true`, then `lldecl` should be given a function body.
// Otherwise, it should be left as a declaration of an external
// function, with no definition in the current compilation unit.
trans_everywhere || is_first
};
let lldecl = match map_node {
2015-07-31 00:04:06 -07:00
hir_map::NodeItem(i) => {
match *i {
2015-07-31 00:04:06 -07:00
hir::Item {
node: hir::ItemFn(ref decl, _, _, abi, _, ref body),
..
} => {
let d = mk_lldecl(abi);
let needs_body = setup_lldecl(d, &i.attrs);
if needs_body {
if abi != Abi::Rust {
foreign::trans_rust_fn_with_foreign_abi(
2016-02-09 21:24:11 +01:00
ccx, &decl, &body, &[], d, psubsts, fn_node_id,
Some(&hash[..]));
} else {
trans_fn(ccx,
2016-02-09 21:24:11 +01:00
&decl,
&body,
d,
psubsts,
fn_node_id,
&i.attrs);
}
}
d
}
_ => {
2014-03-05 16:36:01 +02:00
ccx.sess().bug("Can't monomorphize this kind of item")
}
}
}
2015-07-31 00:04:06 -07:00
hir_map::NodeVariant(v) => {
let variant = inlined_variant_def(ccx, fn_node_id);
assert_eq!(v.node.name, variant.name);
let d = mk_lldecl(Abi::Rust);
attributes::inline(d, attributes::InlineAttr::Hint);
trans_enum_variant(ccx, fn_node_id, Disr::from(variant.disr_val), psubsts, d);
d
}
2015-07-31 00:04:06 -07:00
hir_map::NodeImplItem(impl_item) => {
match impl_item.node {
2015-11-12 15:57:51 +01:00
hir::ImplItemKind::Method(ref sig, ref body) => {
let d = mk_lldecl(Abi::Rust);
let needs_body = setup_lldecl(d, &impl_item.attrs);
if needs_body {
trans_fn(ccx,
&sig.decl,
body,
d,
psubsts,
impl_item.id,
&impl_item.attrs);
}
d
}
_ => {
ccx.sess().bug(&format!("can't monomorphize a {:?}",
map_node))
}
}
}
2015-07-31 00:04:06 -07:00
hir_map::NodeTraitItem(trait_item) => {
match trait_item.node {
2015-07-31 00:04:06 -07:00
hir::MethodTraitItem(ref sig, Some(ref body)) => {
let d = mk_lldecl(Abi::Rust);
let needs_body = setup_lldecl(d, &trait_item.attrs);
if needs_body {
trans_fn(ccx,
&sig.decl,
body,
d,
psubsts,
trait_item.id,
&trait_item.attrs);
}
d
}
_ => {
2015-01-07 11:58:31 -05:00
ccx.sess().bug(&format!("can't monomorphize a {:?}",
map_node))
}
}
}
2015-07-31 00:04:06 -07:00
hir_map::NodeStructCtor(struct_def) => {
let d = mk_lldecl(Abi::Rust);
attributes::inline(d, attributes::InlineAttr::Hint);
2015-10-08 23:45:46 +03:00
if struct_def.is_struct() {
2015-10-02 03:53:28 +03:00
panic!("ast-mapped struct didn't have a ctor id")
}
base::trans_tuple_struct(ccx,
2015-10-10 03:28:40 +03:00
struct_def.id(),
psubsts,
d);
d
}
// Ugh -- but this ensures any new variants won't be forgotten
2015-07-31 00:04:06 -07:00
hir_map::NodeForeignItem(..) |
hir_map::NodeLifetime(..) |
hir_map::NodeTyParam(..) |
hir_map::NodeExpr(..) |
hir_map::NodeStmt(..) |
hir_map::NodeBlock(..) |
hir_map::NodePat(..) |
hir_map::NodeLocal(..) => {
2015-01-07 11:58:31 -05:00
ccx.sess().bug(&format!("can't monomorphize a {:?}",
map_node))
}
};
2014-09-05 09:18:53 -07:00
ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
debug!("leaving monomorphic fn {}", ccx.tcx().item_path_str(fn_id));
(lldecl, mono_ty, true)
}
2015-01-28 08:34:18 -05:00
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct MonoId<'tcx> {
2015-08-16 06:32:28 -04:00
pub def: DefId,
pub params: &'tcx subst::VecPerParamSpace<Ty<'tcx>>
2014-04-20 19:29:56 +03:00
}
/// Monomorphizes a type from the AST by first applying the in-scope
/// substitutions and then normalizing any associated types.
2016-02-29 23:36:51 +00:00
pub fn apply_param_substs<'tcx,T>(tcx: &TyCtxt<'tcx>,
param_substs: &Substs<'tcx>,
value: &T)
-> T
where T : TypeFoldable<'tcx>
{
let substituted = value.subst(tcx, param_substs);
normalize_associated_type(tcx, &substituted)
}
/// Returns the normalized type of a struct field
2016-02-29 23:36:51 +00:00
pub fn field_ty<'tcx>(tcx: &TyCtxt<'tcx>,
param_substs: &Substs<'tcx>,
2015-08-07 14:41:33 +03:00
f: ty::FieldDef<'tcx>)
-> Ty<'tcx>
{
normalize_associated_type(tcx, &f.ty(tcx, param_substs))
}