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;
17 use middle::subst::{Subst, Substs};
19 use middle::ty_fold::{TypeFolder, TypeFoldable};
20 use trans::base::{set_llvm_fn_attrs, set_inline_hint};
21 use trans::base::{trans_enum_variant, push_ctxt, get_item_val};
22 use trans::base::{trans_fn, decl_internal_rust_fn};
26 use middle::ty::{mod, HasProjectionTypes, Ty};
27 use util::ppaux::Repr;
32 use syntax::ast_util::{local_def, PostExpansionMethod};
34 use syntax::codemap::DUMMY_SP;
35 use std::hash::{sip, Hash};
37 pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
39 psubsts: &subst::Substs<'tcx>,
40 ref_id: Option<ast::NodeId>)
42 debug!("monomorphic_fn(\
46 fn_id.repr(ccx.tcx()),
47 psubsts.repr(ccx.tcx()),
50 assert!(psubsts.types.all(|t| {
51 !ty::type_needs_infer(*t) && !ty::type_has_params(*t)
54 let _icx = push_ctxt("monomorphic_fn");
56 let hash_id = MonoId {
58 params: psubsts.types.clone()
61 match ccx.monomorphized().borrow().get(&hash_id) {
63 debug!("leaving monomorphic fn {}",
64 ty::item_path_str(ccx.tcx(), fn_id));
70 debug!("monomorphic_fn(\
74 fn_id.repr(ccx.tcx()),
75 psubsts.repr(ccx.tcx()),
78 let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
79 let llitem_ty = tpt.ty;
81 let map_node = session::expect(
83 ccx.tcx().map.find(fn_id.node),
85 format!("while monomorphizing {}, couldn't find it in \
86 the item map (may have attempted to monomorphize \
87 an item defined in a different crate?)",
91 if let ast_map::NodeForeignItem(_) = map_node {
92 if ccx.tcx().map.get_foreign_abi(fn_id.node) != abi::RustIntrinsic {
93 // Foreign externs don't have to be monomorphized.
94 return (get_item_val(ccx, fn_id.node), true);
98 debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
100 let mono_ty = llitem_ty.subst(ccx.tcx(), psubsts);
101 debug!("mono_ty = {} (post-substitution)", mono_ty.repr(ccx.tcx()));
103 let mono_ty = normalize_associated_type(ccx.tcx(), &mono_ty);
104 debug!("mono_ty = {} (post-normalization)", mono_ty.repr(ccx.tcx()));
106 ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
110 let mut monomorphizing = ccx.monomorphizing().borrow_mut();
111 depth = match monomorphizing.get(&fn_id) {
112 Some(&d) => d, None => 0
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_id.node),
120 "reached the recursion limit during monomorphization");
123 monomorphizing.insert(fn_id, depth + 1);
128 let mut state = sip::SipState::new();
129 hash_id.hash(&mut state);
130 mono_ty.hash(&mut state);
132 hash = format!("h{}", state.result());
133 ccx.tcx().map.with_path(fn_id.node, |path| {
134 exported_name(path, hash[])
138 debug!("monomorphize_fn mangled to {}", s);
140 // This shouldn't need to option dance.
141 let mut hash_id = Some(hash_id);
142 let mut mk_lldecl = |&mut : abi: abi::Abi| {
143 let lldecl = if abi != abi::Rust {
144 foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, s[])
146 decl_internal_rust_fn(ccx, mono_ty, s[])
149 ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl);
152 let setup_lldecl = |&: lldecl, attrs: &[ast::Attribute]| {
153 base::update_linkage(ccx, lldecl, None, base::OriginalTranslation);
154 set_llvm_fn_attrs(ccx, attrs, lldecl);
156 let is_first = !ccx.available_monomorphizations().borrow().contains(&s);
158 ccx.available_monomorphizations().borrow_mut().insert(s.clone());
161 let trans_everywhere = attr::requests_inline(attrs);
162 if trans_everywhere && !is_first {
163 llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage);
166 // If `true`, then `lldecl` should be given a function body.
167 // Otherwise, it should be left as a declaration of an external
168 // function, with no definition in the current compilation unit.
169 trans_everywhere || is_first
172 let lldecl = match map_node {
173 ast_map::NodeItem(i) => {
176 node: ast::ItemFn(ref decl, _, abi, _, ref body),
179 let d = mk_lldecl(abi);
180 let needs_body = setup_lldecl(d, i.attrs[]);
182 if abi != abi::Rust {
183 foreign::trans_rust_fn_with_foreign_abi(
184 ccx, &**decl, &**body, &[], d, psubsts, fn_id.node,
187 trans_fn(ccx, &**decl, &**body, d, psubsts, fn_id.node, &[]);
194 ccx.sess().bug("Can't monomorphize this kind of item")
198 ast_map::NodeVariant(v) => {
199 let parent = ccx.tcx().map.get_parent(fn_id.node);
200 let tvs = ty::enum_variants(ccx.tcx(), local_def(parent));
201 let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
202 let d = mk_lldecl(abi::Rust);
205 ast::TupleVariantKind(ref args) => {
206 trans_enum_variant(ccx,
214 ast::StructVariantKind(_) =>
215 ccx.sess().bug("can't monomorphize struct variants"),
219 ast_map::NodeImplItem(ii) => {
221 ast::MethodImplItem(ref mth) => {
222 let d = mk_lldecl(abi::Rust);
223 let needs_body = setup_lldecl(d, mth.attrs[]);
235 ast::TypeImplItem(_) => {
236 ccx.sess().bug("can't monomorphize an associated type")
240 ast_map::NodeTraitItem(method) => {
242 ast::ProvidedMethod(ref mth) => {
243 let d = mk_lldecl(abi::Rust);
244 let needs_body = setup_lldecl(d, mth.attrs[]);
246 trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d,
247 psubsts, mth.id, &[]);
252 ccx.sess().bug(format!("can't monomorphize a {}",
257 ast_map::NodeStructCtor(struct_def) => {
258 let d = mk_lldecl(abi::Rust);
260 base::trans_tuple_struct(ccx,
262 struct_def.ctor_id.expect("ast-mapped tuple struct \
263 didn't have a ctor id"),
269 // Ugh -- but this ensures any new variants won't be forgotten
270 ast_map::NodeForeignItem(..) |
271 ast_map::NodeLifetime(..) |
272 ast_map::NodeExpr(..) |
273 ast_map::NodeStmt(..) |
274 ast_map::NodeArg(..) |
275 ast_map::NodeBlock(..) |
276 ast_map::NodePat(..) |
277 ast_map::NodeLocal(..) => {
278 ccx.sess().bug(format!("can't monomorphize a {}",
283 ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
285 debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
289 #[deriving(PartialEq, Eq, Hash, Show)]
290 pub struct MonoId<'tcx> {
292 pub params: subst::VecPerParamSpace<Ty<'tcx>>
295 /// Monomorphizes a type from the AST by first applying the in-scope
296 /// substitutions and then normalizing any associated types.
297 pub fn apply_param_substs<'tcx,T>(tcx: &ty::ctxt<'tcx>,
298 param_substs: &Substs<'tcx>,
301 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
303 assert!(param_substs.regions.is_erased());
305 let substituted = value.subst(tcx, param_substs);
306 normalize_associated_type(tcx, &substituted)
309 /// Removes associated types, if any. Since this during
310 /// monomorphization, we know that only concrete types are involved,
311 /// and hence we can be sure that all associated types will be
312 /// completely normalized away.
313 pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T
314 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
316 debug!("normalize_associated_type(t={})", value.repr(tcx));
318 if !value.has_projection_types() {
319 return value.clone();
322 // FIXME(#20304) -- cache
324 let infcx = infer::new_infer_ctxt(tcx);
325 let typer = NormalizingUnboxedClosureTyper::new(tcx);
326 let mut selcx = traits::SelectionContext::new(&infcx, &typer);
327 let cause = traits::ObligationCause::dummy();
328 let traits::Normalized { value: result, obligations } =
329 traits::normalize(&mut selcx, cause, value);
331 debug!("normalize_associated_type: result={} obligations={}",
333 obligations.repr(tcx));
335 let mut fulfill_cx = traits::FulfillmentContext::new();
336 for obligation in obligations.into_iter() {
337 fulfill_cx.register_predicate_obligation(&infcx, obligation);
339 let result = drain_fulfillment_cx(DUMMY_SP, &infcx, &mut fulfill_cx, &result);