1 // Copyright 2012-2014 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.
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.
11 use back::link::exported_name;
14 use middle::def_id::DefId;
15 use middle::infer::normalize_associated_type;
17 use middle::subst::{Subst, Substs};
18 use middle::ty::fold::{TypeFolder, TypeFoldable};
19 use trans::attributes;
20 use trans::base::{trans_enum_variant, push_ctxt, get_item_val};
21 use trans::base::trans_fn;
26 use middle::ty::{self, HasTypeFlags, Ty};
27 use rustc::front::map as hir_map;
35 use std::hash::{Hasher, Hash, SipHasher};
37 pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
39 psubsts: &'tcx subst::Substs<'tcx>,
40 ref_id: Option<ast::NodeId>)
41 -> (ValueRef, Ty<'tcx>, bool) {
42 debug!("monomorphic_fn(\
50 assert!(!psubsts.types.needs_infer() && !psubsts.types.has_param_types());
52 // we can only monomorphize things in this crate (or inlined into it)
53 let fn_node_id = ccx.tcx().map.as_local_node_id(fn_id).unwrap();
55 let _icx = push_ctxt("monomorphic_fn");
57 let hash_id = MonoId {
59 params: &psubsts.types
62 let item_ty = ccx.tcx().lookup_item_type(fn_id).ty;
64 debug!("monomorphic_fn about to subst into {:?}", item_ty);
65 let mono_ty = apply_param_substs(ccx.tcx(), psubsts, &item_ty);
66 debug!("mono_ty = {:?} (post-substitution)", mono_ty);
68 match ccx.monomorphized().borrow().get(&hash_id) {
70 debug!("leaving monomorphic fn {}",
71 ccx.tcx().item_path_str(fn_id));
72 return (val, mono_ty, false);
77 debug!("monomorphic_fn(\
86 let map_node = errors::expect(
87 ccx.sess().diagnostic(),
88 ccx.tcx().map.find(fn_node_id),
90 format!("while monomorphizing {:?}, couldn't find it in \
91 the item map (may have attempted to monomorphize \
92 an item defined in a different crate?)",
96 if let hir_map::NodeForeignItem(_) = map_node {
97 let abi = ccx.tcx().map.get_foreign_abi(fn_node_id);
98 if abi != abi::RustIntrinsic && abi != abi::PlatformIntrinsic {
99 // Foreign externs don't have to be monomorphized.
100 return (get_item_val(ccx, fn_node_id), mono_ty, true);
104 ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
108 let mut monomorphizing = ccx.monomorphizing().borrow_mut();
109 depth = match monomorphizing.get(&fn_id) {
110 Some(&d) => d, None => 0
113 debug!("monomorphic_fn: depth for fn_id={:?} is {:?}", fn_id, depth+1);
115 // Random cut-off -- code that needs to instantiate the same function
116 // recursively more than thirty times can probably safely be assumed
117 // to be causing an infinite expansion.
118 if depth > ccx.sess().recursion_limit.get() {
119 ccx.sess().span_fatal(ccx.tcx().map.span(fn_node_id),
120 "reached the recursion limit during monomorphization");
123 monomorphizing.insert(fn_id, depth + 1);
128 let mut state = SipHasher::new();
129 hash_id.hash(&mut state);
130 mono_ty.hash(&mut state);
132 hash = format!("h{}", state.finish());
133 let path = ccx.tcx().map.def_path_from_id(fn_node_id);
134 exported_name(path, &hash[..])
137 debug!("monomorphize_fn mangled to {}", s);
139 // This shouldn't need to option dance.
140 let mut hash_id = Some(hash_id);
141 let mut mk_lldecl = |abi: abi::Abi| {
142 let lldecl = if abi != abi::Rust {
143 foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, &s)
145 // FIXME(nagisa): perhaps needs a more fine grained selection? See
146 // setup_lldecl below.
147 declare::define_internal_rust_fn(ccx, &s, mono_ty)
150 ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl);
153 let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| {
154 base::update_linkage(ccx, lldecl, None, base::OriginalTranslation);
155 attributes::from_fn_attrs(ccx, attrs, lldecl);
157 let is_first = !ccx.available_monomorphizations().borrow().contains(&s);
159 ccx.available_monomorphizations().borrow_mut().insert(s.clone());
162 let trans_everywhere = attr::requests_inline(attrs);
163 if trans_everywhere && !is_first {
164 llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage);
167 // If `true`, then `lldecl` should be given a function body.
168 // Otherwise, it should be left as a declaration of an external
169 // function, with no definition in the current compilation unit.
170 trans_everywhere || is_first
173 let lldecl = match map_node {
174 hir_map::NodeItem(i) => {
177 node: hir::ItemFn(ref decl, _, _, abi, _, ref body),
180 let d = mk_lldecl(abi);
181 let needs_body = setup_lldecl(d, &i.attrs);
183 if abi != abi::Rust {
184 foreign::trans_rust_fn_with_foreign_abi(
185 ccx, &**decl, &**body, &[], d, psubsts, fn_node_id,
188 trans_fn(ccx, &**decl, &**body, d, psubsts, fn_node_id, &[]);
195 ccx.sess().bug("Can't monomorphize this kind of item")
199 hir_map::NodeVariant(v) => {
200 let variant = inlined_variant_def(ccx, fn_node_id);
201 assert_eq!(v.node.name, variant.name);
202 let d = mk_lldecl(abi::Rust);
203 attributes::inline(d, attributes::InlineAttr::Hint);
204 trans_enum_variant(ccx, fn_node_id, variant.disr_val, psubsts, d);
207 hir_map::NodeImplItem(impl_item) => {
208 match impl_item.node {
209 hir::ImplItemKind::Method(ref sig, ref body) => {
210 let d = mk_lldecl(abi::Rust);
211 let needs_body = setup_lldecl(d, &impl_item.attrs);
224 ccx.sess().bug(&format!("can't monomorphize a {:?}",
229 hir_map::NodeTraitItem(trait_item) => {
230 match trait_item.node {
231 hir::MethodTraitItem(ref sig, Some(ref body)) => {
232 let d = mk_lldecl(abi::Rust);
233 let needs_body = setup_lldecl(d, &trait_item.attrs);
235 trans_fn(ccx, &sig.decl, body, d,
236 psubsts, trait_item.id, &[]);
241 ccx.sess().bug(&format!("can't monomorphize a {:?}",
246 hir_map::NodeStructCtor(struct_def) => {
247 let d = mk_lldecl(abi::Rust);
248 attributes::inline(d, attributes::InlineAttr::Hint);
249 if struct_def.is_struct() {
250 panic!("ast-mapped struct didn't have a ctor id")
252 base::trans_tuple_struct(ccx,
259 // Ugh -- but this ensures any new variants won't be forgotten
260 hir_map::NodeForeignItem(..) |
261 hir_map::NodeLifetime(..) |
262 hir_map::NodeTyParam(..) |
263 hir_map::NodeExpr(..) |
264 hir_map::NodeStmt(..) |
265 hir_map::NodeBlock(..) |
266 hir_map::NodePat(..) |
267 hir_map::NodeLocal(..) => {
268 ccx.sess().bug(&format!("can't monomorphize a {:?}",
273 ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
275 debug!("leaving monomorphic fn {}", ccx.tcx().item_path_str(fn_id));
276 (lldecl, mono_ty, true)
279 #[derive(PartialEq, Eq, Hash, Debug)]
280 pub struct MonoId<'tcx> {
282 pub params: &'tcx subst::VecPerParamSpace<Ty<'tcx>>
285 /// Monomorphizes a type from the AST by first applying the in-scope
286 /// substitutions and then normalizing any associated types.
287 pub fn apply_param_substs<'tcx,T>(tcx: &ty::ctxt<'tcx>,
288 param_substs: &Substs<'tcx>,
291 where T : TypeFoldable<'tcx> + HasTypeFlags
293 let substituted = value.subst(tcx, param_substs);
294 normalize_associated_type(tcx, &substituted)
298 /// Returns the normalized type of a struct field
299 pub fn field_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
300 param_substs: &Substs<'tcx>,
301 f: ty::FieldDef<'tcx>)
304 normalize_associated_type(tcx, &f.ty(tcx, param_substs))