1 // Copyright 2012-2014 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.
11 pub use self::ClosureKind::*;
14 use back::link::mangle_internal_name_by_path_and_seq;
17 use middle::mem_categorization::Typer;
21 use trans::cleanup::{CleanupMethods, ScopeId};
23 use trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
26 use trans::monomorphize::MonoId;
27 use trans::type_of::*;
28 use trans::type_::Type;
29 use middle::ty::{mod, Ty};
30 use middle::subst::{Subst, Substs};
31 use session::config::FullDebugInfo;
32 use util::ppaux::Repr;
33 use util::ppaux::ty_to_string;
35 use arena::TypedArena;
39 // ___Good to know (tm)__________________________________________________
41 // The layout of a closure environment in memory is
42 // roughly as follows:
44 // struct rust_opaque_box { // see rust_internal.h
45 // unsigned ref_count; // obsolete (part of @T's header)
46 // fn(void*) *drop_glue; // destructor (for proc)
47 // rust_opaque_box *prev; // obsolete (part of @T's header)
48 // rust_opaque_box *next; // obsolete (part of @T's header)
49 // struct closure_data {
56 // Note that the closure is itself a rust_opaque_box. This is true
57 // even for ~fn and ||, because we wish to keep binary compatibility
58 // between all kinds of closures. The allocation strategy for this
59 // closure depends on the closure type. For a sendfn, the closure
60 // (and the referenced type descriptors) will be allocated in the
61 // exchange heap. For a fn, the closure is allocated in the task heap
62 // and is reference counted. For a block, the closure is allocated on
65 // ## Opaque closures and the embedded type descriptor ##
67 // One interesting part of closures is that they encapsulate the data
68 // that they close over. So when I have a ptr to a closure, I do not
69 // know how many type descriptors it contains nor what upvars are
70 // captured within. That means I do not know precisely how big it is
71 // nor where its fields are located. This is called an "opaque
74 // Typically an opaque closure suffices because we only manipulate it
75 // by ptr. The routine Type::at_box().ptr_to() returns an appropriate
76 // type for such an opaque closure; it allows access to the box fields,
77 // but not the closure_data itself.
79 // But sometimes, such as when cloning or freeing a closure, we need
80 // to know the full information. That is where the type descriptor
81 // that defines the closure comes in handy. We can use its take and
82 // drop glue functions to allocate/free data as needed.
84 // ## Subtleties concerning alignment ##
86 // It is important that we be able to locate the closure data *without
87 // knowing the kind of data that is being bound*. This can be tricky
88 // because the alignment requirements of the bound data affects the
89 // alignment requires of the closure_data struct as a whole. However,
90 // right now this is a non-issue in any case, because the size of the
91 // rust_opaque_box header is always a multiple of 16-bytes, which is
92 // the maximum alignment requirement we ever have to worry about.
94 // The only reason alignment matters is that, in order to learn what data
95 // is bound, we would normally first load the type descriptors: but their
96 // location is ultimately depend on their content! There is, however, a
97 // workaround. We can load the tydesc from the rust_opaque_box, which
98 // describes the closure_data struct and has self-contained derived type
99 // descriptors, and read the alignment from there. It's just annoying to
100 // do. Hopefully should this ever become an issue we'll have monomorphized
101 // and type descriptors will all be a bad dream.
103 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
105 pub struct EnvValue<'tcx> {
106 action: ast::CaptureClause,
107 datum: Datum<'tcx, Lvalue>
110 impl<'tcx> Copy for EnvValue<'tcx> {}
112 impl<'tcx> EnvValue<'tcx> {
113 pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String {
114 format!("{}({})", self.action, self.datum.to_string(ccx))
118 // Given a closure ty, emits a corresponding tuple ty
119 pub fn mk_closure_tys<'tcx>(tcx: &ty::ctxt<'tcx>,
120 bound_values: &[EnvValue<'tcx>])
122 // determine the types of the values in the env. Note that this
123 // is the actual types that will be stored in the map, not the
124 // logical types as the user sees them, so by-ref upvars must be
125 // converted to ptrs.
126 let bound_tys = bound_values.iter().map(|bv| {
128 ast::CaptureByValue => bv.datum.ty,
129 ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
132 let cdata_ty = ty::mk_tup(tcx, bound_tys);
133 debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty));
137 fn tuplify_box_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
138 let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8());
139 ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t))
142 fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
143 store: ty::TraitStore,
145 -> Result<'blk, 'tcx> {
146 let _icx = push_ctxt("closure::allocate_cbox");
149 // Allocate and initialize the box:
150 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
152 ty::UniqTraitStore => {
153 malloc_raw_dyn_proc(bcx, cbox_ty)
155 ty::RegionTraitStore(..) => {
156 let llbox = alloc_ty(bcx, cbox_ty, "__closure");
157 Result::new(bcx, llbox)
162 pub struct ClosureResult<'blk, 'tcx: 'blk> {
163 llbox: ValueRef, // llvalue of ptr to closure
164 cdata_ty: Ty<'tcx>, // type of the closure data
165 bcx: Block<'blk, 'tcx> // final bcx
168 // Given a block context and a list of tydescs and values to bind
169 // construct a closure out of them. If copying is true, it is a
170 // heap allocated closure that copies the upvars into environment.
171 // Otherwise, it is stack allocated and copies pointers to the upvars.
172 pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
173 bound_values: Vec<EnvValue<'tcx>> ,
174 store: ty::TraitStore)
175 -> ClosureResult<'blk, 'tcx> {
176 let _icx = push_ctxt("closure::store_environment");
180 // compute the type of the closure
181 let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice());
183 // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
184 // tuple. This could be a ptr in uniq or a box or on stack,
186 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
187 let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
188 let llboxptr_ty = type_of(ccx, cboxptr_ty);
190 // If there are no bound values, no point in allocating anything.
191 if bound_values.is_empty() {
192 return ClosureResult {llbox: C_null(llboxptr_ty),
197 // allocate closure in the heap
198 let Result {bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty);
200 let llbox = PointerCast(bcx, llbox, llboxptr_ty);
201 debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty));
203 // Copy expr values into boxed bindings.
205 for (i, bv) in bound_values.into_iter().enumerate() {
206 debug!("Copy {} into closure", bv.to_string(ccx));
208 if ccx.sess().asm_comments() {
209 add_comment(bcx, format!("Copy {} into closure",
210 bv.to_string(ccx)).as_slice());
213 let bound_data = GEPi(bcx, llbox, &[0u, abi::BOX_FIELD_BODY, i]);
216 ast::CaptureByValue => {
217 bcx = bv.datum.store_to(bcx, bound_data);
219 ast::CaptureByRef => {
220 Store(bcx, bv.datum.to_llref(), bound_data);
225 ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
228 // Given a context and a list of upvars, build a closure. This just
229 // collects the upvars and packages them up for store_environment.
230 fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>,
231 freevar_mode: ast::CaptureClause,
232 freevars: &Vec<ty::Freevar>,
233 store: ty::TraitStore)
234 -> ClosureResult<'blk, 'tcx> {
235 let _icx = push_ctxt("closure::build_closure");
237 // If we need to, package up the iterator body to call
240 // Package up the captured upvars
241 let mut env_vals = Vec::new();
242 for freevar in freevars.iter() {
243 let datum = expr::trans_local_var(bcx, freevar.def);
244 env_vals.push(EnvValue {action: freevar_mode, datum: datum});
247 store_environment(bcx, env_vals, store)
250 // Given an enclosing block context, a new function context, a closure type,
251 // and a list of upvars, generate code to load and populate the environment
252 // with the upvars and type descriptors.
253 fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
255 freevars: &[ty::Freevar],
256 store: ty::TraitStore)
257 -> Block<'blk, 'tcx> {
258 let _icx = push_ctxt("closure::load_environment");
260 // Load a pointer to the closure data, skipping over the box header:
261 let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
263 // Store the pointer to closure data in an alloca for debug info because that's what the
264 // llvm.dbg.declare intrinsic expects
265 let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
266 let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
267 Store(bcx, llcdata, alloc);
273 // Populate the upvars from the environment
275 for freevar in freevars.iter() {
276 let mut upvarptr = GEPi(bcx, llcdata, &[0u, i]);
277 let captured_by_ref = match store {
278 ty::RegionTraitStore(..) => {
279 upvarptr = Load(bcx, upvarptr);
282 ty::UniqTraitStore => false
284 let def_id = freevar.def.def_id();
286 bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr);
287 if let Some(env_pointer_alloca) = env_pointer_alloca {
288 debuginfo::create_captured_var_metadata(
303 fn load_unboxed_closure_environment<'blk, 'tcx>(
304 bcx: Block<'blk, 'tcx>,
305 arg_scope_id: ScopeId,
306 freevar_mode: ast::CaptureClause,
307 freevars: &[ty::Freevar])
308 -> Block<'blk, 'tcx> {
309 let _icx = push_ctxt("closure::load_environment");
311 // Special case for small by-value selfs.
312 let closure_id = ast_util::local_def(bcx.fcx.id);
313 let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id,
314 node_id_type(bcx, closure_id.node));
315 let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id);
316 let llenv = if kind == ty::FnOnceUnboxedClosureKind &&
317 !arg_is_indirect(bcx.ccx(), self_type) {
318 let datum = rvalue_scratch_datum(bcx,
320 "unboxed_closure_env");
321 store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
324 bcx.fcx.llenv.unwrap()
327 // Store the pointer to closure data in an alloca for debug info because that's what the
328 // llvm.dbg.declare intrinsic expects
329 let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
330 let alloc = alloca(bcx, val_ty(llenv), "__debuginfo_env_ptr");
331 Store(bcx, llenv, alloc);
337 for (i, freevar) in freevars.iter().enumerate() {
338 let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
339 let captured_by_ref = match freevar_mode {
340 ast::CaptureByRef => {
341 upvar_ptr = Load(bcx, upvar_ptr);
344 ast::CaptureByValue => false
346 let def_id = freevar.def.def_id();
347 bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
349 if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue {
350 bcx.fcx.schedule_drop_mem(arg_scope_id,
352 node_id_type(bcx, def_id.node))
355 if let Some(env_pointer_alloca) = env_pointer_alloca {
356 debuginfo::create_captured_var_metadata(
369 fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
370 Store(bcx, llfn, GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]));
371 let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
372 Store(bcx, llenvptr, GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]));
375 #[deriving(PartialEq)]
376 pub enum ClosureKind<'tcx> {
378 // See load_environment.
379 BoxedClosure(Ty<'tcx>, ty::TraitStore),
380 // See load_unboxed_closure_environment.
381 UnboxedClosure(ast::CaptureClause)
384 pub struct ClosureEnv<'a, 'tcx> {
385 freevars: &'a [ty::Freevar],
386 pub kind: ClosureKind<'tcx>
389 impl<'a, 'tcx> ClosureEnv<'a, 'tcx> {
390 pub fn new(freevars: &'a [ty::Freevar], kind: ClosureKind<'tcx>)
391 -> ClosureEnv<'a, 'tcx> {
398 pub fn load<'blk>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
399 -> Block<'blk, 'tcx> {
400 // Don't bother to create the block if there's nothing to load
401 if self.freevars.is_empty() {
407 BoxedClosure(cdata_ty, store) => {
408 load_environment(bcx, cdata_ty, self.freevars, store)
410 UnboxedClosure(freevar_mode) => {
411 load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, self.freevars)
417 /// Translates the body of a closure expression.
422 /// - `id`: The id of the closure expression.
423 /// - `cap_clause`: information about captured variables, if any.
424 /// - `dest`: where to write the closure value, which must be a
425 /// (fn ptr, env) pair
426 pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
427 store: ty::TraitStore,
432 -> Block<'blk, 'tcx> {
433 let _icx = push_ctxt("closure::trans_expr_fn");
435 let dest_addr = match dest {
436 expr::SaveIn(p) => p,
438 return bcx; // closure construction is non-side-effecting
444 let fty = node_id_type(bcx, id);
445 let s = tcx.map.with_path(id, |path| {
446 mangle_internal_name_by_path_and_seq(path, "closure")
448 let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice());
450 // set an inline hint for all closures
451 set_inline_hint(llfn);
453 let freevar_mode = tcx.capture_mode(id);
454 let freevars: Vec<ty::Freevar> =
455 ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect());
461 } = build_closure(bcx, freevar_mode, &freevars, store);
467 bcx.fcx.param_substs,
472 ClosureEnv::new(freevars.as_slice(),
473 BoxedClosure(cdata_ty, store)));
474 fill_fn_pair(bcx, dest_addr, llfn, llbox);
478 /// Returns the LLVM function declaration for an unboxed closure, creating it
479 /// if necessary. If the ID does not correspond to a closure ID, returns None.
480 pub fn get_or_create_declaration_if_unboxed_closure<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
481 closure_id: ast::DefId,
482 substs: &Substs<'tcx>)
483 -> Option<ValueRef> {
485 if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
486 // Not an unboxed closure.
490 let function_type = ty::node_id_to_type(bcx.tcx(), closure_id.node);
491 let function_type = function_type.subst(bcx.tcx(), substs);
493 // Normalize type so differences in regions and typedefs don't cause
494 // duplicate declarations
495 let function_type = ty::normalize_ty(bcx.tcx(), function_type);
496 let params = match function_type.sty {
497 ty::ty_unboxed_closure(_, _, ref substs) => substs.types.clone(),
500 let mono_id = MonoId {
505 match ccx.unboxed_closure_vals().borrow().get(&mono_id) {
507 debug!("get_or_create_declaration_if_unboxed_closure(): found \
514 let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
515 mangle_internal_name_by_path_and_seq(path, "unboxed_closure")
518 let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice());
520 // set an inline hint for all closures
521 set_inline_hint(llfn);
523 debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \
524 closure {} (type {})",
526 ccx.tn().type_to_string(val_ty(llfn)));
527 ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn);
532 pub fn trans_unboxed_closure<'blk, 'tcx>(
533 mut bcx: Block<'blk, 'tcx>,
538 -> Block<'blk, 'tcx> {
539 let _icx = push_ctxt("closure::trans_unboxed_closure");
541 debug!("trans_unboxed_closure()");
543 let closure_id = ast_util::local_def(id);
544 let llfn = get_or_create_declaration_if_unboxed_closure(
547 bcx.fcx.param_substs).unwrap();
549 let function_type = (*bcx.tcx().unboxed_closures.borrow())[closure_id]
552 let function_type = ty::mk_closure(bcx.tcx(), function_type);
554 let freevars: Vec<ty::Freevar> =
555 ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect());
556 let freevar_mode = bcx.tcx().capture_mode(id);
558 trans_closure(bcx.ccx(),
562 bcx.fcx.param_substs,
565 ty::ty_fn_ret(function_type),
566 ty::ty_fn_abi(function_type),
567 ClosureEnv::new(freevars.as_slice(),
568 UnboxedClosure(freevar_mode)));
570 // Don't hoist this to the top of the function. It's perfectly legitimate
571 // to have a zero-size unboxed closure (in which case dest will be
572 // `Ignore`) and we must still generate the closure body.
573 let dest_addr = match dest {
574 expr::SaveIn(p) => p,
576 debug!("trans_unboxed_closure() ignoring result");
581 let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id));
583 // Create the closure.
584 for (i, freevar) in freevars.iter().enumerate() {
585 let datum = expr::trans_local_var(bcx, freevar.def);
586 let upvar_slot_dest = adt::trans_field_ptr(bcx,
592 ast::CaptureByValue => {
593 bcx = datum.store_to(bcx, upvar_slot_dest);
595 ast::CaptureByRef => {
596 Store(bcx, datum.to_llref(), upvar_slot_dest);
600 adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
605 pub fn get_wrapper_for_bare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
606 closure_ty: Ty<'tcx>,
609 is_local: bool) -> ValueRef {
611 let def_id = match def {
612 def::DefFn(did, _) | def::DefStaticMethod(did, _) |
613 def::DefVariant(_, did, _) | def::DefStruct(did) => did,
615 ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
616 expected a statically resolved fn, got \
622 match ccx.closure_bare_wrapper_cache().borrow().get(&fn_ptr) {
623 Some(&llval) => return llval,
629 debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
631 let f = match closure_ty.sty {
632 ty::ty_closure(ref f) => f,
634 ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
635 expected a closure ty, got {}",
636 closure_ty.repr(tcx)).as_slice());
640 let name = ty::with_path(tcx, def_id, |path| {
641 mangle_internal_name_by_path_and_seq(path, "as_closure")
643 let llfn = if is_local {
644 decl_internal_rust_fn(ccx, closure_ty, name.as_slice())
646 decl_rust_fn(ccx, closure_ty, name.as_slice())
649 ccx.closure_bare_wrapper_cache().borrow_mut().insert(fn_ptr, llfn);
651 // This is only used by statics inlined from a different crate.
653 // Don't regenerate the wrapper, just reuse the original one.
657 let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
659 let arena = TypedArena::new();
660 let empty_param_substs = Substs::trans_empty();
661 let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, true, f.sig.output,
662 &empty_param_substs, None, &arena);
663 let bcx = init_function(&fcx, true, f.sig.output);
665 let args = create_datums_for_fn_args(&fcx,
666 ty::ty_fn_args(closure_ty)
668 let mut llargs = Vec::new();
669 match fcx.llretslotptr.get() {
671 assert!(!fcx.needs_ret_allocas);
672 llargs.push(llretptr);
676 llargs.extend(args.iter().map(|arg| arg.val));
678 let retval = Call(bcx, fn_ptr, llargs.as_slice(), None);
680 ty::FnConverging(output_type) => {
681 if return_type_is_void(ccx, output_type) || fcx.llretslotptr.get().is_some() {
692 // HACK(eddyb) finish_fn cannot be used here, we returned directly.
693 debuginfo::clear_source_location(&fcx);
699 pub fn make_closure_from_bare_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
700 closure_ty: Ty<'tcx>,
703 -> DatumBlock<'blk, 'tcx, Expr> {
704 let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
705 let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def, fn_ptr, true);
706 fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p(bcx.ccx())));
708 DatumBlock::new(bcx, scratch.to_expr_datum())