]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/closure.rs
Add verbose option to rustdoc in order to fix problem with --version
[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::mem_categorization::Typer;
17 use trans::adt;
18 use trans::base::*;
19 use trans::build::*;
20 use trans::cleanup::{CleanupMethods, ScopeId};
21 use trans::common::*;
22 use trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
23 use trans::debuginfo;
24 use trans::expr;
25 use trans::monomorphize::MonoId;
26 use trans::type_of::*;
27 use trans::type_::Type;
28 use middle::ty::{mod, Ty};
29 use middle::subst::{Subst, Substs};
30 use session::config::FullDebugInfo;
31 use util::ppaux::Repr;
32 use util::ppaux::ty_to_string;
33
34 use arena::TypedArena;
35 use syntax::ast;
36 use syntax::ast_util;
37
38 // ___Good to know (tm)__________________________________________________
39 //
40 // The layout of a closure environment in memory is
41 // roughly as follows:
42 //
43 // struct rust_opaque_box {         // see rust_internal.h
44 //   unsigned ref_count;            // obsolete (part of @T's header)
45 //   fn(void*) *drop_glue;          // destructor (for proc)
46 //   rust_opaque_box *prev;         // obsolete (part of @T's header)
47 //   rust_opaque_box *next;         // obsolete (part of @T's header)
48 //   struct closure_data {
49 //       upvar1_t upvar1;
50 //       ...
51 //       upvarN_t upvarN;
52 //    }
53 // };
54 //
55 // Note that the closure is itself a rust_opaque_box.  This is true
56 // even for ~fn and ||, because we wish to keep binary compatibility
57 // between all kinds of closures.  The allocation strategy for this
58 // closure depends on the closure type.  For a sendfn, the closure
59 // (and the referenced type descriptors) will be allocated in the
60 // exchange heap.  For a fn, the closure is allocated in the task heap
61 // and is reference counted.  For a block, the closure is allocated on
62 // the stack.
63 //
64 // ## Opaque closures and the embedded type descriptor ##
65 //
66 // One interesting part of closures is that they encapsulate the data
67 // that they close over.  So when I have a ptr to a closure, I do not
68 // know how many type descriptors it contains nor what upvars are
69 // captured within.  That means I do not know precisely how big it is
70 // nor where its fields are located.  This is called an "opaque
71 // closure".
72 //
73 // Typically an opaque closure suffices because we only manipulate it
74 // by ptr.  The routine Type::at_box().ptr_to() returns an appropriate
75 // type for such an opaque closure; it allows access to the box fields,
76 // but not the closure_data itself.
77 //
78 // But sometimes, such as when cloning or freeing a closure, we need
79 // to know the full information.  That is where the type descriptor
80 // that defines the closure comes in handy.  We can use its take and
81 // drop glue functions to allocate/free data as needed.
82 //
83 // ## Subtleties concerning alignment ##
84 //
85 // It is important that we be able to locate the closure data *without
86 // knowing the kind of data that is being bound*.  This can be tricky
87 // because the alignment requirements of the bound data affects the
88 // alignment requires of the closure_data struct as a whole.  However,
89 // right now this is a non-issue in any case, because the size of the
90 // rust_opaque_box header is always a multiple of 16-bytes, which is
91 // the maximum alignment requirement we ever have to worry about.
92 //
93 // The only reason alignment matters is that, in order to learn what data
94 // is bound, we would normally first load the type descriptors: but their
95 // location is ultimately depend on their content!  There is, however, a
96 // workaround.  We can load the tydesc from the rust_opaque_box, which
97 // describes the closure_data struct and has self-contained derived type
98 // descriptors, and read the alignment from there.   It's just annoying to
99 // do.  Hopefully should this ever become an issue we'll have monomorphized
100 // and type descriptors will all be a bad dream.
101 //
102 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103
104 #[deriving(Copy)]
105 pub struct EnvValue<'tcx> {
106     action: ast::CaptureClause,
107     datum: Datum<'tcx, Lvalue>
108 }
109
110 impl<'tcx> EnvValue<'tcx> {
111     pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String {
112         format!("{}({})", self.action, self.datum.to_string(ccx))
113     }
114 }
115
116 // Given a closure ty, emits a corresponding tuple ty
117 pub fn mk_closure_tys<'tcx>(tcx: &ty::ctxt<'tcx>,
118                             bound_values: &[EnvValue<'tcx>])
119                             -> Ty<'tcx> {
120     // determine the types of the values in the env.  Note that this
121     // is the actual types that will be stored in the map, not the
122     // logical types as the user sees them, so by-ref upvars must be
123     // converted to ptrs.
124     let bound_tys = bound_values.iter().map(|bv| {
125         match bv.action {
126             ast::CaptureByValue => bv.datum.ty,
127             ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
128         }
129     }).collect();
130     let cdata_ty = ty::mk_tup(tcx, bound_tys);
131     debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty));
132     return cdata_ty;
133 }
134
135 fn tuplify_box_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
136     let ptr = ty::mk_imm_ptr(tcx, tcx.types.i8);
137     ty::mk_tup(tcx, vec!(tcx.types.uint, ty::mk_nil_ptr(tcx), ptr, ptr, t))
138 }
139
140 fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
141                              store: ty::TraitStore,
142                              cdata_ty: Ty<'tcx>)
143                              -> Result<'blk, 'tcx> {
144     let _icx = push_ctxt("closure::allocate_cbox");
145     let tcx = bcx.tcx();
146
147     // Allocate and initialize the box:
148     let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
149     match store {
150         ty::UniqTraitStore => {
151             malloc_raw_dyn_proc(bcx, cbox_ty)
152         }
153         ty::RegionTraitStore(..) => {
154             let llbox = alloc_ty(bcx, cbox_ty, "__closure");
155             Result::new(bcx, llbox)
156         }
157     }
158 }
159
160 pub struct ClosureResult<'blk, 'tcx: 'blk> {
161     llbox: ValueRef,        // llvalue of ptr to closure
162     cdata_ty: Ty<'tcx>,     // type of the closure data
163     bcx: Block<'blk, 'tcx>  // final bcx
164 }
165
166 // Given a block context and a list of tydescs and values to bind
167 // construct a closure out of them. If copying is true, it is a
168 // heap allocated closure that copies the upvars into environment.
169 // Otherwise, it is stack allocated and copies pointers to the upvars.
170 pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
171                                      bound_values: Vec<EnvValue<'tcx>> ,
172                                      store: ty::TraitStore)
173                                      -> ClosureResult<'blk, 'tcx> {
174     let _icx = push_ctxt("closure::store_environment");
175     let ccx = bcx.ccx();
176     let tcx = ccx.tcx();
177
178     // compute the type of the closure
179     let cdata_ty = mk_closure_tys(tcx, bound_values[]);
180
181     // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
182     // tuple.  This could be a ptr in uniq or a box or on stack,
183     // whatever.
184     let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
185     let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
186     let llboxptr_ty = type_of(ccx, cboxptr_ty);
187
188     // If there are no bound values, no point in allocating anything.
189     if bound_values.is_empty() {
190         return ClosureResult {llbox: C_null(llboxptr_ty),
191                               cdata_ty: cdata_ty,
192                               bcx: bcx};
193     }
194
195     // allocate closure in the heap
196     let Result {bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty);
197
198     let llbox = PointerCast(bcx, llbox, llboxptr_ty);
199     debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty));
200
201     // Copy expr values into boxed bindings.
202     let mut bcx = bcx;
203     for (i, bv) in bound_values.into_iter().enumerate() {
204         debug!("Copy {} into closure", bv.to_string(ccx));
205
206         if ccx.sess().asm_comments() {
207             add_comment(bcx, format!("Copy {} into closure",
208                                      bv.to_string(ccx))[]);
209         }
210
211         let bound_data = GEPi(bcx, llbox, &[0u, abi::BOX_FIELD_BODY, i]);
212
213         match bv.action {
214             ast::CaptureByValue => {
215                 bcx = bv.datum.store_to(bcx, bound_data);
216             }
217             ast::CaptureByRef => {
218                 Store(bcx, bv.datum.to_llref(), bound_data);
219             }
220         }
221     }
222
223     ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
224 }
225
226 // Given a context and a list of upvars, build a closure. This just
227 // collects the upvars and packages them up for store_environment.
228 fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>,
229                              freevar_mode: ast::CaptureClause,
230                              freevars: &Vec<ty::Freevar>,
231                              store: ty::TraitStore)
232                              -> ClosureResult<'blk, 'tcx> {
233     let _icx = push_ctxt("closure::build_closure");
234
235     // If we need to, package up the iterator body to call
236     let bcx = bcx0;
237
238     // Package up the captured upvars
239     let mut env_vals = Vec::new();
240     for freevar in freevars.iter() {
241         let datum = expr::trans_local_var(bcx, freevar.def);
242         env_vals.push(EnvValue {action: freevar_mode, datum: datum});
243     }
244
245     store_environment(bcx, env_vals, store)
246 }
247
248 // Given an enclosing block context, a new function context, a closure type,
249 // and a list of upvars, generate code to load and populate the environment
250 // with the upvars and type descriptors.
251 fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
252                                 cdata_ty: Ty<'tcx>,
253                                 freevars: &[ty::Freevar],
254                                 store: ty::TraitStore)
255                                 -> Block<'blk, 'tcx> {
256     let _icx = push_ctxt("closure::load_environment");
257
258     // Load a pointer to the closure data, skipping over the box header:
259     let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
260
261     // Store the pointer to closure data in an alloca for debug info because that's what the
262     // llvm.dbg.declare intrinsic expects
263     let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
264         let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
265         Store(bcx, llcdata, alloc);
266         Some(alloc)
267     } else {
268         None
269     };
270
271     // Populate the upvars from the environment
272     let mut i = 0u;
273     for freevar in freevars.iter() {
274         let mut upvarptr = GEPi(bcx, llcdata, &[0u, i]);
275         let captured_by_ref = match store {
276             ty::RegionTraitStore(..) => {
277                 upvarptr = Load(bcx, upvarptr);
278                 true
279             }
280             ty::UniqTraitStore => false
281         };
282         let def_id = freevar.def.def_id();
283
284         bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr);
285         if let Some(env_pointer_alloca) = env_pointer_alloca {
286             debuginfo::create_captured_var_metadata(
287                 bcx,
288                 def_id.node,
289                 env_pointer_alloca,
290                 i,
291                 captured_by_ref,
292                 freevar.span);
293         }
294
295         i += 1u;
296     }
297
298     bcx
299 }
300
301 fn load_unboxed_closure_environment<'blk, 'tcx>(
302                                     bcx: Block<'blk, 'tcx>,
303                                     arg_scope_id: ScopeId,
304                                     freevar_mode: ast::CaptureClause,
305                                     freevars: &[ty::Freevar])
306                                     -> Block<'blk, 'tcx> {
307     let _icx = push_ctxt("closure::load_environment");
308
309     // Special case for small by-value selfs.
310     let closure_id = ast_util::local_def(bcx.fcx.id);
311     let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id,
312                                                   node_id_type(bcx, closure_id.node));
313     let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id);
314     let llenv = if kind == ty::FnOnceUnboxedClosureKind &&
315             !arg_is_indirect(bcx.ccx(), self_type) {
316         let datum = rvalue_scratch_datum(bcx,
317                                          self_type,
318                                          "unboxed_closure_env");
319         store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
320         datum.val
321     } else {
322         bcx.fcx.llenv.unwrap()
323     };
324
325     // Store the pointer to closure data in an alloca for debug info because that's what the
326     // llvm.dbg.declare intrinsic expects
327     let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
328         let alloc = alloca(bcx, val_ty(llenv), "__debuginfo_env_ptr");
329         Store(bcx, llenv, alloc);
330         Some(alloc)
331     } else {
332         None
333     };
334
335     for (i, freevar) in freevars.iter().enumerate() {
336         let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
337         let captured_by_ref = match freevar_mode {
338             ast::CaptureByRef => {
339                 upvar_ptr = Load(bcx, upvar_ptr);
340                 true
341             }
342             ast::CaptureByValue => false
343         };
344         let def_id = freevar.def.def_id();
345         bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
346
347         if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue {
348             bcx.fcx.schedule_drop_mem(arg_scope_id,
349                                       upvar_ptr,
350                                       node_id_type(bcx, def_id.node))
351         }
352
353         if let Some(env_pointer_alloca) = env_pointer_alloca {
354             debuginfo::create_captured_var_metadata(
355                 bcx,
356                 def_id.node,
357                 env_pointer_alloca,
358                 i,
359                 captured_by_ref,
360                 freevar.span);
361         }
362     }
363
364     bcx
365 }
366
367 fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
368     Store(bcx, llfn, GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]));
369     let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
370     Store(bcx, llenvptr, GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]));
371 }
372
373 #[deriving(PartialEq)]
374 pub enum ClosureKind<'tcx> {
375     NotClosure,
376     // See load_environment.
377     BoxedClosure(Ty<'tcx>, ty::TraitStore),
378     // See load_unboxed_closure_environment.
379     UnboxedClosure(ast::CaptureClause)
380 }
381
382 pub struct ClosureEnv<'a, 'tcx> {
383     freevars: &'a [ty::Freevar],
384     pub kind: ClosureKind<'tcx>
385 }
386
387 impl<'a, 'tcx> ClosureEnv<'a, 'tcx> {
388     pub fn new(freevars: &'a [ty::Freevar], kind: ClosureKind<'tcx>)
389                -> ClosureEnv<'a, 'tcx> {
390         ClosureEnv {
391             freevars: freevars,
392             kind: kind
393         }
394     }
395
396     pub fn load<'blk>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
397                       -> Block<'blk, 'tcx> {
398         // Don't bother to create the block if there's nothing to load
399         if self.freevars.is_empty() {
400             return bcx;
401         }
402
403         match self.kind {
404             NotClosure => bcx,
405             BoxedClosure(cdata_ty, store) => {
406                 load_environment(bcx, cdata_ty, self.freevars, store)
407             }
408             UnboxedClosure(freevar_mode) => {
409                 load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, self.freevars)
410             }
411         }
412     }
413 }
414
415 /// Translates the body of a closure expression.
416 ///
417 /// - `store`
418 /// - `decl`
419 /// - `body`
420 /// - `id`: The id of the closure expression.
421 /// - `cap_clause`: information about captured variables, if any.
422 /// - `dest`: where to write the closure value, which must be a
423 ///   (fn ptr, env) pair
424 pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
425                                  store: ty::TraitStore,
426                                  decl: &ast::FnDecl,
427                                  body: &ast::Block,
428                                  id: ast::NodeId,
429                                  dest: expr::Dest)
430                                  -> Block<'blk, 'tcx> {
431     let _icx = push_ctxt("closure::trans_expr_fn");
432
433     let dest_addr = match dest {
434         expr::SaveIn(p) => p,
435         expr::Ignore => {
436             return bcx; // closure construction is non-side-effecting
437         }
438     };
439
440     let ccx = bcx.ccx();
441     let tcx = bcx.tcx();
442     let fty = node_id_type(bcx, id);
443     let s = tcx.map.with_path(id, |path| {
444         mangle_internal_name_by_path_and_seq(path, "closure")
445     });
446     let llfn = decl_internal_rust_fn(ccx, fty, s[]);
447
448     // set an inline hint for all closures
449     set_inline_hint(llfn);
450
451     let freevar_mode = tcx.capture_mode(id);
452     let freevars: Vec<ty::Freevar> =
453         ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect());
454
455     let ClosureResult {
456         llbox,
457         cdata_ty,
458         bcx
459     } = build_closure(bcx, freevar_mode, &freevars, store);
460
461     trans_closure(ccx,
462                   decl,
463                   body,
464                   llfn,
465                   bcx.fcx.param_substs,
466                   id,
467                   &[],
468                   ty::ty_fn_ret(fty),
469                   ty::ty_fn_abi(fty),
470                   ClosureEnv::new(freevars[],
471                                   BoxedClosure(cdata_ty, store)));
472     fill_fn_pair(bcx, dest_addr, llfn, llbox);
473     bcx
474 }
475
476 /// Returns the LLVM function declaration for an unboxed closure, creating it
477 /// if necessary. If the ID does not correspond to a closure ID, returns None.
478 pub fn get_or_create_declaration_if_unboxed_closure<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
479                                                                 closure_id: ast::DefId,
480                                                                 substs: &Substs<'tcx>)
481                                                                 -> Option<ValueRef> {
482     let ccx = bcx.ccx();
483     if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
484         // Not an unboxed closure.
485         return None
486     }
487
488     let function_type = ty::node_id_to_type(bcx.tcx(), closure_id.node);
489     let function_type = function_type.subst(bcx.tcx(), substs);
490
491     // Normalize type so differences in regions and typedefs don't cause
492     // duplicate declarations
493     let function_type = ty::normalize_ty(bcx.tcx(), function_type);
494     let params = match function_type.sty {
495         ty::ty_unboxed_closure(_, _, ref substs) => substs.types.clone(),
496         _ => unreachable!()
497     };
498     let mono_id = MonoId {
499         def: closure_id,
500         params: params
501     };
502
503     match ccx.unboxed_closure_vals().borrow().get(&mono_id) {
504         Some(llfn) => {
505             debug!("get_or_create_declaration_if_unboxed_closure(): found \
506                     closure");
507             return Some(*llfn)
508         }
509         None => {}
510     }
511
512     let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
513         mangle_internal_name_by_path_and_seq(path, "unboxed_closure")
514     });
515
516     let llfn = decl_internal_rust_fn(ccx, function_type, symbol[]);
517
518     // set an inline hint for all closures
519     set_inline_hint(llfn);
520
521     debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \
522             closure {} (type {})",
523            mono_id,
524            ccx.tn().type_to_string(val_ty(llfn)));
525     ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn);
526
527     Some(llfn)
528 }
529
530 pub fn trans_unboxed_closure<'blk, 'tcx>(
531                              mut bcx: Block<'blk, 'tcx>,
532                              decl: &ast::FnDecl,
533                              body: &ast::Block,
534                              id: ast::NodeId,
535                              dest: expr::Dest)
536                              -> Block<'blk, 'tcx> {
537     let _icx = push_ctxt("closure::trans_unboxed_closure");
538
539     debug!("trans_unboxed_closure()");
540
541     let closure_id = ast_util::local_def(id);
542     let llfn = get_or_create_declaration_if_unboxed_closure(
543         bcx,
544         closure_id,
545         bcx.fcx.param_substs).unwrap();
546
547     let function_type = (*bcx.tcx().unboxed_closures.borrow())[closure_id]
548                                                               .closure_type
549                                                               .clone();
550     let function_type = ty::mk_closure(bcx.tcx(), function_type);
551
552     let freevars: Vec<ty::Freevar> =
553         ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect());
554     let freevar_mode = bcx.tcx().capture_mode(id);
555
556     trans_closure(bcx.ccx(),
557                   decl,
558                   body,
559                   llfn,
560                   bcx.fcx.param_substs,
561                   id,
562                   &[],
563                   ty::ty_fn_ret(function_type),
564                   ty::ty_fn_abi(function_type),
565                   ClosureEnv::new(freevars[],
566                                   UnboxedClosure(freevar_mode)));
567
568     // Don't hoist this to the top of the function. It's perfectly legitimate
569     // to have a zero-size unboxed closure (in which case dest will be
570     // `Ignore`) and we must still generate the closure body.
571     let dest_addr = match dest {
572         expr::SaveIn(p) => p,
573         expr::Ignore => {
574             debug!("trans_unboxed_closure() ignoring result");
575             return bcx
576         }
577     };
578
579     let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id));
580
581     // Create the closure.
582     for (i, freevar) in freevars.iter().enumerate() {
583         let datum = expr::trans_local_var(bcx, freevar.def);
584         let upvar_slot_dest = adt::trans_field_ptr(bcx,
585                                                    &*repr,
586                                                    dest_addr,
587                                                    0,
588                                                    i);
589         match freevar_mode {
590             ast::CaptureByValue => {
591                 bcx = datum.store_to(bcx, upvar_slot_dest);
592             }
593             ast::CaptureByRef => {
594                 Store(bcx, datum.to_llref(), upvar_slot_dest);
595             }
596         }
597     }
598     adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
599
600     bcx
601 }
602
603 pub fn get_wrapper_for_bare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
604                                          closure_ty: Ty<'tcx>,
605                                          def_id: ast::DefId,
606                                          fn_ptr: ValueRef,
607                                          is_local: bool) -> ValueRef {
608
609     match ccx.closure_bare_wrapper_cache().borrow().get(&fn_ptr) {
610         Some(&llval) => return llval,
611         None => {}
612     }
613
614     let tcx = ccx.tcx();
615
616     debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
617
618     let f = match closure_ty.sty {
619         ty::ty_closure(ref f) => f,
620         _ => {
621             ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
622                                     expected a closure ty, got {}",
623                                     closure_ty.repr(tcx))[]);
624         }
625     };
626
627     let name = ty::with_path(tcx, def_id, |path| {
628         mangle_internal_name_by_path_and_seq(path, "as_closure")
629     });
630     let llfn = if is_local {
631         decl_internal_rust_fn(ccx, closure_ty, name[])
632     } else {
633         decl_rust_fn(ccx, closure_ty, name[])
634     };
635
636     ccx.closure_bare_wrapper_cache().borrow_mut().insert(fn_ptr, llfn);
637
638     // This is only used by statics inlined from a different crate.
639     if !is_local {
640         // Don't regenerate the wrapper, just reuse the original one.
641         return llfn;
642     }
643
644     let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
645
646     let arena = TypedArena::new();
647     let empty_param_substs = Substs::trans_empty();
648     let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, true, f.sig.0.output,
649                           &empty_param_substs, None, &arena);
650     let bcx = init_function(&fcx, true, f.sig.0.output);
651
652     let args = create_datums_for_fn_args(&fcx,
653                                          ty::ty_fn_args(closure_ty)
654                                             []);
655     let mut llargs = Vec::new();
656     match fcx.llretslotptr.get() {
657         Some(llretptr) => {
658             assert!(!fcx.needs_ret_allocas);
659             llargs.push(llretptr);
660         }
661         None => {}
662     }
663     llargs.extend(args.iter().map(|arg| arg.val));
664
665     let retval = Call(bcx, fn_ptr, llargs.as_slice(), None);
666     match f.sig.0.output {
667         ty::FnConverging(output_type) => {
668             if return_type_is_void(ccx, output_type) || fcx.llretslotptr.get().is_some() {
669                 RetVoid(bcx);
670             } else {
671                 Ret(bcx, retval);
672             }
673         }
674         ty::FnDiverging => {
675             RetVoid(bcx);
676         }
677     }
678
679     // HACK(eddyb) finish_fn cannot be used here, we returned directly.
680     debuginfo::clear_source_location(&fcx);
681     fcx.cleanup();
682
683     llfn
684 }
685
686 pub fn make_closure_from_bare_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
687                                              closure_ty: Ty<'tcx>,
688                                              def_id: ast::DefId,
689                                              fn_ptr: ValueRef)
690                                              -> DatumBlock<'blk, 'tcx, Expr>  {
691     let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
692     let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def_id, fn_ptr, true);
693     fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p(bcx.ccx())));
694
695     DatumBlock::new(bcx, scratch.to_expr_datum())
696 }