]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/monomorphize.rs
auto merge of #14813 : cmr/rust/once-docs-unsafe, r=alexcrichton
[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 use back::link::exported_name;
12 use driver::session;
13 use lib::llvm::ValueRef;
14 use middle::subst;
15 use middle::subst::Subst;
16 use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint};
17 use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val};
18 use middle::trans::base::{trans_fn, decl_internal_rust_fn};
19 use middle::trans::base;
20 use middle::trans::common::*;
21 use middle::trans::intrinsic;
22 use middle::ty;
23 use middle::typeck;
24 use util::ppaux::Repr;
25
26 use syntax::abi;
27 use syntax::ast;
28 use syntax::ast_map;
29 use syntax::ast_util::local_def;
30 use std::hash::{sip, Hash};
31
32 pub fn monomorphic_fn(ccx: &CrateContext,
33                       fn_id: ast::DefId,
34                       real_substs: &subst::Substs,
35                       vtables: typeck::vtable_res,
36                       self_vtables: Option<typeck::vtable_param_res>,
37                       ref_id: Option<ast::NodeId>)
38     -> (ValueRef, bool) {
39     debug!("monomorphic_fn(\
40             fn_id={}, \
41             real_substs={}, \
42             vtables={}, \
43             self_vtable={}, \
44             ref_id={:?})",
45            fn_id.repr(ccx.tcx()),
46            real_substs.repr(ccx.tcx()),
47            vtables.repr(ccx.tcx()),
48            self_vtables.repr(ccx.tcx()),
49            ref_id);
50
51     assert!(real_substs.tps.iter().all(|t| {
52         !ty::type_needs_infer(*t) && !ty::type_has_params(*t)
53     }));
54
55     let _icx = push_ctxt("monomorphic_fn");
56
57     let substs_iter = real_substs.self_ty.iter().chain(real_substs.tps.iter());
58     let param_ids: Vec<ty::t> = substs_iter.map(|t| *t).collect();
59     let hash_id = MonoId {
60         def: fn_id,
61         params: param_ids
62     };
63
64     match ccx.monomorphized.borrow().find(&hash_id) {
65         Some(&val) => {
66             debug!("leaving monomorphic fn {}",
67             ty::item_path_str(ccx.tcx(), fn_id));
68             return (val, false);
69         }
70         None => ()
71     }
72
73     let psubsts = param_substs {
74         substs: (*real_substs).clone(),
75         vtables: vtables,
76         self_vtables: self_vtables
77     };
78
79     debug!("monomorphic_fn(\
80             fn_id={}, \
81             psubsts={}, \
82             hash_id={:?})",
83            fn_id.repr(ccx.tcx()),
84            psubsts.repr(ccx.tcx()),
85            hash_id);
86
87     let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
88     let llitem_ty = tpt.ty;
89
90     // We need to do special handling of the substitutions if we are
91     // calling a static provided method. This is sort of unfortunate.
92     let mut is_static_provided = None;
93
94     let map_node = session::expect(
95         ccx.sess(),
96         ccx.tcx.map.find(fn_id.node),
97         || {
98             format!("while monomorphizing {:?}, couldn't find it in \
99                      the item map (may have attempted to monomorphize \
100                      an item defined in a different crate?)",
101                     fn_id)
102         });
103
104     match map_node {
105         ast_map::NodeForeignItem(_) => {
106             if ccx.tcx.map.get_foreign_abi(fn_id.node) != abi::RustIntrinsic {
107                 // Foreign externs don't have to be monomorphized.
108                 return (get_item_val(ccx, fn_id.node), true);
109             }
110         }
111         ast_map::NodeTraitMethod(method) => {
112             match *method {
113                 ast::Provided(m) => {
114                     // If this is a static provided method, indicate that
115                     // and stash the number of params on the method.
116                     if m.explicit_self.node == ast::SelfStatic {
117                         is_static_provided = Some(m.generics.ty_params.len());
118                     }
119                 }
120                 _ => {}
121             }
122         }
123         _ => {}
124     }
125
126     debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
127     let mono_ty = match is_static_provided {
128         None => llitem_ty.subst(ccx.tcx(), real_substs),
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 visible 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 = real_substs.tps.len() - num_method_ty_params;
145             let mut tps = Vec::new();
146             tps.push_all(real_substs.tps.slice(0, idx));
147             tps.push(real_substs.self_ty.unwrap());
148             tps.push_all(real_substs.tps.tailn(idx));
149
150             let substs = subst::Substs { regions: subst::ErasedRegions,
151                                          self_ty: None,
152                                          tps: tps };
153
154             debug!("static default: changed substitution to {}",
155                    substs.repr(ccx.tcx()));
156
157             llitem_ty.subst(ccx.tcx(), &substs)
158         }
159     };
160
161     ccx.stats.n_monos.set(ccx.stats.n_monos.get() + 1);
162
163     let depth;
164     {
165         let mut monomorphizing = ccx.monomorphizing.borrow_mut();
166         depth = match monomorphizing.find(&fn_id) {
167             Some(&d) => d, None => 0
168         };
169
170         // Random cut-off -- code that needs to instantiate the same function
171         // recursively more than thirty times can probably safely be assumed
172         // to be causing an infinite expansion.
173         if depth > ccx.sess().recursion_limit.get() {
174             ccx.sess().span_fatal(ccx.tcx.map.span(fn_id.node),
175                 "reached the recursion limit during monomorphization");
176         }
177
178         monomorphizing.insert(fn_id, depth + 1);
179     }
180
181     let s = ccx.tcx.map.with_path(fn_id.node, |path| {
182         let mut state = sip::SipState::new();
183         hash_id.hash(&mut state);
184         mono_ty.hash(&mut state);
185
186         exported_name(path,
187                       format!("h{}", state.result()).as_slice(),
188                       ccx.link_meta.crateid.version_or_default())
189     });
190     debug!("monomorphize_fn mangled to {}", s);
191
192     // This shouldn't need to option dance.
193     let mut hash_id = Some(hash_id);
194     let mk_lldecl = || {
195         let lldecl = decl_internal_rust_fn(ccx, mono_ty, s.as_slice());
196         ccx.monomorphized.borrow_mut().insert(hash_id.take_unwrap(), lldecl);
197         lldecl
198     };
199
200     let lldecl = match map_node {
201         ast_map::NodeItem(i) => {
202             match *i {
203               ast::Item {
204                   node: ast::ItemFn(ref decl, _, _, _, ref body),
205                   ..
206               } => {
207                   let d = mk_lldecl();
208                   set_llvm_fn_attrs(i.attrs.as_slice(), d);
209                   trans_fn(ccx, &**decl, &**body, d, &psubsts, fn_id.node, []);
210                   d
211               }
212               _ => {
213                 ccx.sess().bug("Can't monomorphize this kind of item")
214               }
215             }
216         }
217         ast_map::NodeForeignItem(i) => {
218             let simple = intrinsic::get_simple_intrinsic(ccx, &*i);
219             match simple {
220                 Some(decl) => decl,
221                 None => {
222                     let d = mk_lldecl();
223                     intrinsic::trans_intrinsic(ccx, d, &*i, &psubsts, ref_id);
224                     d
225                 }
226             }
227         }
228         ast_map::NodeVariant(v) => {
229             let parent = ccx.tcx.map.get_parent(fn_id.node);
230             let tvs = ty::enum_variants(ccx.tcx(), local_def(parent));
231             let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
232             let d = mk_lldecl();
233             set_inline_hint(d);
234             match v.node.kind {
235                 ast::TupleVariantKind(ref args) => {
236                     trans_enum_variant(ccx,
237                                        parent,
238                                        &*v,
239                                        args.as_slice(),
240                                        this_tv.disr_val,
241                                        &psubsts,
242                                        d);
243                 }
244                 ast::StructVariantKind(_) =>
245                     ccx.sess().bug("can't monomorphize struct variants"),
246             }
247             d
248         }
249         ast_map::NodeMethod(mth) => {
250             let d = mk_lldecl();
251             set_llvm_fn_attrs(mth.attrs.as_slice(), d);
252             trans_fn(ccx, &*mth.decl, &*mth.body, d, &psubsts, mth.id, []);
253             d
254         }
255         ast_map::NodeTraitMethod(method) => {
256             match *method {
257                 ast::Provided(mth) => {
258                     let d = mk_lldecl();
259                     set_llvm_fn_attrs(mth.attrs.as_slice(), d);
260                     trans_fn(ccx, &*mth.decl, &*mth.body, d, &psubsts, mth.id, []);
261                     d
262                 }
263                 _ => {
264                     ccx.sess().bug(format!("can't monomorphize a {:?}",
265                                            map_node).as_slice())
266                 }
267             }
268         }
269         ast_map::NodeStructCtor(struct_def) => {
270             let d = mk_lldecl();
271             set_inline_hint(d);
272             base::trans_tuple_struct(ccx,
273                                      struct_def.fields.as_slice(),
274                                      struct_def.ctor_id.expect("ast-mapped tuple struct \
275                                                                 didn't have a ctor id"),
276                                      &psubsts,
277                                      d);
278             d
279         }
280
281         // Ugh -- but this ensures any new variants won't be forgotten
282         ast_map::NodeLifetime(..) |
283         ast_map::NodeExpr(..) |
284         ast_map::NodeStmt(..) |
285         ast_map::NodeArg(..) |
286         ast_map::NodeBlock(..) |
287         ast_map::NodePat(..) |
288         ast_map::NodeLocal(..) => {
289             ccx.sess().bug(format!("can't monomorphize a {:?}",
290                                    map_node).as_slice())
291         }
292     };
293
294     ccx.monomorphizing.borrow_mut().insert(fn_id, depth);
295
296     debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
297     (lldecl, false)
298 }
299
300 // Used to identify cached monomorphized functions and vtables
301 #[deriving(PartialEq, Eq, Hash)]
302 pub struct MonoParamId {
303     pub subst: ty::t,
304 }
305
306 #[deriving(PartialEq, Eq, Hash)]
307 pub struct MonoId {
308     pub def: ast::DefId,
309     pub params: Vec<ty::t>
310 }
311
312 pub fn make_vtable_id(_ccx: &CrateContext,
313                       origin: &typeck::vtable_origin)
314                       -> MonoId {
315     match origin {
316         &typeck::vtable_static(impl_id, ref substs, _) => {
317             MonoId {
318                 def: impl_id,
319                 params: substs.tps.iter().map(|subst| *subst).collect()
320             }
321         }
322
323         // can't this be checked at the callee?
324         _ => fail!("make_vtable_id needs vtable_static")
325     }
326 }