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.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, ~[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");
166 // Allocate and initialize the box:
168 ast::ManagedSigil => {
169 tcx.sess.bug("trying to trans allocation of @fn")
172 malloc_raw(bcx, cdata_ty, heap_exchange_closure)
174 ast::BorrowedSigil => {
175 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
176 let llbox = alloc_ty(bcx, cbox_ty, "__closure");
182 pub struct ClosureResult<'a> {
183 llbox: ValueRef, // llvalue of ptr to closure
184 cdata_ty: ty::t, // type of the closure data
185 bcx: &'a Block<'a> // final bcx
188 // Given a block context and a list of tydescs and values to bind
189 // construct a closure out of them. If copying is true, it is a
190 // heap allocated closure that copies the upvars into environment.
191 // Otherwise, it is stack allocated and copies pointers to the upvars.
192 pub fn store_environment<'a>(
194 bound_values: ~[EnvValue],
196 -> ClosureResult<'a> {
197 let _icx = push_ctxt("closure::store_environment");
201 // compute the type of the closure
202 let cdata_ty = mk_closure_tys(tcx, bound_values);
204 // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
205 // tuple. This could be a ptr in uniq or a box or on stack,
207 let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
208 let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
209 let llboxptr_ty = type_of(ccx, cboxptr_ty);
211 // If there are no bound values, no point in allocating anything.
212 if bound_values.is_empty() {
213 return ClosureResult {llbox: C_null(llboxptr_ty),
218 // allocate closure in the heap
219 let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, sigil, cdata_ty);
221 let llbox = PointerCast(bcx, llbox, llboxptr_ty);
222 debug!("tuplify_box_ty = {}", ty_to_str(tcx, cbox_ty));
224 // Copy expr values into boxed bindings.
226 for (i, bv) in bound_values.move_iter().enumerate() {
227 debug!("Copy {} into closure", bv.to_str(ccx));
229 if ccx.sess.asm_comments() {
230 add_comment(bcx, format!("Copy {} into closure",
234 let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]);
237 EnvCopy | EnvMove => {
238 bcx = bv.datum.store_to(bcx, bound_data);
241 Store(bcx, bv.datum.to_llref(), bound_data);
246 ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
249 // Given a context and a list of upvars, build a closure. This just
250 // collects the upvars and packages them up for store_environment.
251 fn build_closure<'a>(bcx0: &'a Block<'a>,
252 cap_vars: &[moves::CaptureVar],
254 -> ClosureResult<'a> {
255 let _icx = push_ctxt("closure::build_closure");
257 // If we need to, package up the iterator body to call
260 // Package up the captured upvars
261 let mut env_vals = ~[];
262 for cap_var in cap_vars.iter() {
263 debug!("Building closure: captured variable {:?}", *cap_var);
264 let datum = expr::trans_local_var(bcx, cap_var.def);
267 assert_eq!(sigil, ast::BorrowedSigil);
268 env_vals.push(EnvValue {action: EnvRef,
272 env_vals.push(EnvValue {action: EnvCopy,
276 env_vals.push(EnvValue {action: EnvMove,
282 return store_environment(bcx, env_vals, sigil);
285 // Given an enclosing block context, a new function context, a closure type,
286 // and a list of upvars, generate code to load and populate the environment
287 // with the upvars and type descriptors.
288 fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t,
289 cap_vars: &[moves::CaptureVar],
290 sigil: ast::Sigil) -> &'a Block<'a> {
291 let _icx = push_ctxt("closure::load_environment");
293 // Don't bother to create the block if there's nothing to load
294 if cap_vars.len() == 0 {
298 // Load a pointer to the closure data, skipping over the box header:
299 let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
301 // Store the pointer to closure data in an alloca for debug info because that's what the
302 // llvm.dbg.declare intrinsic expects
303 let env_pointer_alloca = if bcx.ccx().sess.opts.debuginfo == FullDebugInfo {
304 let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
305 Store(bcx, llcdata, alloc);
311 // Populate the upvars from the environment
313 for cap_var in cap_vars.iter() {
314 let mut upvarptr = GEPi(bcx, llcdata, [0u, i]);
316 ast::BorrowedSigil => { upvarptr = Load(bcx, upvarptr); }
317 ast::ManagedSigil | ast::OwnedSigil => {}
319 let def_id = ast_util::def_id_of_def(cap_var.def);
322 let mut llupvars = bcx.fcx.llupvars.borrow_mut();
323 llupvars.get().insert(def_id.node, upvarptr);
326 for &env_pointer_alloca in env_pointer_alloca.iter() {
327 debuginfo::create_captured_var_metadata(
343 fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
344 Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
345 let llenvptr = PointerCast(bcx, llenvptr, Type::i8p());
346 Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box]));
349 pub fn trans_expr_fn<'a>(
359 * Translates the body of a closure expression.
364 * - `id`: The id of the closure expression.
365 * - `cap_clause`: information about captured variables, if any.
366 * - `dest`: where to write the closure value, which must be a
370 let _icx = push_ctxt("closure::trans_expr_fn");
372 let dest_addr = match dest {
373 expr::SaveIn(p) => p,
375 return bcx; // closure construction is non-side-effecting
380 let fty = node_id_type(bcx, id);
381 let f = match ty::get(fty).sty {
382 ty::ty_closure(ref f) => f,
383 _ => fail!("expected closure")
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, true, f.sig.inputs, f.sig.output, s);
392 // set an inline hint for all closures
393 set_inline_hint(llfn);
396 let capture_map = ccx.maps.capture_map.borrow();
397 capture_map.get().get_copy(&id)
399 let ClosureResult {llbox, cdata_ty, bcx} = build_closure(bcx, *cap_vars.borrow(), sigil);
400 trans_closure(ccx, decl, body, llfn,
401 bcx.fcx.param_substs, id,
402 [], ty::ty_fn_ret(fty),
403 |bcx| load_environment(bcx, cdata_ty, *cap_vars.borrow(), sigil));
404 fill_fn_pair(bcx, dest_addr, llfn, llbox);
409 pub fn get_wrapper_for_bare_fn(ccx: @CrateContext,
413 is_local: bool) -> ValueRef {
415 let def_id = match def {
416 ast::DefFn(did, _) | ast::DefStaticMethod(did, _, _) |
417 ast::DefVariant(_, did, _) | ast::DefStruct(did) => did,
419 ccx.sess.bug(format!("get_wrapper_for_bare_fn: \
420 expected a statically resolved fn, got {:?}",
426 let cache = ccx.closure_bare_wrapper_cache.borrow();
427 match cache.get().find(&fn_ptr) {
428 Some(&llval) => return llval,
435 debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
437 let f = match ty::get(closure_ty).sty {
438 ty::ty_closure(ref f) => f,
440 ccx.sess.bug(format!("get_wrapper_for_bare_fn: \
441 expected a closure ty, got {}",
442 closure_ty.repr(tcx)));
446 let name = ty::with_path(tcx, def_id, |path| {
447 mangle_internal_name_by_path_and_seq(path, "as_closure")
449 let llfn = if is_local {
450 decl_internal_rust_fn(ccx, true, f.sig.inputs, f.sig.output, name)
452 decl_rust_fn(ccx, true, f.sig.inputs, f.sig.output, name)
456 let mut cache = ccx.closure_bare_wrapper_cache.borrow_mut();
457 cache.get().insert(fn_ptr, llfn);
460 // This is only used by statics inlined from a different crate.
462 // Don't regenerate the wrapper, just reuse the original one.
466 let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
468 let arena = TypedArena::new();
469 let fcx = new_fn_ctxt(ccx, llfn, -1, true, f.sig.output, None, None, &arena);
470 init_function(&fcx, true, f.sig.output, None);
471 let bcx = fcx.entry_bcx.get().unwrap();
473 let args = create_datums_for_fn_args(&fcx, ty::ty_fn_args(closure_ty));
474 let mut llargs = ~[];
475 match fcx.llretptr.get() {
477 llargs.push(llretptr);
481 llargs.extend(&mut args.iter().map(|arg| arg.val));
483 let retval = Call(bcx, fn_ptr, llargs, []);
484 if type_is_zero_size(ccx, f.sig.output) || fcx.llretptr.get().is_some() {
490 // HACK(eddyb) finish_fn cannot be used here, we returned directly.
491 debuginfo::clear_source_location(&fcx);
497 pub fn make_closure_from_bare_fn<'a>(bcx: &'a Block<'a>,
501 -> DatumBlock<'a, Expr> {
502 let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
503 let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def, fn_ptr, true);
504 fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p()));
506 DatumBlock(bcx, scratch.to_expr_datum())