]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/monomorphize.rs
auto merge of #15999 : Kimundi/rust/fix_folder, r=nikomatsakis
[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 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::ty;
22 use middle::typeck;
23 use util::ppaux::Repr;
24
25 use syntax::abi;
26 use syntax::ast;
27 use syntax::ast_map;
28 use syntax::ast_util::{local_def, PostExpansionMethod};
29 use std::hash::{sip, Hash};
30
31 pub fn monomorphic_fn(ccx: &CrateContext,
32                       fn_id: ast::DefId,
33                       real_substs: &subst::Substs,
34                       vtables: typeck::vtable_res,
35                       ref_id: Option<ast::NodeId>)
36     -> (ValueRef, bool) {
37     debug!("monomorphic_fn(\
38             fn_id={}, \
39             real_substs={}, \
40             vtables={}, \
41             ref_id={:?})",
42            fn_id.repr(ccx.tcx()),
43            real_substs.repr(ccx.tcx()),
44            vtables.repr(ccx.tcx()),
45            ref_id);
46
47     assert!(real_substs.types.all(|t| {
48         !ty::type_needs_infer(*t) && !ty::type_has_params(*t)
49     }));
50
51     let _icx = push_ctxt("monomorphic_fn");
52
53     let hash_id = MonoId {
54         def: fn_id,
55         params: real_substs.types.clone()
56     };
57
58     match ccx.monomorphized.borrow().find(&hash_id) {
59         Some(&val) => {
60             debug!("leaving monomorphic fn {}",
61             ty::item_path_str(ccx.tcx(), fn_id));
62             return (val, false);
63         }
64         None => ()
65     }
66
67     let psubsts = param_substs {
68         substs: (*real_substs).clone(),
69         vtables: vtables,
70     };
71
72     debug!("monomorphic_fn(\
73             fn_id={}, \
74             psubsts={}, \
75             hash_id={:?})",
76            fn_id.repr(ccx.tcx()),
77            psubsts.repr(ccx.tcx()),
78            hash_id);
79
80     let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
81     let llitem_ty = tpt.ty;
82
83     let map_node = session::expect(
84         ccx.sess(),
85         ccx.tcx.map.find(fn_id.node),
86         || {
87             format!("while monomorphizing {:?}, couldn't find it in \
88                      the item map (may have attempted to monomorphize \
89                      an item defined in a different crate?)",
90                     fn_id)
91         });
92
93     match map_node {
94         ast_map::NodeForeignItem(_) => {
95             if ccx.tcx.map.get_foreign_abi(fn_id.node) != abi::RustIntrinsic {
96                 // Foreign externs don't have to be monomorphized.
97                 return (get_item_val(ccx, fn_id.node), true);
98             }
99         }
100         _ => {}
101     }
102
103     debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
104     let mono_ty = llitem_ty.subst(ccx.tcx(), real_substs);
105
106     ccx.stats.n_monos.set(ccx.stats.n_monos.get() + 1);
107
108     let depth;
109     {
110         let mut monomorphizing = ccx.monomorphizing.borrow_mut();
111         depth = match monomorphizing.find(&fn_id) {
112             Some(&d) => d, None => 0
113         };
114
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");
121         }
122
123         monomorphizing.insert(fn_id, depth + 1);
124     }
125
126     let s = ccx.tcx.map.with_path(fn_id.node, |path| {
127         let mut state = sip::SipState::new();
128         hash_id.hash(&mut state);
129         mono_ty.hash(&mut state);
130
131         exported_name(path, format!("h{}", state.result()).as_slice())
132     });
133     debug!("monomorphize_fn mangled to {}", s);
134
135     // This shouldn't need to option dance.
136     let mut hash_id = Some(hash_id);
137     let mk_lldecl = || {
138         let lldecl = decl_internal_rust_fn(ccx, mono_ty, s.as_slice());
139         ccx.monomorphized.borrow_mut().insert(hash_id.take_unwrap(), lldecl);
140         lldecl
141     };
142
143     let lldecl = match map_node {
144         ast_map::NodeItem(i) => {
145             match *i {
146               ast::Item {
147                   node: ast::ItemFn(ref decl, _, _, _, ref body),
148                   ..
149               } => {
150                   let d = mk_lldecl();
151                   set_llvm_fn_attrs(i.attrs.as_slice(), d);
152                   trans_fn(ccx, &**decl, &**body, d, &psubsts, fn_id.node, [],
153                            IgnoreItems);
154                   d
155               }
156               _ => {
157                 ccx.sess().bug("Can't monomorphize this kind of item")
158               }
159             }
160         }
161         ast_map::NodeVariant(v) => {
162             let parent = ccx.tcx.map.get_parent(fn_id.node);
163             let tvs = ty::enum_variants(ccx.tcx(), local_def(parent));
164             let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
165             let d = mk_lldecl();
166             set_inline_hint(d);
167             match v.node.kind {
168                 ast::TupleVariantKind(ref args) => {
169                     trans_enum_variant(ccx,
170                                        parent,
171                                        &*v,
172                                        args.as_slice(),
173                                        this_tv.disr_val,
174                                        &psubsts,
175                                        d);
176                 }
177                 ast::StructVariantKind(_) =>
178                     ccx.sess().bug("can't monomorphize struct variants"),
179             }
180             d
181         }
182         ast_map::NodeMethod(mth) => {
183             let d = mk_lldecl();
184             set_llvm_fn_attrs(mth.attrs.as_slice(), d);
185             trans_fn(ccx, &*mth.pe_fn_decl(), &*mth.pe_body(), d, &psubsts, mth.id, [],
186                      IgnoreItems);
187             d
188         }
189         ast_map::NodeTraitMethod(method) => {
190             match *method {
191                 ast::Provided(mth) => {
192                     let d = mk_lldecl();
193                     set_llvm_fn_attrs(mth.attrs.as_slice(), d);
194                     trans_fn(ccx, &*mth.pe_fn_decl(), &*mth.pe_body(), d,
195                              &psubsts, mth.id, [], IgnoreItems);
196                     d
197                 }
198                 _ => {
199                     ccx.sess().bug(format!("can't monomorphize a {:?}",
200                                            map_node).as_slice())
201                 }
202             }
203         }
204         ast_map::NodeStructCtor(struct_def) => {
205             let d = mk_lldecl();
206             set_inline_hint(d);
207             base::trans_tuple_struct(ccx,
208                                      struct_def.fields.as_slice(),
209                                      struct_def.ctor_id.expect("ast-mapped tuple struct \
210                                                                 didn't have a ctor id"),
211                                      &psubsts,
212                                      d);
213             d
214         }
215
216         // Ugh -- but this ensures any new variants won't be forgotten
217         ast_map::NodeForeignItem(..) |
218         ast_map::NodeLifetime(..) |
219         ast_map::NodeExpr(..) |
220         ast_map::NodeStmt(..) |
221         ast_map::NodeArg(..) |
222         ast_map::NodeBlock(..) |
223         ast_map::NodePat(..) |
224         ast_map::NodeLocal(..) => {
225             ccx.sess().bug(format!("can't monomorphize a {:?}",
226                                    map_node).as_slice())
227         }
228     };
229
230     ccx.monomorphizing.borrow_mut().insert(fn_id, depth);
231
232     debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
233     (lldecl, false)
234 }
235
236 // Used to identify cached monomorphized functions and vtables
237 #[deriving(PartialEq, Eq, Hash)]
238 pub struct MonoParamId {
239     pub subst: ty::t,
240 }
241
242 #[deriving(PartialEq, Eq, Hash)]
243 pub struct MonoId {
244     pub def: ast::DefId,
245     pub params: subst::VecPerParamSpace<ty::t>
246 }
247
248 pub fn make_vtable_id(_ccx: &CrateContext,
249                       origin: &typeck::vtable_origin)
250                       -> MonoId {
251     match origin {
252         &typeck::vtable_static(impl_id, ref substs, _) => {
253             MonoId {
254                 def: impl_id,
255                 params: substs.types.clone()
256             }
257         }
258
259         &typeck::vtable_unboxed_closure(def_id) => {
260             MonoId {
261                 def: def_id,
262                 params: subst::VecPerParamSpace::empty(),
263             }
264         }
265
266         // can't this be checked at the callee?
267         _ => fail!("make_vtable_id needs vtable_static")
268     }
269 }