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.
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::session::FullDebugInfo;
15 use lib::llvm::ValueRef;
17 use middle::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::common::*;
20 use middle::trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
21 use middle::trans::debuginfo;
22 use middle::trans::expr;
23 use middle::trans::type_of::*;
24 use middle::trans::type_::Type;
26 use util::ppaux::Repr;
27 use util::ppaux::ty_to_str;
29 use arena::TypedArena;
33 // ___Good to know (tm)__________________________________________________
35 // The layout of a closure environment in memory is
36 // roughly as follows:
38 // struct rust_opaque_box { // see rust_internal.h
39 // unsigned ref_count; // only used for @fn()
40 // type_desc *tydesc; // describes closure_data struct
41 // rust_opaque_box *prev; // (used internally by memory alloc)
42 // rust_opaque_box *next; // (used internally by memory alloc)
43 // struct closure_data {
44 // type_desc *bound_tdescs[]; // bound descriptors
53 // Note that the closure is itself a rust_opaque_box. This is true
54 // even for ~fn and ||, because we wish to keep binary compatibility
55 // between all kinds of closures. The allocation strategy for this
56 // closure depends on the closure type. For a sendfn, the closure
57 // (and the referenced type descriptors) will be allocated in the
58 // exchange heap. For a fn, the closure is allocated in the task heap
59 // and is reference counted. For a block, the closure is allocated on
62 // ## Opaque closures and the embedded type descriptor ##
64 // One interesting part of closures is that they encapsulate the data
65 // that they close over. So when I have a ptr to a closure, I do not
66 // know how many type descriptors it contains nor what upvars are
67 // captured within. That means I do not know precisely how big it is
68 // nor where its fields are located. This is called an "opaque
71 // Typically an opaque closure suffices because we only manipulate it
72 // by ptr. The routine Type::at_box().ptr_to() returns an appropriate
73 // type for such an opaque closure; it allows access to the box fields,
74 // but not the closure_data itself.
76 // But sometimes, such as when cloning or freeing a closure, we need
77 // to know the full information. That is where the type descriptor
78 // that defines the closure comes in handy. We can use its take and
79 // drop glue functions to allocate/free data as needed.
81 // ## Subtleties concerning alignment ##
83 // It is important that we be able to locate the closure data *without
84 // knowing the kind of data that is being bound*. This can be tricky
85 // because the alignment requirements of the bound data affects the
86 // alignment requires of the closure_data struct as a whole. However,
87 // right now this is a non-issue in any case, because the size of the
88 // rust_opaque_box header is always a mutiple of 16-bytes, which is
89 // the maximum alignment requirement we ever have to worry about.
91 // The only reason alignment matters is that, in order to learn what data
92 // is bound, we would normally first load the type descriptors: but their
93 // location is ultimately depend on their content! There is, however, a
94 // workaround. We can load the tydesc from the rust_opaque_box, which
95 // describes the closure_data struct and has self-contained derived type
96 // descriptors, and read the alignment from there. It's just annoying to
97 // do. Hopefully should this ever become an issue we'll have monomorphized
98 // and type descriptors will all be a bad dream.
100 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103 /// Copy the value from this llvm ValueRef into the environment.
106 /// Move the value from this llvm ValueRef into the environment.
109 /// Access by reference (used for stack closures).
113 pub struct EnvValue {
119 pub fn to_str(&self) -> ~str {
121 EnvCopy => ~"EnvCopy",
122 EnvMove => ~"EnvMove",
129 pub fn to_str(&self, ccx: &CrateContext) -> ~str {
130 format!("{}({})", self.action.to_str(), self.datum.to_str(ccx))
134 // Given a closure ty, emits a corresponding tuple ty
135 pub fn mk_closure_tys(tcx: &ty::ctxt,
136 bound_values: &[EnvValue])
138 // determine the types of the values in the env. Note that this
139 // is the actual types that will be stored in the map, not the
140 // logical types as the user sees them, so by-ref upvars must be
141 // converted to ptrs.
142 let bound_tys = bound_values.iter().map(|bv| {
144 EnvCopy | EnvMove => bv.datum.ty,
145 EnvRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
148 let cdata_ty = ty::mk_tup(tcx, bound_tys);
149 debug!("cdata_ty={}", ty_to_str(tcx, cdata_ty));
153 fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t {
154 let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8());
155 ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t))
158 fn allocate_cbox<'a>(bcx: &'a Block<'a>,
162 let _icx = push_ctxt("closure::allocate_cbox");
165 // Allocate and initialize the box:
167 ast::ManagedSigil => {
168 tcx.sess.bug("trying to trans allocation of @fn")
171 malloc_raw(bcx, cdata_ty, heap_exchange_closure)
173 ast::BorrowedSigil => {
174 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
175 let llbox = alloc_ty(bcx, cbox_ty, "__closure");
181 pub struct ClosureResult<'a> {
182 llbox: ValueRef, // llvalue of ptr to closure
183 cdata_ty: ty::t, // type of the closure data
184 bcx: &'a Block<'a> // final bcx
187 // Given a block context and a list of tydescs and values to bind
188 // construct a closure out of them. If copying is true, it is a
189 // heap allocated closure that copies the upvars into environment.
190 // Otherwise, it is stack allocated and copies pointers to the upvars.
191 pub fn store_environment<'a>(
193 bound_values: Vec<EnvValue> ,
195 -> ClosureResult<'a> {
196 let _icx = push_ctxt("closure::store_environment");
200 // compute the type of the closure
201 let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice());
203 // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
204 // tuple. This could be a ptr in uniq or a box or on stack,
206 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
207 let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
208 let llboxptr_ty = type_of(ccx, cboxptr_ty);
210 // If there are no bound values, no point in allocating anything.
211 if bound_values.is_empty() {
212 return ClosureResult {llbox: C_null(llboxptr_ty),
217 // allocate closure in the heap
218 let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, sigil, cdata_ty);
220 let llbox = PointerCast(bcx, llbox, llboxptr_ty);
221 debug!("tuplify_box_ty = {}", ty_to_str(tcx, cbox_ty));
223 // Copy expr values into boxed bindings.
225 for (i, bv) in bound_values.move_iter().enumerate() {
226 debug!("Copy {} into closure", bv.to_str(ccx));
228 if ccx.sess().asm_comments() {
229 add_comment(bcx, format!("Copy {} into closure",
233 let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]);
236 EnvCopy | EnvMove => {
237 bcx = bv.datum.store_to(bcx, bound_data);
240 Store(bcx, bv.datum.to_llref(), bound_data);
245 ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
248 // Given a context and a list of upvars, build a closure. This just
249 // collects the upvars and packages them up for store_environment.
250 fn build_closure<'a>(bcx0: &'a Block<'a>,
251 cap_vars: &[moves::CaptureVar],
253 -> ClosureResult<'a> {
254 let _icx = push_ctxt("closure::build_closure");
256 // If we need to, package up the iterator body to call
259 // Package up the captured upvars
260 let mut env_vals = Vec::new();
261 for cap_var in cap_vars.iter() {
262 debug!("Building closure: captured variable {:?}", *cap_var);
263 let datum = expr::trans_local_var(bcx, cap_var.def);
266 assert_eq!(sigil, ast::BorrowedSigil);
267 env_vals.push(EnvValue {action: EnvRef,
271 env_vals.push(EnvValue {action: EnvCopy,
275 env_vals.push(EnvValue {action: EnvMove,
281 return store_environment(bcx, env_vals, sigil);
284 // Given an enclosing block context, a new function context, a closure type,
285 // and a list of upvars, generate code to load and populate the environment
286 // with the upvars and type descriptors.
287 fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t,
288 cap_vars: &[moves::CaptureVar],
289 sigil: ast::Sigil) -> &'a Block<'a> {
290 let _icx = push_ctxt("closure::load_environment");
292 // Don't bother to create the block if there's nothing to load
293 if cap_vars.len() == 0 {
297 // Load a pointer to the closure data, skipping over the box header:
298 let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
300 // Store the pointer to closure data in an alloca for debug info because that's what the
301 // llvm.dbg.declare intrinsic expects
302 let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
303 let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
304 Store(bcx, llcdata, alloc);
310 // Populate the upvars from the environment
312 for cap_var in cap_vars.iter() {
313 let mut upvarptr = GEPi(bcx, llcdata, [0u, i]);
315 ast::BorrowedSigil => { upvarptr = Load(bcx, upvarptr); }
316 ast::ManagedSigil | ast::OwnedSigil => {}
318 let def_id = ast_util::def_id_of_def(cap_var.def);
321 let mut llupvars = bcx.fcx.llupvars.borrow_mut();
322 llupvars.get().insert(def_id.node, upvarptr);
325 for &env_pointer_alloca in env_pointer_alloca.iter() {
326 debuginfo::create_captured_var_metadata(
342 fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
343 Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
344 let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
345 Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box]));
348 pub fn trans_expr_fn<'a>(
358 * Translates the body of a closure expression.
363 * - `id`: The id of the closure expression.
364 * - `cap_clause`: information about captured variables, if any.
365 * - `dest`: where to write the closure value, which must be a
369 let _icx = push_ctxt("closure::trans_expr_fn");
371 let dest_addr = match dest {
372 expr::SaveIn(p) => p,
374 return bcx; // closure construction is non-side-effecting
379 let fty = node_id_type(bcx, id);
380 let f = match ty::get(fty).sty {
381 ty::ty_closure(ref f) => f,
382 _ => fail!("expected closure")
386 let s = tcx.map.with_path(id, |path| {
387 mangle_internal_name_by_path_and_seq(path, "closure")
389 let llfn = decl_internal_rust_fn(ccx,
391 f.sig.inputs.as_slice(),
395 // set an inline hint for all closures
396 set_inline_hint(llfn);
398 let cap_vars = ccx.maps.capture_map.borrow().get().get_copy(&id);
399 let ClosureResult {llbox, cdata_ty, bcx} =
400 build_closure(bcx, cap_vars.deref().as_slice(), sigil);
401 trans_closure(ccx, decl, body, llfn,
402 bcx.fcx.param_substs, id,
403 [], ty::ty_fn_ret(fty),
404 |bcx| load_environment(bcx, cdata_ty, cap_vars.deref().as_slice(), sigil));
405 fill_fn_pair(bcx, dest_addr, llfn, llbox);
410 pub fn get_wrapper_for_bare_fn(ccx: &CrateContext,
414 is_local: bool) -> ValueRef {
416 let def_id = match def {
417 ast::DefFn(did, _) | ast::DefStaticMethod(did, _, _) |
418 ast::DefVariant(_, did, _) | ast::DefStruct(did) => did,
420 ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
421 expected a statically resolved fn, got {:?}",
427 let cache = ccx.closure_bare_wrapper_cache.borrow();
428 match cache.get().find(&fn_ptr) {
429 Some(&llval) => return llval,
436 debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
438 let f = match ty::get(closure_ty).sty {
439 ty::ty_closure(ref f) => f,
441 ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
442 expected a closure ty, got {}",
443 closure_ty.repr(tcx)));
447 let name = ty::with_path(tcx, def_id, |path| {
448 mangle_internal_name_by_path_and_seq(path, "as_closure")
450 let llfn = if is_local {
451 decl_internal_rust_fn(ccx,
453 f.sig.inputs.as_slice(),
457 decl_rust_fn(ccx, true, f.sig.inputs.as_slice(), f.sig.output, name)
461 let mut cache = ccx.closure_bare_wrapper_cache.borrow_mut();
462 cache.get().insert(fn_ptr, llfn);
465 // This is only used by statics inlined from a different crate.
467 // Don't regenerate the wrapper, just reuse the original one.
471 let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
473 let arena = TypedArena::new();
474 let fcx = new_fn_ctxt(ccx, llfn, -1, true, f.sig.output, None, None, &arena);
475 init_function(&fcx, true, f.sig.output, None);
476 let bcx = fcx.entry_bcx.get().unwrap();
478 let args = create_datums_for_fn_args(&fcx,
479 ty::ty_fn_args(closure_ty)
481 let mut llargs = Vec::new();
482 match fcx.llretptr.get() {
484 llargs.push(llretptr);
488 llargs.extend(&mut args.iter().map(|arg| arg.val));
490 let retval = Call(bcx, fn_ptr, llargs.as_slice(), []);
491 if type_is_zero_size(ccx, f.sig.output) || fcx.llretptr.get().is_some() {
497 // HACK(eddyb) finish_fn cannot be used here, we returned directly.
498 debuginfo::clear_source_location(&fcx);
504 pub fn make_closure_from_bare_fn<'a>(bcx: &'a Block<'a>,
508 -> DatumBlock<'a, Expr> {
509 let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
510 let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def, fn_ptr, true);
511 fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p(bcx.ccx())));
513 DatumBlock(bcx, scratch.to_expr_datum())