]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/monomorphize.rs
librustc: Automatically change uses of `~[T]` to `Vec<T>` in rustc.
[rust.git] / src / librustc / middle / trans / monomorphize.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
12 use back::link::mangle_exported_name;
13 use driver::session;
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;
22 use middle::ty;
23 use middle::typeck;
24 use util::ppaux::Repr;
25
26 use syntax::ast;
27 use syntax::ast_map;
28 use syntax::ast_util::local_def;
29
30 pub fn monomorphic_fn(ccx: @CrateContext,
31                       fn_id: ast::DefId,
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>)
36     -> (ValueRef, bool) {
37     debug!("monomorphic_fn(\
38             fn_id={}, \
39             real_substs={}, \
40             vtables={}, \
41             self_vtable={}, \
42             ref_id={:?})",
43            fn_id.repr(ccx.tcx),
44            real_substs.repr(ccx.tcx),
45            vtables.repr(ccx.tcx),
46            self_vtables.repr(ccx.tcx),
47            ref_id);
48
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;
52
53     let psubsts = @param_substs {
54         tys: real_substs.tps.to_owned(),
55         vtables: vtables,
56         self_ty: real_substs.self_ty.clone(),
57         self_vtables: self_vtables
58     };
59
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)); }
62
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 }) {
66         must_cast = true;
67     }
68
69     debug!("monomorphic_fn(\
70             fn_id={}, \
71             psubsts={}, \
72             hash_id={:?})",
73            fn_id.repr(ccx.tcx),
74            psubsts.repr(ccx.tcx),
75            hash_id);
76
77     {
78         let monomorphized = ccx.monomorphized.borrow();
79         match monomorphized.get().find(&hash_id) {
80           Some(&val) => {
81             debug!("leaving monomorphic fn {}",
82                    ty::item_path_str(ccx.tcx, fn_id));
83             return (val, must_cast);
84           }
85           None => ()
86         }
87     }
88
89     let tpt = ty::lookup_item_type(ccx.tcx, fn_id);
90     let llitem_ty = tpt.ty;
91
92     // We need to do special handling of the substitutions if we are
93     // calling a static provided method. This is sort of unfortunate.
94     let mut is_static_provided = None;
95
96     let map_node = session::expect(
97         ccx.sess,
98         ccx.tcx.map.find(fn_id.node),
99         || format!("while monomorphizing {:?}, couldn't find it in the \
100                     item map (may have attempted to monomorphize an item \
101                     defined in a different crate?)", fn_id));
102
103     match map_node {
104         ast_map::NodeForeignItem(_) => {
105             if !ccx.tcx.map.get_foreign_abis(fn_id.node).is_intrinsic() {
106                 // Foreign externs don't have to be monomorphized.
107                 return (get_item_val(ccx, fn_id.node), true);
108             }
109         }
110         ast_map::NodeTraitMethod(method) => {
111             match *method {
112                 ast::Provided(m) => {
113                     // If this is a static provided method, indicate that
114                     // and stash the number of params on the method.
115                     if m.explicit_self.node == ast::SelfStatic {
116                         is_static_provided = Some(m.generics.ty_params.len());
117                     }
118                 }
119                 _ => {}
120             }
121         }
122         _ => {}
123     }
124
125     debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx));
126     let mono_ty = match is_static_provided {
127         None => ty::subst_tps(ccx.tcx, psubsts.tys,
128                               psubsts.self_ty, llitem_ty),
129         Some(num_method_ty_params) => {
130             // Static default methods are a little unfortunate, in
131             // that the "internal" and "external" type of them differ.
132             // Internally, the method body can refer to Self, but the
133             // externally visable type of the method has a type param
134             // inserted in between the trait type params and the
135             // method type params. The substs that we are given are
136             // the proper substs *internally* to the method body, so
137             // we have to use those when compiling it.
138             //
139             // In order to get the proper substitution to use on the
140             // type of the method, we pull apart the substitution and
141             // stick a substitution for the self type in.
142             // This is a bit unfortunate.
143
144             let idx = psubsts.tys.len() - num_method_ty_params;
145             let substs = psubsts.tys.slice(0, idx) +
146                 &[psubsts.self_ty.unwrap()] + psubsts.tys.tailn(idx);
147             debug!("static default: changed substitution to {}",
148                    substs.repr(ccx.tcx));
149
150             ty::subst_tps(ccx.tcx, substs, None, llitem_ty)
151         }
152     };
153
154     let f = match ty::get(mono_ty).sty {
155         ty::ty_bare_fn(ref f) => {
156             assert!(f.abis.is_rust() || f.abis.is_intrinsic());
157             f
158         }
159         _ => fail!("expected bare rust fn or an intrinsic")
160     };
161
162     ccx.stats.n_monos.set(ccx.stats.n_monos.get() + 1);
163
164     let depth;
165     {
166         let mut monomorphizing = ccx.monomorphizing.borrow_mut();
167         depth = match monomorphizing.get().find(&fn_id) {
168             Some(&d) => d, None => 0
169         };
170
171         // Random cut-off -- code that needs to instantiate the same function
172         // recursively more than thirty times can probably safely be assumed
173         // to be causing an infinite expansion.
174         if depth > 30 {
175             ccx.sess.span_fatal(
176                 ccx.tcx.map.span(fn_id.node),
177                 "overly deep expansion of inlined function");
178         }
179         monomorphizing.get().insert(fn_id, depth + 1);
180     }
181
182     let s = ccx.tcx.map.with_path(fn_id.node, |path| {
183         mangle_exported_name(ccx, path, mono_ty, fn_id.node)
184     });
185     debug!("monomorphize_fn mangled to {}", s);
186
187     let mk_lldecl = || {
188         let lldecl = decl_internal_rust_fn(ccx, false,
189                                            f.sig.inputs,
190                                            f.sig.output, s);
191         let mut monomorphized = ccx.monomorphized.borrow_mut();
192         monomorphized.get().insert(hash_id, lldecl);
193         lldecl
194     };
195
196     let lldecl = match map_node {
197         ast_map::NodeItem(i) => {
198             match *i {
199               ast::Item {
200                   node: ast::ItemFn(decl, _, _, _, body),
201                   ..
202               } => {
203                   let d = mk_lldecl();
204                   set_llvm_fn_attrs(i.attrs.as_slice(), d);
205                   trans_fn(ccx, decl, body, d, Some(psubsts), fn_id.node, []);
206                   d
207               }
208               _ => {
209                 ccx.tcx.sess.bug("Can't monomorphize this kind of item")
210               }
211             }
212         }
213         ast_map::NodeForeignItem(i) => {
214             let simple = intrinsic::get_simple_intrinsic(ccx, i);
215             match simple {
216                 Some(decl) => decl,
217                 None => {
218                     let d = mk_lldecl();
219                     intrinsic::trans_intrinsic(ccx, d, i, psubsts, ref_id);
220                     d
221                 }
222             }
223         }
224         ast_map::NodeVariant(v) => {
225             let parent = ccx.tcx.map.get_parent(fn_id.node);
226             let tvs = ty::enum_variants(ccx.tcx, local_def(parent));
227             let this_tv = *tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
228             let d = mk_lldecl();
229             set_inline_hint(d);
230             match v.node.kind {
231                 ast::TupleVariantKind(ref args) => {
232                     trans_enum_variant(ccx,
233                                        parent,
234                                        v,
235                                        args.as_slice(),
236                                        this_tv.disr_val,
237                                        Some(psubsts),
238                                        d);
239                 }
240                 ast::StructVariantKind(_) =>
241                     ccx.tcx.sess.bug("can't monomorphize struct variants"),
242             }
243             d
244         }
245         ast_map::NodeMethod(mth) => {
246             let d = mk_lldecl();
247             set_llvm_fn_attrs(mth.attrs.as_slice(), d);
248             trans_fn(ccx, mth.decl, mth.body, d, Some(psubsts), mth.id, []);
249             d
250         }
251         ast_map::NodeTraitMethod(method) => {
252             match *method {
253                 ast::Provided(mth) => {
254                     let d = mk_lldecl();
255                     set_llvm_fn_attrs(mth.attrs.as_slice(), d);
256                     trans_fn(ccx, mth.decl, mth.body, d, Some(psubsts), mth.id, []);
257                     d
258                 }
259                 _ => {
260                     ccx.tcx.sess.bug(format!("can't monomorphize a {:?}",
261                                              map_node))
262                 }
263             }
264         }
265         ast_map::NodeStructCtor(struct_def) => {
266             let d = mk_lldecl();
267             set_inline_hint(d);
268             base::trans_tuple_struct(ccx,
269                                      struct_def.fields.as_slice(),
270                                      struct_def.ctor_id.expect("ast-mapped tuple struct \
271                                                                 didn't have a ctor id"),
272                                      Some(psubsts),
273                                      d);
274             d
275         }
276
277         // Ugh -- but this ensures any new variants won't be forgotten
278         ast_map::NodeExpr(..) |
279         ast_map::NodeStmt(..) |
280         ast_map::NodeArg(..) |
281         ast_map::NodeBlock(..) |
282         ast_map::NodeLocal(..) => {
283             ccx.tcx.sess.bug(format!("can't monomorphize a {:?}", map_node))
284         }
285     };
286
287     {
288         let mut monomorphizing = ccx.monomorphizing.borrow_mut();
289         monomorphizing.get().insert(fn_id, depth);
290     }
291
292     debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx, fn_id));
293     (lldecl, must_cast)
294 }
295
296 pub fn make_mono_id(ccx: @CrateContext,
297                     item: ast::DefId,
298                     substs: &param_substs) -> mono_id {
299     // FIXME (possibly #5801): Need a lot of type hints to get
300     // .collect() to work.
301     let substs_iter = substs.self_ty.iter().chain(substs.tys.iter());
302     let precise_param_ids: Vec<(ty::t, Option<@Vec<mono_id> >)> = match substs.vtables {
303       Some(vts) => {
304         debug!("make_mono_id vtables={} substs={}",
305                vts.repr(ccx.tcx), substs.tys.repr(ccx.tcx));
306         let vts_iter = substs.self_vtables.iter().chain(vts.iter());
307         vts_iter.zip(substs_iter).map(|(vtable, subst)| {
308             let v = vtable.map(|vt| meth::vtable_id(ccx, vt));
309             (*subst, if !v.is_empty() { Some(@v) } else { None })
310         }).collect()
311       }
312       None => substs_iter.map(|subst| (*subst, None::<@Vec<mono_id> >)).collect()
313     };
314
315
316     let param_ids = precise_param_ids.iter().map(|x| {
317         let (a, b) = *x;
318         mono_precise(a, b)
319     }).collect();
320     @mono_id_ {def: item, params: param_ids}
321 }