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.
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.
12 use back::link::mangle_exported_name;
14 use lib::llvm::ValueRef;
15 use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint};
16 use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val};
17 use middle::trans::base::{trans_fn, decl_internal_rust_fn};
18 use middle::trans::base;
19 use middle::trans::common::*;
20 use middle::trans::meth;
21 use middle::trans::intrinsic;
24 use util::ppaux::Repr;
28 use syntax::ast_util::local_def;
30 pub fn monomorphic_fn(ccx: &CrateContext,
32 real_substs: &ty::substs,
33 vtables: Option<typeck::vtable_res>,
34 self_vtables: Option<typeck::vtable_param_res>,
35 ref_id: Option<ast::NodeId>)
37 debug!("monomorphic_fn(\
43 fn_id.repr(ccx.tcx()),
44 real_substs.repr(ccx.tcx()),
45 vtables.repr(ccx.tcx()),
46 self_vtables.repr(ccx.tcx()),
49 assert!(real_substs.tps.iter().all(|t| !ty::type_needs_infer(*t)));
50 let _icx = push_ctxt("monomorphic_fn");
51 let mut must_cast = false;
53 let psubsts = @param_substs {
54 tys: real_substs.tps.clone(),
56 self_ty: real_substs.self_ty.clone(),
57 self_vtables: self_vtables
60 for s in real_substs.tps.iter() { assert!(!ty::type_has_params(*s)); }
61 for s in psubsts.tys.iter() { assert!(!ty::type_has_params(*s)); }
63 let hash_id = make_mono_id(ccx, fn_id, &*psubsts);
64 if hash_id.params.iter().any(
65 |p| match *p { mono_precise(_, _) => false, _ => true }) {
69 debug!("monomorphic_fn(\
73 fn_id.repr(ccx.tcx()),
74 psubsts.repr(ccx.tcx()),
77 match ccx.monomorphized.borrow().find(&hash_id) {
79 debug!("leaving monomorphic fn {}",
80 ty::item_path_str(ccx.tcx(), fn_id));
81 return (val, must_cast);
86 let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
87 let llitem_ty = tpt.ty;
89 // We need to do special handling of the substitutions if we are
90 // calling a static provided method. This is sort of unfortunate.
91 let mut is_static_provided = None;
93 let map_node = session::expect(
95 ccx.tcx.map.find(fn_id.node),
96 || format!("while monomorphizing {:?}, couldn't find it in the \
97 item map (may have attempted to monomorphize an item \
98 defined in a different crate?)", fn_id));
101 ast_map::NodeForeignItem(_) => {
102 if !ccx.tcx.map.get_foreign_abis(fn_id.node).is_intrinsic() {
103 // Foreign externs don't have to be monomorphized.
104 return (get_item_val(ccx, fn_id.node), true);
107 ast_map::NodeTraitMethod(method) => {
109 ast::Provided(m) => {
110 // If this is a static provided method, indicate that
111 // and stash the number of params on the method.
112 if m.explicit_self.node == ast::SelfStatic {
113 is_static_provided = Some(m.generics.ty_params.len());
122 debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
123 let mono_ty = match is_static_provided {
124 None => ty::subst_tps(ccx.tcx(), psubsts.tys.as_slice(),
125 psubsts.self_ty, llitem_ty),
126 Some(num_method_ty_params) => {
127 // Static default methods are a little unfortunate, in
128 // that the "internal" and "external" type of them differ.
129 // Internally, the method body can refer to Self, but the
130 // externally visable type of the method has a type param
131 // inserted in between the trait type params and the
132 // method type params. The substs that we are given are
133 // the proper substs *internally* to the method body, so
134 // we have to use those when compiling it.
136 // In order to get the proper substitution to use on the
137 // type of the method, we pull apart the substitution and
138 // stick a substitution for the self type in.
139 // This is a bit unfortunate.
141 let idx = psubsts.tys.len() - num_method_ty_params;
142 let substs = psubsts.tys.slice(0, idx) +
143 &[psubsts.self_ty.unwrap()] + psubsts.tys.tailn(idx);
144 debug!("static default: changed substitution to {}",
145 substs.repr(ccx.tcx()));
147 ty::subst_tps(ccx.tcx(), substs, None, llitem_ty)
151 let f = match ty::get(mono_ty).sty {
152 ty::ty_bare_fn(ref f) => {
153 assert!(f.abis.is_rust() || f.abis.is_intrinsic());
156 _ => fail!("expected bare rust fn or an intrinsic")
159 ccx.stats.n_monos.set(ccx.stats.n_monos.get() + 1);
163 let mut monomorphizing = ccx.monomorphizing.borrow_mut();
164 depth = match monomorphizing.find(&fn_id) {
165 Some(&d) => d, None => 0
168 // Random cut-off -- code that needs to instantiate the same function
169 // recursively more than thirty times can probably safely be assumed
170 // to be causing an infinite expansion.
171 if depth > ccx.sess().recursion_limit.get() {
172 ccx.sess().span_fatal(ccx.tcx.map.span(fn_id.node),
173 "reached the recursion limit during monomorphization");
176 monomorphizing.insert(fn_id, depth + 1);
179 let s = ccx.tcx.map.with_path(fn_id.node, |path| {
180 mangle_exported_name(ccx, path, mono_ty, fn_id.node)
182 debug!("monomorphize_fn mangled to {}", s);
185 let lldecl = decl_internal_rust_fn(ccx, false,
186 f.sig.inputs.as_slice(),
188 ccx.monomorphized.borrow_mut().insert(hash_id, lldecl);
192 let lldecl = match map_node {
193 ast_map::NodeItem(i) => {
196 node: ast::ItemFn(decl, _, _, _, body),
200 set_llvm_fn_attrs(i.attrs.as_slice(), d);
201 trans_fn(ccx, decl, body, d, Some(psubsts), fn_id.node, []);
205 ccx.sess().bug("Can't monomorphize this kind of item")
209 ast_map::NodeForeignItem(i) => {
210 let simple = intrinsic::get_simple_intrinsic(ccx, i);
215 intrinsic::trans_intrinsic(ccx, d, i, psubsts, ref_id);
220 ast_map::NodeVariant(v) => {
221 let parent = ccx.tcx.map.get_parent(fn_id.node);
222 let tvs = ty::enum_variants(ccx.tcx(), local_def(parent));
223 let this_tv = *tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
227 ast::TupleVariantKind(ref args) => {
228 trans_enum_variant(ccx,
236 ast::StructVariantKind(_) =>
237 ccx.sess().bug("can't monomorphize struct variants"),
241 ast_map::NodeMethod(mth) => {
243 set_llvm_fn_attrs(mth.attrs.as_slice(), d);
244 trans_fn(ccx, mth.decl, mth.body, d, Some(psubsts), mth.id, []);
247 ast_map::NodeTraitMethod(method) => {
249 ast::Provided(mth) => {
251 set_llvm_fn_attrs(mth.attrs.as_slice(), d);
252 trans_fn(ccx, mth.decl, mth.body, d, Some(psubsts), mth.id, []);
256 ccx.sess().bug(format!("can't monomorphize a {:?}",
261 ast_map::NodeStructCtor(struct_def) => {
264 base::trans_tuple_struct(ccx,
265 struct_def.fields.as_slice(),
266 struct_def.ctor_id.expect("ast-mapped tuple struct \
267 didn't have a ctor id"),
273 // Ugh -- but this ensures any new variants won't be forgotten
274 ast_map::NodeExpr(..) |
275 ast_map::NodeStmt(..) |
276 ast_map::NodeArg(..) |
277 ast_map::NodeBlock(..) |
278 ast_map::NodeLocal(..) => {
279 ccx.sess().bug(format!("can't monomorphize a {:?}", map_node))
283 ccx.monomorphizing.borrow_mut().insert(fn_id, depth);
285 debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
289 pub fn make_mono_id(ccx: &CrateContext,
291 substs: ¶m_substs) -> mono_id {
292 // FIXME (possibly #5801): Need a lot of type hints to get
293 // .collect() to work.
294 let substs_iter = substs.self_ty.iter().chain(substs.tys.iter());
295 let precise_param_ids: Vec<(ty::t, Option<@Vec<mono_id> >)> = match substs.vtables {
297 debug!("make_mono_id vtables={} substs={}",
298 vts.repr(ccx.tcx()), substs.tys.repr(ccx.tcx()));
299 let vts_iter = substs.self_vtables.iter().chain(vts.iter());
300 vts_iter.zip(substs_iter).map(|(vtable, subst)| {
301 let v = vtable.map(|vt| meth::vtable_id(ccx, vt));
302 (*subst, if !v.is_empty() { Some(@v) } else { None })
305 None => substs_iter.map(|subst| (*subst, None::<@Vec<mono_id> >)).collect()
309 let param_ids = precise_param_ids.iter().map(|x| {
313 @mono_id_ {def: item, params: param_ids}