]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/closure.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[rust.git] / src / librustc_trans / trans / closure.rs
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.
4 //
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.
10
11 pub use self::ClosureKind::*;
12
13 use back::abi;
14 use back::link::mangle_internal_name_by_path_and_seq;
15 use llvm::ValueRef;
16 use middle::def;
17 use middle::mem_categorization::Typer;
18 use trans::adt;
19 use trans::base::*;
20 use trans::build::*;
21 use trans::cleanup::{CleanupMethods, ScopeId};
22 use trans::common::*;
23 use trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
24 use trans::debuginfo;
25 use trans::expr;
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;
34
35 use arena::TypedArena;
36 use syntax::ast;
37 use syntax::ast_util;
38
39 // ___Good to know (tm)__________________________________________________
40 //
41 // The layout of a closure environment in memory is
42 // roughly as follows:
43 //
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 {
50 //       upvar1_t upvar1;
51 //       ...
52 //       upvarN_t upvarN;
53 //    }
54 // };
55 //
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
63 // the stack.
64 //
65 // ## Opaque closures and the embedded type descriptor ##
66 //
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
72 // closure".
73 //
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.
78 //
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.
83 //
84 // ## Subtleties concerning alignment ##
85 //
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.
93 //
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.
102 //
103 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
104
105 pub struct EnvValue<'tcx> {
106     action: ast::CaptureClause,
107     datum: Datum<'tcx, Lvalue>
108 }
109
110 impl<'tcx> Copy for EnvValue<'tcx> {}
111
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))
115     }
116 }
117
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>])
121                             -> Ty<'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| {
127         match bv.action {
128             ast::CaptureByValue => bv.datum.ty,
129             ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
130         }
131     }).collect();
132     let cdata_ty = ty::mk_tup(tcx, bound_tys);
133     debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty));
134     return cdata_ty;
135 }
136
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))
140 }
141
142 fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
143                              store: ty::TraitStore,
144                              cdata_ty: Ty<'tcx>)
145                              -> Result<'blk, 'tcx> {
146     let _icx = push_ctxt("closure::allocate_cbox");
147     let tcx = bcx.tcx();
148
149     // Allocate and initialize the box:
150     let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
151     match store {
152         ty::UniqTraitStore => {
153             malloc_raw_dyn_proc(bcx, cbox_ty)
154         }
155         ty::RegionTraitStore(..) => {
156             let llbox = alloc_ty(bcx, cbox_ty, "__closure");
157             Result::new(bcx, llbox)
158         }
159     }
160 }
161
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
166 }
167
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");
177     let ccx = bcx.ccx();
178     let tcx = ccx.tcx();
179
180     // compute the type of the closure
181     let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice());
182
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,
185     // whatever.
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);
189
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),
193                               cdata_ty: cdata_ty,
194                               bcx: bcx};
195     }
196
197     // allocate closure in the heap
198     let Result {bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty);
199
200     let llbox = PointerCast(bcx, llbox, llboxptr_ty);
201     debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty));
202
203     // Copy expr values into boxed bindings.
204     let mut bcx = bcx;
205     for (i, bv) in bound_values.into_iter().enumerate() {
206         debug!("Copy {} into closure", bv.to_string(ccx));
207
208         if ccx.sess().asm_comments() {
209             add_comment(bcx, format!("Copy {} into closure",
210                                      bv.to_string(ccx)).as_slice());
211         }
212
213         let bound_data = GEPi(bcx, llbox, &[0u, abi::BOX_FIELD_BODY, i]);
214
215         match bv.action {
216             ast::CaptureByValue => {
217                 bcx = bv.datum.store_to(bcx, bound_data);
218             }
219             ast::CaptureByRef => {
220                 Store(bcx, bv.datum.to_llref(), bound_data);
221             }
222         }
223     }
224
225     ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
226 }
227
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");
236
237     // If we need to, package up the iterator body to call
238     let bcx = bcx0;
239
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});
245     }
246
247     store_environment(bcx, env_vals, store)
248 }
249
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>,
254                                 cdata_ty: Ty<'tcx>,
255                                 freevars: &[ty::Freevar],
256                                 store: ty::TraitStore)
257                                 -> Block<'blk, 'tcx> {
258     let _icx = push_ctxt("closure::load_environment");
259
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());
262
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);
268         Some(alloc)
269     } else {
270         None
271     };
272
273     // Populate the upvars from the environment
274     let mut i = 0u;
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);
280                 true
281             }
282             ty::UniqTraitStore => false
283         };
284         let def_id = freevar.def.def_id();
285
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(
289                 bcx,
290                 def_id.node,
291                 env_pointer_alloca,
292                 i,
293                 captured_by_ref,
294                 freevar.span);
295         }
296
297         i += 1u;
298     }
299
300     bcx
301 }
302
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");
310
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,
319                                          self_type,
320                                          "unboxed_closure_env");
321         store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
322         datum.val
323     } else {
324         bcx.fcx.llenv.unwrap()
325     };
326
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);
332         Some(alloc)
333     } else {
334         None
335     };
336
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);
342                 true
343             }
344             ast::CaptureByValue => false
345         };
346         let def_id = freevar.def.def_id();
347         bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
348
349         if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue {
350             bcx.fcx.schedule_drop_mem(arg_scope_id,
351                                       upvar_ptr,
352                                       node_id_type(bcx, def_id.node))
353         }
354
355         if let Some(env_pointer_alloca) = env_pointer_alloca {
356             debuginfo::create_captured_var_metadata(
357                 bcx,
358                 def_id.node,
359                 env_pointer_alloca,
360                 i,
361                 captured_by_ref,
362                 freevar.span);
363         }
364     }
365
366     bcx
367 }
368
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]));
373 }
374
375 #[deriving(PartialEq)]
376 pub enum ClosureKind<'tcx> {
377     NotClosure,
378     // See load_environment.
379     BoxedClosure(Ty<'tcx>, ty::TraitStore),
380     // See load_unboxed_closure_environment.
381     UnboxedClosure(ast::CaptureClause)
382 }
383
384 pub struct ClosureEnv<'a, 'tcx> {
385     freevars: &'a [ty::Freevar],
386     pub kind: ClosureKind<'tcx>
387 }
388
389 impl<'a, 'tcx> ClosureEnv<'a, 'tcx> {
390     pub fn new(freevars: &'a [ty::Freevar], kind: ClosureKind<'tcx>)
391                -> ClosureEnv<'a, 'tcx> {
392         ClosureEnv {
393             freevars: freevars,
394             kind: kind
395         }
396     }
397
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() {
402             return bcx;
403         }
404
405         match self.kind {
406             NotClosure => bcx,
407             BoxedClosure(cdata_ty, store) => {
408                 load_environment(bcx, cdata_ty, self.freevars, store)
409             }
410             UnboxedClosure(freevar_mode) => {
411                 load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, self.freevars)
412             }
413         }
414     }
415 }
416
417 /// Translates the body of a closure expression.
418 ///
419 /// - `store`
420 /// - `decl`
421 /// - `body`
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,
428                                  decl: &ast::FnDecl,
429                                  body: &ast::Block,
430                                  id: ast::NodeId,
431                                  dest: expr::Dest)
432                                  -> Block<'blk, 'tcx> {
433     let _icx = push_ctxt("closure::trans_expr_fn");
434
435     let dest_addr = match dest {
436         expr::SaveIn(p) => p,
437         expr::Ignore => {
438             return bcx; // closure construction is non-side-effecting
439         }
440     };
441
442     let ccx = bcx.ccx();
443     let tcx = bcx.tcx();
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")
447     });
448     let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice());
449
450     // set an inline hint for all closures
451     set_inline_hint(llfn);
452
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());
456
457     let ClosureResult {
458         llbox,
459         cdata_ty,
460         bcx
461     } = build_closure(bcx, freevar_mode, &freevars, store);
462
463     trans_closure(ccx,
464                   decl,
465                   body,
466                   llfn,
467                   bcx.fcx.param_substs,
468                   id,
469                   &[],
470                   ty::ty_fn_ret(fty),
471                   ty::ty_fn_abi(fty),
472                   ClosureEnv::new(freevars.as_slice(),
473                                   BoxedClosure(cdata_ty, store)));
474     fill_fn_pair(bcx, dest_addr, llfn, llbox);
475     bcx
476 }
477
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> {
484     let ccx = bcx.ccx();
485     if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
486         // Not an unboxed closure.
487         return None
488     }
489
490     let function_type = ty::node_id_to_type(bcx.tcx(), closure_id.node);
491     let function_type = function_type.subst(bcx.tcx(), substs);
492
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(),
498         _ => unreachable!()
499     };
500     let mono_id = MonoId {
501         def: closure_id,
502         params: params
503     };
504
505     match ccx.unboxed_closure_vals().borrow().get(&mono_id) {
506         Some(llfn) => {
507             debug!("get_or_create_declaration_if_unboxed_closure(): found \
508                     closure");
509             return Some(*llfn)
510         }
511         None => {}
512     }
513
514     let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
515         mangle_internal_name_by_path_and_seq(path, "unboxed_closure")
516     });
517
518     let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice());
519
520     // set an inline hint for all closures
521     set_inline_hint(llfn);
522
523     debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \
524             closure {} (type {})",
525            mono_id,
526            ccx.tn().type_to_string(val_ty(llfn)));
527     ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn);
528
529     Some(llfn)
530 }
531
532 pub fn trans_unboxed_closure<'blk, 'tcx>(
533                              mut bcx: Block<'blk, 'tcx>,
534                              decl: &ast::FnDecl,
535                              body: &ast::Block,
536                              id: ast::NodeId,
537                              dest: expr::Dest)
538                              -> Block<'blk, 'tcx> {
539     let _icx = push_ctxt("closure::trans_unboxed_closure");
540
541     debug!("trans_unboxed_closure()");
542
543     let closure_id = ast_util::local_def(id);
544     let llfn = get_or_create_declaration_if_unboxed_closure(
545         bcx,
546         closure_id,
547         bcx.fcx.param_substs).unwrap();
548
549     let function_type = (*bcx.tcx().unboxed_closures.borrow())[closure_id]
550                                                               .closure_type
551                                                               .clone();
552     let function_type = ty::mk_closure(bcx.tcx(), function_type);
553
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);
557
558     trans_closure(bcx.ccx(),
559                   decl,
560                   body,
561                   llfn,
562                   bcx.fcx.param_substs,
563                   id,
564                   &[],
565                   ty::ty_fn_ret(function_type),
566                   ty::ty_fn_abi(function_type),
567                   ClosureEnv::new(freevars.as_slice(),
568                                   UnboxedClosure(freevar_mode)));
569
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,
575         expr::Ignore => {
576             debug!("trans_unboxed_closure() ignoring result");
577             return bcx
578         }
579     };
580
581     let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id));
582
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,
587                                                    &*repr,
588                                                    dest_addr,
589                                                    0,
590                                                    i);
591         match freevar_mode {
592             ast::CaptureByValue => {
593                 bcx = datum.store_to(bcx, upvar_slot_dest);
594             }
595             ast::CaptureByRef => {
596                 Store(bcx, datum.to_llref(), upvar_slot_dest);
597             }
598         }
599     }
600     adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
601
602     bcx
603 }
604
605 pub fn get_wrapper_for_bare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
606                                          closure_ty: Ty<'tcx>,
607                                          def: def::Def,
608                                          fn_ptr: ValueRef,
609                                          is_local: bool) -> ValueRef {
610
611     let def_id = match def {
612         def::DefFn(did, _) | def::DefStaticMethod(did, _) |
613         def::DefVariant(_, did, _) | def::DefStruct(did) => did,
614         _ => {
615             ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
616                                     expected a statically resolved fn, got \
617                                     {}",
618                                     def).as_slice());
619         }
620     };
621
622     match ccx.closure_bare_wrapper_cache().borrow().get(&fn_ptr) {
623         Some(&llval) => return llval,
624         None => {}
625     }
626
627     let tcx = ccx.tcx();
628
629     debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
630
631     let f = match closure_ty.sty {
632         ty::ty_closure(ref f) => f,
633         _ => {
634             ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
635                                     expected a closure ty, got {}",
636                                     closure_ty.repr(tcx)).as_slice());
637         }
638     };
639
640     let name = ty::with_path(tcx, def_id, |path| {
641         mangle_internal_name_by_path_and_seq(path, "as_closure")
642     });
643     let llfn = if is_local {
644         decl_internal_rust_fn(ccx, closure_ty, name.as_slice())
645     } else {
646         decl_rust_fn(ccx, closure_ty, name.as_slice())
647     };
648
649     ccx.closure_bare_wrapper_cache().borrow_mut().insert(fn_ptr, llfn);
650
651     // This is only used by statics inlined from a different crate.
652     if !is_local {
653         // Don't regenerate the wrapper, just reuse the original one.
654         return llfn;
655     }
656
657     let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
658
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);
664
665     let args = create_datums_for_fn_args(&fcx,
666                                          ty::ty_fn_args(closure_ty)
667                                             .as_slice());
668     let mut llargs = Vec::new();
669     match fcx.llretslotptr.get() {
670         Some(llretptr) => {
671             assert!(!fcx.needs_ret_allocas);
672             llargs.push(llretptr);
673         }
674         None => {}
675     }
676     llargs.extend(args.iter().map(|arg| arg.val));
677
678     let retval = Call(bcx, fn_ptr, llargs.as_slice(), None);
679     match f.sig.output {
680         ty::FnConverging(output_type) => {
681             if return_type_is_void(ccx, output_type) || fcx.llretslotptr.get().is_some() {
682                 RetVoid(bcx);
683             } else {
684                 Ret(bcx, retval);
685             }
686         }
687         ty::FnDiverging => {
688             RetVoid(bcx);
689         }
690     }
691
692     // HACK(eddyb) finish_fn cannot be used here, we returned directly.
693     debuginfo::clear_source_location(&fcx);
694     fcx.cleanup();
695
696     llfn
697 }
698
699 pub fn make_closure_from_bare_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
700                                              closure_ty: Ty<'tcx>,
701                                              def: def::Def,
702                                              fn_ptr: ValueRef)
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())));
707
708     DatumBlock::new(bcx, scratch.to_expr_datum())
709 }