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.
13 use back::link::mangle_internal_name_by_path_and_seq;
14 use driver::config::FullDebugInfo;
17 use middle::mem_categorization::Typer;
18 use middle::trans::adt;
19 use middle::trans::base::*;
20 use middle::trans::build::*;
21 use middle::trans::cleanup::{CleanupMethods, ScopeId};
22 use middle::trans::common::*;
23 use middle::trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
24 use middle::trans::debuginfo;
25 use middle::trans::expr;
26 use middle::trans::monomorphize::MonoId;
27 use middle::trans::type_of::*;
28 use middle::trans::type_::Type;
30 use util::ppaux::Repr;
31 use util::ppaux::ty_to_string;
33 use arena::TypedArena;
37 // ___Good to know (tm)__________________________________________________
39 // The layout of a closure environment in memory is
40 // roughly as follows:
42 // struct rust_opaque_box { // see rust_internal.h
43 // unsigned ref_count; // obsolete (part of @T's header)
44 // fn(void*) *drop_glue; // destructor (for proc)
45 // rust_opaque_box *prev; // obsolete (part of @T's header)
46 // rust_opaque_box *next; // obsolete (part of @T's header)
47 // struct closure_data {
54 // Note that the closure is itself a rust_opaque_box. This is true
55 // even for ~fn and ||, because we wish to keep binary compatibility
56 // between all kinds of closures. The allocation strategy for this
57 // closure depends on the closure type. For a sendfn, the closure
58 // (and the referenced type descriptors) will be allocated in the
59 // exchange heap. For a fn, the closure is allocated in the task heap
60 // and is reference counted. For a block, the closure is allocated on
63 // ## Opaque closures and the embedded type descriptor ##
65 // One interesting part of closures is that they encapsulate the data
66 // that they close over. So when I have a ptr to a closure, I do not
67 // know how many type descriptors it contains nor what upvars are
68 // captured within. That means I do not know precisely how big it is
69 // nor where its fields are located. This is called an "opaque
72 // Typically an opaque closure suffices because we only manipulate it
73 // by ptr. The routine Type::at_box().ptr_to() returns an appropriate
74 // type for such an opaque closure; it allows access to the box fields,
75 // but not the closure_data itself.
77 // But sometimes, such as when cloning or freeing a closure, we need
78 // to know the full information. That is where the type descriptor
79 // that defines the closure comes in handy. We can use its take and
80 // drop glue functions to allocate/free data as needed.
82 // ## Subtleties concerning alignment ##
84 // It is important that we be able to locate the closure data *without
85 // knowing the kind of data that is being bound*. This can be tricky
86 // because the alignment requirements of the bound data affects the
87 // alignment requires of the closure_data struct as a whole. However,
88 // right now this is a non-issue in any case, because the size of the
89 // rust_opaque_box header is always a multiple of 16-bytes, which is
90 // the maximum alignment requirement we ever have to worry about.
92 // The only reason alignment matters is that, in order to learn what data
93 // is bound, we would normally first load the type descriptors: but their
94 // location is ultimately depend on their content! There is, however, a
95 // workaround. We can load the tydesc from the rust_opaque_box, which
96 // describes the closure_data struct and has self-contained derived type
97 // descriptors, and read the alignment from there. It's just annoying to
98 // do. Hopefully should this ever become an issue we'll have monomorphized
99 // and type descriptors will all be a bad dream.
101 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103 pub struct EnvValue {
104 action: ast::CaptureClause,
109 pub fn to_string(&self, ccx: &CrateContext) -> String {
110 format!("{}({})", self.action, self.datum.to_string(ccx))
114 // Given a closure ty, emits a corresponding tuple ty
115 pub fn mk_closure_tys(tcx: &ty::ctxt,
116 bound_values: &[EnvValue])
118 // determine the types of the values in the env. Note that this
119 // is the actual types that will be stored in the map, not the
120 // logical types as the user sees them, so by-ref upvars must be
121 // converted to ptrs.
122 let bound_tys = bound_values.iter().map(|bv| {
124 ast::CaptureByValue => bv.datum.ty,
125 ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
128 let cdata_ty = ty::mk_tup(tcx, bound_tys);
129 debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty));
133 fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t {
134 let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8());
135 ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t))
138 fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
139 store: ty::TraitStore,
141 -> Result<'blk, 'tcx> {
142 let _icx = push_ctxt("closure::allocate_cbox");
145 // Allocate and initialize the box:
146 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
148 ty::UniqTraitStore => {
149 malloc_raw_dyn_proc(bcx, cbox_ty)
151 ty::RegionTraitStore(..) => {
152 let llbox = alloc_ty(bcx, cbox_ty, "__closure");
153 Result::new(bcx, llbox)
158 pub struct ClosureResult<'blk, 'tcx: 'blk> {
159 llbox: ValueRef, // llvalue of ptr to closure
160 cdata_ty: ty::t, // type of the closure data
161 bcx: Block<'blk, 'tcx> // final bcx
164 // Given a block context and a list of tydescs and values to bind
165 // construct a closure out of them. If copying is true, it is a
166 // heap allocated closure that copies the upvars into environment.
167 // Otherwise, it is stack allocated and copies pointers to the upvars.
168 pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
169 bound_values: Vec<EnvValue> ,
170 store: ty::TraitStore)
171 -> ClosureResult<'blk, 'tcx> {
172 let _icx = push_ctxt("closure::store_environment");
176 // compute the type of the closure
177 let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice());
179 // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
180 // tuple. This could be a ptr in uniq or a box or on stack,
182 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
183 let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
184 let llboxptr_ty = type_of(ccx, cboxptr_ty);
186 // If there are no bound values, no point in allocating anything.
187 if bound_values.is_empty() {
188 return ClosureResult {llbox: C_null(llboxptr_ty),
193 // allocate closure in the heap
194 let Result {bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty);
196 let llbox = PointerCast(bcx, llbox, llboxptr_ty);
197 debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty));
199 // Copy expr values into boxed bindings.
201 for (i, bv) in bound_values.into_iter().enumerate() {
202 debug!("Copy {} into closure", bv.to_string(ccx));
204 if ccx.sess().asm_comments() {
205 add_comment(bcx, format!("Copy {} into closure",
206 bv.to_string(ccx)).as_slice());
209 let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]);
212 ast::CaptureByValue => {
213 bcx = bv.datum.store_to(bcx, bound_data);
215 ast::CaptureByRef => {
216 Store(bcx, bv.datum.to_llref(), bound_data);
221 ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
224 // Given a context and a list of upvars, build a closure. This just
225 // collects the upvars and packages them up for store_environment.
226 fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>,
227 freevar_mode: ast::CaptureClause,
228 freevars: &Vec<ty::Freevar>,
229 store: ty::TraitStore)
230 -> ClosureResult<'blk, 'tcx> {
231 let _icx = push_ctxt("closure::build_closure");
233 // If we need to, package up the iterator body to call
236 // Package up the captured upvars
237 let mut env_vals = Vec::new();
238 for freevar in freevars.iter() {
239 let datum = expr::trans_local_var(bcx, freevar.def);
240 env_vals.push(EnvValue {action: freevar_mode, datum: datum});
243 store_environment(bcx, env_vals, store)
246 // Given an enclosing block context, a new function context, a closure type,
247 // and a list of upvars, generate code to load and populate the environment
248 // with the upvars and type descriptors.
249 fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
251 freevars: &Vec<ty::Freevar>,
252 store: ty::TraitStore)
253 -> Block<'blk, 'tcx> {
254 let _icx = push_ctxt("closure::load_environment");
256 // Don't bother to create the block if there's nothing to load
257 if freevars.len() == 0 {
261 // Load a pointer to the closure data, skipping over the box header:
262 let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
264 // Store the pointer to closure data in an alloca for debug info because that's what the
265 // llvm.dbg.declare intrinsic expects
266 let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
267 let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
268 Store(bcx, llcdata, alloc);
274 // Populate the upvars from the environment
276 for freevar in freevars.iter() {
277 let mut upvarptr = GEPi(bcx, llcdata, [0u, i]);
279 ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); }
280 ty::UniqTraitStore => {}
282 let def_id = freevar.def.def_id();
284 bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr);
285 for &env_pointer_alloca in env_pointer_alloca.iter() {
286 debuginfo::create_captured_var_metadata(
302 fn load_unboxed_closure_environment<'blk, 'tcx>(
303 bcx: Block<'blk, 'tcx>,
304 arg_scope_id: ScopeId,
305 freevar_mode: ast::CaptureClause,
306 freevars: &Vec<ty::Freevar>,
307 closure_id: ast::DefId)
308 -> Block<'blk, 'tcx> {
309 let _icx = push_ctxt("closure::load_environment");
311 if freevars.len() == 0 {
315 // Special case for small by-value selfs.
316 let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id,
317 node_id_type(bcx, closure_id.node));
318 let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id);
319 let llenv = if kind == ty::FnOnceUnboxedClosureKind &&
320 !arg_is_indirect(bcx.ccx(), self_type) {
321 let datum = rvalue_scratch_datum(bcx,
323 "unboxed_closure_env");
324 store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
325 assert!(freevars.len() <= 1);
328 bcx.fcx.llenv.unwrap()
331 for (i, freevar) in freevars.iter().enumerate() {
332 let mut upvar_ptr = GEPi(bcx, llenv, [0, i]);
333 if freevar_mode == ast::CaptureByRef {
334 upvar_ptr = Load(bcx, upvar_ptr);
336 let def_id = freevar.def.def_id();
337 bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
339 if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue {
340 bcx.fcx.schedule_drop_mem(arg_scope_id,
342 node_id_type(bcx, def_id.node))
349 fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
350 Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
351 let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
352 Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box]));
355 pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
356 store: ty::TraitStore,
361 -> Block<'blk, 'tcx> {
364 * Translates the body of a closure expression.
369 * - `id`: The id of the closure expression.
370 * - `cap_clause`: information about captured variables, if any.
371 * - `dest`: where to write the closure value, which must be a
375 let _icx = push_ctxt("closure::trans_expr_fn");
377 let dest_addr = match dest {
378 expr::SaveIn(p) => p,
380 return bcx; // closure construction is non-side-effecting
386 let fty = node_id_type(bcx, id);
387 let s = tcx.map.with_path(id, |path| {
388 mangle_internal_name_by_path_and_seq(path, "closure")
390 let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice());
392 // set an inline hint for all closures
393 set_inline_hint(llfn);
395 let freevar_mode = tcx.capture_mode(id);
396 let freevars: Vec<ty::Freevar> =
397 ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect());
403 } = build_closure(bcx, freevar_mode, &freevars, store);
408 bcx.fcx.param_substs,
415 |bcx, _| load_environment(bcx, cdata_ty, &freevars, store));
416 fill_fn_pair(bcx, dest_addr, llfn, llbox);
420 /// Returns the LLVM function declaration for an unboxed closure, creating it
421 /// if necessary. If the ID does not correspond to a closure ID, returns None.
422 pub fn get_or_create_declaration_if_unboxed_closure<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
423 closure_id: ast::DefId)
424 -> Option<ValueRef> {
426 if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
427 // Not an unboxed closure.
431 let function_type = node_id_type(bcx, closure_id.node);
432 let params = match ty::get(function_type).sty {
433 ty::ty_unboxed_closure(_, _, ref substs) => substs.types.clone(),
436 let mono_id = MonoId {
441 match ccx.unboxed_closure_vals().borrow().get(&mono_id) {
443 debug!("get_or_create_declaration_if_unboxed_closure(): found \
450 let function_type = node_id_type(bcx, closure_id.node);
451 let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
452 mangle_internal_name_by_path_and_seq(path, "unboxed_closure")
455 let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice());
457 // set an inline hint for all closures
458 set_inline_hint(llfn);
460 debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \
461 closure {} (type {})",
463 ccx.tn().type_to_string(val_ty(llfn)));
464 ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn);
469 pub fn trans_unboxed_closure<'blk, 'tcx>(
470 mut bcx: Block<'blk, 'tcx>,
475 -> Block<'blk, 'tcx> {
476 let _icx = push_ctxt("closure::trans_unboxed_closure");
478 debug!("trans_unboxed_closure()");
480 let closure_id = ast_util::local_def(id);
481 let llfn = get_or_create_declaration_if_unboxed_closure(
483 closure_id).unwrap();
485 let function_type = (*bcx.tcx().unboxed_closures.borrow())[closure_id]
488 let function_type = ty::mk_closure(bcx.tcx(), function_type);
490 let freevars: Vec<ty::Freevar> =
491 ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect());
492 let freevars_ptr = &freevars;
493 let freevar_mode = bcx.tcx().capture_mode(id);
495 trans_closure(bcx.ccx(),
499 bcx.fcx.param_substs,
502 ty::ty_fn_ret(function_type),
503 ty::ty_fn_abi(function_type),
507 load_unboxed_closure_environment(bcx,
514 // Don't hoist this to the top of the function. It's perfectly legitimate
515 // to have a zero-size unboxed closure (in which case dest will be
516 // `Ignore`) and we must still generate the closure body.
517 let dest_addr = match dest {
518 expr::SaveIn(p) => p,
520 debug!("trans_unboxed_closure() ignoring result");
525 let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id));
527 // Create the closure.
528 for (i, freevar) in freevars_ptr.iter().enumerate() {
529 let datum = expr::trans_local_var(bcx, freevar.def);
530 let upvar_slot_dest = adt::trans_field_ptr(bcx,
536 ast::CaptureByValue => {
537 bcx = datum.store_to(bcx, upvar_slot_dest);
539 ast::CaptureByRef => {
540 Store(bcx, datum.to_llref(), upvar_slot_dest);
544 adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
549 pub fn get_wrapper_for_bare_fn(ccx: &CrateContext,
553 is_local: bool) -> ValueRef {
555 let def_id = match def {
556 def::DefFn(did, _) | def::DefStaticMethod(did, _) |
557 def::DefVariant(_, did, _) | def::DefStruct(did) => did,
559 ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
560 expected a statically resolved fn, got \
566 match ccx.closure_bare_wrapper_cache().borrow().get(&fn_ptr) {
567 Some(&llval) => return llval,
573 debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
575 let f = match ty::get(closure_ty).sty {
576 ty::ty_closure(ref f) => f,
578 ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
579 expected a closure ty, got {}",
580 closure_ty.repr(tcx)).as_slice());
584 let name = ty::with_path(tcx, def_id, |path| {
585 mangle_internal_name_by_path_and_seq(path, "as_closure")
587 let llfn = if is_local {
588 decl_internal_rust_fn(ccx, closure_ty, name.as_slice())
590 decl_rust_fn(ccx, closure_ty, name.as_slice())
593 ccx.closure_bare_wrapper_cache().borrow_mut().insert(fn_ptr, llfn);
595 // This is only used by statics inlined from a different crate.
597 // Don't regenerate the wrapper, just reuse the original one.
601 let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
603 let arena = TypedArena::new();
604 let empty_param_substs = param_substs::empty();
605 let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, true, f.sig.output,
606 &empty_param_substs, None, &arena);
607 let bcx = init_function(&fcx, true, f.sig.output);
609 let args = create_datums_for_fn_args(&fcx,
610 ty::ty_fn_args(closure_ty)
612 let mut llargs = Vec::new();
613 match fcx.llretslotptr.get() {
615 assert!(!fcx.needs_ret_allocas);
616 llargs.push(llretptr);
620 llargs.extend(args.iter().map(|arg| arg.val));
622 let retval = Call(bcx, fn_ptr, llargs.as_slice(), None);
624 ty::FnConverging(output_type) => {
625 if return_type_is_void(ccx, output_type) || fcx.llretslotptr.get().is_some() {
636 // HACK(eddyb) finish_fn cannot be used here, we returned directly.
637 debuginfo::clear_source_location(&fcx);
643 pub fn make_closure_from_bare_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
647 -> DatumBlock<'blk, 'tcx, Expr> {
648 let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
649 let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def, fn_ptr, true);
650 fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p(bcx.ccx())));
652 DatumBlock::new(bcx, scratch.to_expr_datum())