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 use arena
::TypedArena
;
12 use back
::link
::{self, mangle_internal_name_by_path_and_seq}
;
13 use llvm
::{ValueRef, get_param}
;
14 use middle
::mem_categorization
::Typer
;
16 use trans
::attributes
;
19 use trans
::callee
::{self, ArgVals, Callee, TraitItem, MethodData}
;
20 use trans
::cleanup
::{CleanupMethods, CustomScope, ScopeId}
;
22 use trans
::datum
::{self, Datum, rvalue_scratch_datum, Rvalue, ByValue}
;
23 use trans
::debuginfo
::{self, DebugLoc}
;
26 use trans
::monomorphize
::{self, MonoId}
;
27 use trans
::type_of
::*;
28 use middle
::ty
::{self, ClosureTyper}
;
29 use middle
::subst
::Substs
;
30 use session
::config
::FullDebugInfo
;
31 use util
::ppaux
::Repr
;
33 use syntax
::abi
::RustCall
;
38 fn load_closure_environment
<'blk
, 'tcx
>(bcx
: Block
<'blk
, 'tcx
>,
39 arg_scope_id
: ScopeId
,
40 freevars
: &[ty
::Freevar
])
43 let _icx
= push_ctxt("closure::load_closure_environment");
45 // Special case for small by-value selfs.
46 let closure_id
= ast_util
::local_def(bcx
.fcx
.id
);
47 let self_type
= self_type_for_closure(bcx
.ccx(), closure_id
,
48 node_id_type(bcx
, closure_id
.node
));
49 let kind
= kind_for_closure(bcx
.ccx(), closure_id
);
50 let llenv
= if kind
== ty
::FnOnceClosureKind
&&
51 !arg_is_indirect(bcx
.ccx(), self_type
) {
52 let datum
= rvalue_scratch_datum(bcx
,
55 store_ty(bcx
, bcx
.fcx
.llenv
.unwrap(), datum
.val
, self_type
);
58 bcx
.fcx
.llenv
.unwrap()
61 // Store the pointer to closure data in an alloca for debug info because that's what the
62 // llvm.dbg.declare intrinsic expects
63 let env_pointer_alloca
= if bcx
.sess().opts
.debuginfo
== FullDebugInfo
{
64 let alloc
= alloca(bcx
, val_ty(llenv
), "__debuginfo_env_ptr");
65 Store(bcx
, llenv
, alloc
);
71 for (i
, freevar
) in freevars
.iter().enumerate() {
72 let upvar_id
= ty
::UpvarId
{ var_id
: freevar
.def
.local_node_id(),
73 closure_expr_id
: closure_id
.node
};
74 let upvar_capture
= bcx
.tcx().upvar_capture(upvar_id
).unwrap();
75 let mut upvar_ptr
= GEPi(bcx
, llenv
, &[0, i
]);
76 let captured_by_ref
= match upvar_capture
{
77 ty
::UpvarCapture
::ByValue
=> false,
78 ty
::UpvarCapture
::ByRef(..) => {
79 upvar_ptr
= Load(bcx
, upvar_ptr
);
83 let def_id
= freevar
.def
.def_id();
84 bcx
.fcx
.llupvars
.borrow_mut().insert(def_id
.node
, upvar_ptr
);
86 if kind
== ty
::FnOnceClosureKind
&& !captured_by_ref
{
87 bcx
.fcx
.schedule_drop_mem(arg_scope_id
,
89 node_id_type(bcx
, def_id
.node
))
92 if let Some(env_pointer_alloca
) = env_pointer_alloca
{
93 debuginfo
::create_captured_var_metadata(
106 pub enum ClosureEnv
<'a
> {
108 Closure(&'a
[ty
::Freevar
]),
111 impl<'a
> ClosureEnv
<'a
> {
112 pub fn load
<'blk
,'tcx
>(self, bcx
: Block
<'blk
, 'tcx
>, arg_scope
: ScopeId
)
116 ClosureEnv
::NotClosure
=> bcx
,
117 ClosureEnv
::Closure(freevars
) => {
118 if freevars
.is_empty() {
121 load_closure_environment(bcx
, arg_scope
, freevars
)
128 /// Returns the LLVM function declaration for a closure, creating it if
129 /// necessary. If the ID does not correspond to a closure ID, returns None.
130 pub fn get_or_create_declaration_if_closure
<'a
, 'tcx
>(ccx
: &CrateContext
<'a
, 'tcx
>,
131 closure_id
: ast
::DefId
,
132 substs
: &Substs
<'tcx
>)
133 -> Option
<Datum
<'tcx
, Rvalue
>> {
134 if !ccx
.tcx().closure_kinds
.borrow().contains_key(&closure_id
) {
139 let function_type
= ty
::node_id_to_type(ccx
.tcx(), closure_id
.node
);
140 let function_type
= monomorphize
::apply_param_substs(ccx
.tcx(), substs
, &function_type
);
142 // Normalize type so differences in regions and typedefs don't cause
143 // duplicate declarations
144 let function_type
= erase_regions(ccx
.tcx(), &function_type
);
145 let params
= match function_type
.sty
{
146 ty
::ty_closure(_
, substs
) => &substs
.types
,
149 let mono_id
= MonoId
{
154 match ccx
.closure_vals().borrow().get(&mono_id
) {
156 debug
!("get_or_create_declaration_if_closure(): found closure");
157 return Some(Datum
::new(llfn
, function_type
, Rvalue
::new(ByValue
)))
162 let symbol
= ccx
.tcx().map
.with_path(closure_id
.node
, |path
| {
163 mangle_internal_name_by_path_and_seq(path
, "closure")
166 // Currently there’s only a single user of get_or_create_declaration_if_closure and it
167 // unconditionally defines the function, therefore we use define_* here.
168 let llfn
= declare
::define_internal_rust_fn(ccx
, &symbol
[..], function_type
).unwrap_or_else(||{
169 ccx
.sess().bug(&format
!("symbol `{}` already defined", symbol
));
172 // set an inline hint for all closures
173 attributes
::inline(llfn
, attributes
::InlineAttr
::Hint
);
175 debug
!("get_or_create_declaration_if_closure(): inserting new \
176 closure {:?} (type {})",
178 ccx
.tn().type_to_string(val_ty(llfn
)));
179 ccx
.closure_vals().borrow_mut().insert(mono_id
, llfn
);
181 Some(Datum
::new(llfn
, function_type
, Rvalue
::new(ByValue
)))
184 pub enum Dest
<'a
, 'tcx
: 'a
> {
185 SaveIn(Block
<'a
, 'tcx
>, ValueRef
),
186 Ignore(&'a CrateContext
<'a
, 'tcx
>)
189 pub fn trans_closure_expr
<'a
, 'tcx
>(dest
: Dest
<'a
, 'tcx
>,
193 param_substs
: &'tcx Substs
<'tcx
>)
194 -> Option
<Block
<'a
, 'tcx
>>
196 let ccx
= match dest
{
197 Dest
::SaveIn(bcx
, _
) => bcx
.ccx(),
198 Dest
::Ignore(ccx
) => ccx
201 let _icx
= push_ctxt("closure::trans_closure");
203 debug
!("trans_closure()");
205 let closure_id
= ast_util
::local_def(id
);
206 let llfn
= get_or_create_declaration_if_closure(
209 param_substs
).unwrap();
211 // Get the type of this closure. Use the current `param_substs` as
212 // the closure substitutions. This makes sense because the closure
213 // takes the same set of type arguments as the enclosing fn, and
214 // this function (`trans_closure`) is invoked at the point
215 // of the closure expression.
216 let typer
= NormalizingClosureTyper
::new(tcx
);
217 let function_type
= typer
.closure_type(closure_id
, param_substs
);
219 let freevars
: Vec
<ty
::Freevar
> =
220 ty
::with_freevars(tcx
, id
, |fv
| fv
.iter().cloned().collect());
222 let sig
= ty
::erase_late_bound_regions(tcx
, &function_type
.sig
);
233 ClosureEnv
::Closure(&freevars
[..]));
235 // Don't hoist this to the top of the function. It's perfectly legitimate
236 // to have a zero-size closure (in which case dest will be `Ignore`) and
237 // we must still generate the closure body.
238 let (mut bcx
, dest_addr
) = match dest
{
239 Dest
::SaveIn(bcx
, p
) => (bcx
, p
),
241 debug
!("trans_closure() ignoring result");
246 let repr
= adt
::represent_type(ccx
, node_id_type(bcx
, id
));
248 // Create the closure.
249 for (i
, freevar
) in freevars
.iter().enumerate() {
250 let datum
= expr
::trans_local_var(bcx
, freevar
.def
);
251 let upvar_slot_dest
= adt
::trans_field_ptr(bcx
, &*repr
, dest_addr
, 0, i
);
252 let upvar_id
= ty
::UpvarId
{ var_id
: freevar
.def
.local_node_id(),
253 closure_expr_id
: id
};
254 match tcx
.upvar_capture(upvar_id
).unwrap() {
255 ty
::UpvarCapture
::ByValue
=> {
256 bcx
= datum
.store_to(bcx
, upvar_slot_dest
);
258 ty
::UpvarCapture
::ByRef(..) => {
259 Store(bcx
, datum
.to_llref(), upvar_slot_dest
);
263 adt
::trans_set_discr(bcx
, &*repr
, dest_addr
, 0);
268 pub fn trans_closure_method
<'a
, 'tcx
>(ccx
: &'a CrateContext
<'a
, 'tcx
>,
269 closure_def_id
: ast
::DefId
,
270 substs
: Substs
<'tcx
>,
271 node
: ExprOrMethodCall
,
272 param_substs
: &'tcx Substs
<'tcx
>,
273 trait_closure_kind
: ty
::ClosureKind
)
276 // The substitutions should have no type parameters remaining
277 // after passing through fulfill_obligation
278 let llfn
= callee
::trans_fn_ref_with_substs(ccx
,
284 // If the closure is a Fn closure, but a FnOnce is needed (etc),
285 // then adapt the self type
286 let closure_kind
= ccx
.tcx().closure_kind(closure_def_id
);
287 trans_closure_adapter_shim(ccx
,
295 fn trans_closure_adapter_shim
<'a
, 'tcx
>(
296 ccx
: &'a CrateContext
<'a
, 'tcx
>,
297 closure_def_id
: ast
::DefId
,
298 substs
: Substs
<'tcx
>,
299 llfn_closure_kind
: ty
::ClosureKind
,
300 trait_closure_kind
: ty
::ClosureKind
,
304 let _icx
= push_ctxt("trans_closure_adapter_shim");
307 debug
!("trans_closure_adapter_shim(llfn_closure_kind={:?}, \
308 trait_closure_kind={:?}, \
312 ccx
.tn().val_to_string(llfn
));
314 match (llfn_closure_kind
, trait_closure_kind
) {
315 (ty
::FnClosureKind
, ty
::FnClosureKind
) |
316 (ty
::FnMutClosureKind
, ty
::FnMutClosureKind
) |
317 (ty
::FnOnceClosureKind
, ty
::FnOnceClosureKind
) => {
318 // No adapter needed.
321 (ty
::FnClosureKind
, ty
::FnMutClosureKind
) => {
322 // The closure fn `llfn` is a `fn(&self, ...)`. We want a
323 // `fn(&mut self, ...)`. In fact, at trans time, these are
324 // basically the same thing, so we can just return llfn.
327 (ty
::FnClosureKind
, ty
::FnOnceClosureKind
) |
328 (ty
::FnMutClosureKind
, ty
::FnOnceClosureKind
) => {
329 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
330 // self, ...)`. We want a `fn(self, ...)`. We can produce
331 // this by doing something like:
333 // fn call_once(self, ...) { call_mut(&self, ...) }
334 // fn call_once(mut self, ...) { call_mut(&mut self, ...) }
336 // These are both the same at trans time.
337 trans_fn_once_adapter_shim(ccx
, closure_def_id
, substs
, llfn
)
340 tcx
.sess
.bug(&format
!("trans_closure_adapter_shim: cannot convert {:?} to {:?}",
342 trait_closure_kind
));
347 fn trans_fn_once_adapter_shim
<'a
, 'tcx
>(
348 ccx
: &'a CrateContext
<'a
, 'tcx
>,
349 closure_def_id
: ast
::DefId
,
350 substs
: Substs
<'tcx
>,
354 debug
!("trans_fn_once_adapter_shim(closure_def_id={}, substs={}, llreffn={})",
355 closure_def_id
.repr(ccx
.tcx()),
356 substs
.repr(ccx
.tcx()),
357 ccx
.tn().val_to_string(llreffn
));
360 let typer
= NormalizingClosureTyper
::new(tcx
);
362 // Find a version of the closure type. Substitute static for the
363 // region since it doesn't really matter.
364 let substs
= tcx
.mk_substs(substs
);
365 let closure_ty
= ty
::mk_closure(tcx
, closure_def_id
, substs
);
366 let ref_closure_ty
= ty
::mk_imm_rptr(tcx
, tcx
.mk_region(ty
::ReStatic
), closure_ty
);
368 // Make a version with the type of by-ref closure.
369 let ty
::ClosureTy { unsafety, abi, mut sig }
= typer
.closure_type(closure_def_id
, substs
);
370 sig
.0.inputs
.insert(0, ref_closure_ty
); // sig has no self type as of yet
371 let llref_bare_fn_ty
= tcx
.mk_bare_fn(ty
::BareFnTy
{ unsafety
: unsafety
,
374 let llref_fn_ty
= ty
::mk_bare_fn(tcx
, None
, llref_bare_fn_ty
);
375 debug
!("trans_fn_once_adapter_shim: llref_fn_ty={}",
376 llref_fn_ty
.repr(tcx
));
378 // Make a version of the closure type with the same arguments, but
379 // with argument #0 being by value.
380 assert_eq
!(abi
, RustCall
);
381 sig
.0.inputs
[0] = closure_ty
;
382 let llonce_bare_fn_ty
= tcx
.mk_bare_fn(ty
::BareFnTy
{ unsafety
: unsafety
,
385 let llonce_fn_ty
= ty
::mk_bare_fn(tcx
, None
, llonce_bare_fn_ty
);
387 // Create the by-value helper.
388 let function_name
= link
::mangle_internal_name_by_type_and_seq(ccx
, llonce_fn_ty
, "once_shim");
389 let lloncefn
= declare
::define_internal_rust_fn(ccx
, &function_name
[..], llonce_fn_ty
)
391 ccx
.sess().bug(&format
!("symbol `{}` already defined", function_name
));
394 let sig
= ty
::erase_late_bound_regions(tcx
, &llonce_bare_fn_ty
.sig
);
395 let (block_arena
, fcx
): (TypedArena
<_
>, FunctionContext
);
396 block_arena
= TypedArena
::new();
397 fcx
= new_fn_ctxt(ccx
,
405 let mut bcx
= init_function(&fcx
, false, sig
.output
);
407 // the first argument (`self`) will be the (by value) closure env.
408 let self_scope
= fcx
.push_custom_cleanup_scope();
409 let self_scope_id
= CustomScope(self_scope
);
410 let rvalue_mode
= datum
::appropriate_rvalue_mode(ccx
, closure_ty
);
411 let llself
= get_param(lloncefn
, fcx
.arg_pos(0) as u32);
412 let env_datum
= Datum
::new(llself
, closure_ty
, Rvalue
::new(rvalue_mode
));
413 let env_datum
= unpack_datum
!(bcx
,
414 env_datum
.to_lvalue_datum_in_scope(bcx
, "self",
417 debug
!("trans_fn_once_adapter_shim: env_datum={}",
418 bcx
.val_to_string(env_datum
.val
));
420 // the remaining arguments will be packed up in a tuple.
421 let input_tys
= match sig
.inputs
[1].sty
{
422 ty
::ty_tup(ref tys
) => &**tys
,
423 _
=> bcx
.sess().bug(&format
!("trans_fn_once_adapter_shim: not rust-call! \
425 closure_def_id
.repr(tcx
)))
430 .map(|(i
, _
)| get_param(lloncefn
, fcx
.arg_pos(i
+1) as u32))
434 fcx
.llretslotptr
.get().map(
435 |_
| expr
::SaveIn(fcx
.get_ret_slot(bcx
, sig
.output
, "ret_slot")));
437 let callee_data
= TraitItem(MethodData
{ llfn
: llreffn
,
438 llself
: env_datum
.val
});
440 bcx
= callee
::trans_call_inner(bcx
,
443 |bcx
, _
| Callee { bcx: bcx, data: callee_data }
,
447 fcx
.pop_custom_cleanup_scope(self_scope
);
449 finish_fn(&fcx
, bcx
, sig
.output
, DebugLoc
::None
);