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