]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/common.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[rust.git] / src / librustc_trans / trans / common.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 #![allow(non_camel_case_types, non_snake_case)]
12
13 //! Code that is useful in various trans modules.
14
15 pub use self::ExprOrMethodCall::*;
16
17 use session::Session;
18 use llvm;
19 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef};
20 use llvm::{True, False, Bool};
21 use middle::cfg;
22 use middle::def;
23 use middle::infer;
24 use middle::lang_items::LangItem;
25 use middle::mem_categorization as mc;
26 use middle::region;
27 use middle::subst::{self, Subst, Substs};
28 use trans::base;
29 use trans::build;
30 use trans::cleanup;
31 use trans::consts;
32 use trans::datum;
33 use trans::debuginfo::{self, DebugLoc};
34 use trans::machine;
35 use trans::monomorphize;
36 use trans::type_::Type;
37 use trans::type_of;
38 use middle::traits;
39 use middle::ty::{self, HasProjectionTypes, Ty};
40 use middle::ty_fold;
41 use middle::ty_fold::{TypeFolder, TypeFoldable};
42 use util::ppaux::Repr;
43 use util::nodemap::{FnvHashMap, NodeMap};
44
45 use arena::TypedArena;
46 use libc::{c_uint, c_char};
47 use std::ffi::CString;
48 use std::cell::{Cell, RefCell};
49 use std::vec::Vec;
50 use syntax::ast::Ident;
51 use syntax::ast;
52 use syntax::ast_map::{PathElem, PathName};
53 use syntax::codemap::{DUMMY_SP, Span};
54 use syntax::parse::token::InternedString;
55 use syntax::parse::token;
56 use util::common::memoized;
57 use util::nodemap::FnvHashSet;
58
59 pub use trans::context::CrateContext;
60
61 /// Returns an equivalent value with all free regions removed (note
62 /// that late-bound regions remain, because they are important for
63 /// subtyping, but they are anonymized and normalized as well). This
64 /// is a stronger, caching version of `ty_fold::erase_regions`.
65 pub fn erase_regions<'tcx,T>(cx: &ty::ctxt<'tcx>, value: &T) -> T
66     where T : TypeFoldable<'tcx> + Repr<'tcx>
67 {
68     let value1 = value.fold_with(&mut RegionEraser(cx));
69     debug!("erase_regions({}) = {}",
70            value.repr(cx), value1.repr(cx));
71     return value1;
72
73     struct RegionEraser<'a, 'tcx: 'a>(&'a ty::ctxt<'tcx>);
74
75     impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> {
76         fn tcx(&self) -> &ty::ctxt<'tcx> { self.0 }
77
78         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
79             match self.tcx().normalized_cache.borrow().get(&ty).cloned() {
80                 None => {}
81                 Some(u) => return u
82             }
83
84             let t_norm = ty_fold::super_fold_ty(self, ty);
85             self.tcx().normalized_cache.borrow_mut().insert(ty, t_norm);
86             return t_norm;
87         }
88
89         fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
90             where T : TypeFoldable<'tcx> + Repr<'tcx>
91         {
92             let u = ty::anonymize_late_bound_regions(self.tcx(), t);
93             ty_fold::super_fold_binder(self, &u)
94         }
95
96         fn fold_region(&mut self, r: ty::Region) -> ty::Region {
97             // because late-bound regions affect subtyping, we can't
98             // erase the bound/free distinction, but we can replace
99             // all free regions with 'static.
100             //
101             // Note that we *CAN* replace early-bound regions -- the
102             // type system never "sees" those, they get substituted
103             // away. In trans, they will always be erased to 'static
104             // whenever a substitution occurs.
105             match r {
106                 ty::ReLateBound(..) => r,
107                 _ => ty::ReStatic
108             }
109         }
110
111         fn fold_substs(&mut self,
112                        substs: &subst::Substs<'tcx>)
113                        -> subst::Substs<'tcx> {
114             subst::Substs { regions: subst::ErasedRegions,
115                             types: substs.types.fold_with(self) }
116         }
117     }
118 }
119
120 // Is the type's representation size known at compile time?
121 pub fn type_is_sized<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
122     let param_env = ty::empty_parameter_environment(tcx);
123     ty::type_is_sized(&param_env, DUMMY_SP, ty)
124 }
125
126 pub fn lltype_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
127     match ty.sty {
128         ty::ty_open(_) => true,
129         _ => type_is_sized(cx, ty),
130     }
131 }
132
133 pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
134     match ty.sty {
135         ty::ty_ptr(ty::mt{ty, ..}) |
136         ty::ty_rptr(_, ty::mt{ty, ..}) |
137         ty::ty_uniq(ty) => {
138             !type_is_sized(cx, ty)
139         }
140         _ => {
141             false
142         }
143     }
144 }
145
146 // Return the smallest part of `ty` which is unsized. Fails if `ty` is sized.
147 // 'Smallest' here means component of the static representation of the type; not
148 // the size of an object at runtime.
149 pub fn unsized_part_of_type<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
150     match ty.sty {
151         ty::ty_str | ty::ty_trait(..) | ty::ty_vec(..) => ty,
152         ty::ty_struct(def_id, substs) => {
153             let unsized_fields: Vec<_> =
154                 ty::struct_fields(cx, def_id, substs)
155                 .iter()
156                 .map(|f| f.mt.ty)
157                 .filter(|ty| !type_is_sized(cx, *ty))
158                 .collect();
159
160             // Exactly one of the fields must be unsized.
161             assert!(unsized_fields.len() == 1);
162
163             unsized_part_of_type(cx, unsized_fields[0])
164         }
165         _ => {
166             assert!(type_is_sized(cx, ty),
167                     "unsized_part_of_type failed even though ty is unsized");
168             panic!("called unsized_part_of_type with sized ty");
169         }
170     }
171 }
172
173 // Some things don't need cleanups during unwinding because the
174 // task can free them all at once later. Currently only things
175 // that only contain scalars and shared boxes can avoid unwind
176 // cleanups.
177 pub fn type_needs_unwind_cleanup<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
178     return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| {
179         type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet())
180     });
181
182     fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>,
183                                         ty: Ty<'tcx>,
184                                         tycache: &mut FnvHashSet<Ty<'tcx>>)
185                                         -> bool
186     {
187         // Prevent infinite recursion
188         if !tycache.insert(ty) {
189             return false;
190         }
191
192         let mut needs_unwind_cleanup = false;
193         ty::maybe_walk_ty(ty, |ty| {
194             needs_unwind_cleanup |= match ty.sty {
195                 ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) |
196                 ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false,
197
198                 ty::ty_enum(did, substs) =>
199                     ty::enum_variants(tcx, did).iter().any(|v|
200                         v.args.iter().any(|&aty| {
201                             let t = aty.subst(tcx, substs);
202                             type_needs_unwind_cleanup_(tcx, t, tycache)
203                         })
204                     ),
205
206                 _ => true
207             };
208             !needs_unwind_cleanup
209         });
210         needs_unwind_cleanup
211     }
212 }
213
214 pub fn type_needs_drop<'tcx>(cx: &ty::ctxt<'tcx>,
215                          ty: Ty<'tcx>)
216                          -> bool {
217     ty::type_contents(cx, ty).needs_drop(cx)
218 }
219
220 fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
221     match ty.sty {
222         ty::ty_struct(def_id, substs) => {
223             let fields = ty::lookup_struct_fields(ccx.tcx(), def_id);
224             fields.len() == 1 && {
225                 let ty = ty::lookup_field_type(ccx.tcx(), def_id, fields[0].id, substs);
226                 let ty = monomorphize::normalize_associated_type(ccx.tcx(), &ty);
227                 type_is_immediate(ccx, ty)
228             }
229         }
230         _ => false
231     }
232 }
233
234 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
235     use trans::machine::llsize_of_alloc;
236     use trans::type_of::sizing_type_of;
237
238     let tcx = ccx.tcx();
239     let simple = ty::type_is_scalar(ty) ||
240         ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
241         type_is_newtype_immediate(ccx, ty) ||
242         ty::type_is_simd(tcx, ty);
243     if simple && !type_is_fat_ptr(tcx, ty) {
244         return true;
245     }
246     if !type_is_sized(tcx, ty) {
247         return false;
248     }
249     match ty.sty {
250         ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) | ty::ty_vec(_, Some(_)) |
251         ty::ty_unboxed_closure(..) => {
252             let llty = sizing_type_of(ccx, ty);
253             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
254         }
255         _ => type_is_zero_size(ccx, ty)
256     }
257 }
258
259 /// Identify types which have size zero at runtime.
260 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
261     use trans::machine::llsize_of_alloc;
262     use trans::type_of::sizing_type_of;
263     let llty = sizing_type_of(ccx, ty);
264     llsize_of_alloc(ccx, llty) == 0
265 }
266
267 /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function
268 /// return types. These are `()`, bot, and uninhabited enums. Note that all such types are also
269 /// zero-size, but not all zero-size types use a `void` return type (in order to aid with C ABI
270 /// compatibility).
271 pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool {
272     ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty)
273 }
274
275 /// Generates a unique symbol based off the name given. This is used to create
276 /// unique symbols for things like closures.
277 pub fn gensym_name(name: &str) -> PathElem {
278     let num = token::gensym(name).usize();
279     // use one colon which will get translated to a period by the mangler, and
280     // we're guaranteed that `num` is globally unique for this crate.
281     PathName(token::gensym(&format!("{}:{}", name, num)[]))
282 }
283
284 #[derive(Copy)]
285 pub struct tydesc_info<'tcx> {
286     pub ty: Ty<'tcx>,
287     pub tydesc: ValueRef,
288     pub size: ValueRef,
289     pub align: ValueRef,
290     pub name: ValueRef,
291 }
292
293 /*
294 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
295 *
296 * An "extern" is an LLVM symbol we wind up emitting an undefined external
297 * reference to. This means "we don't have the thing in this compilation unit,
298 * please make sure you link it in at runtime". This could be a reference to
299 * C code found in a C library, or rust code found in a rust crate.
300 *
301 * Most "externs" are implicitly declared (automatically) as a result of a
302 * user declaring an extern _module_ dependency; this causes the rust driver
303 * to locate an extern crate, scan its compilation metadata, and emit extern
304 * declarations for any symbols used by the declaring crate.
305 *
306 * A "foreign" is an extern that references C (or other non-rust ABI) code.
307 * There is no metadata to scan for extern references so in these cases either
308 * a header-digester like bindgen, or manual function prototypes, have to
309 * serve as declarators. So these are usually given explicitly as prototype
310 * declarations, in rust code, with ABI attributes on them noting which ABI to
311 * link via.
312 *
313 * An "upcall" is a foreign call generated by the compiler (not corresponding
314 * to any user-written call in the code) into the runtime library, to perform
315 * some helper task such as bringing a task to life, allocating memory, etc.
316 *
317 */
318
319 #[derive(Copy)]
320 pub struct NodeIdAndSpan {
321     pub id: ast::NodeId,
322     pub span: Span,
323 }
324
325 pub fn expr_info(expr: &ast::Expr) -> NodeIdAndSpan {
326     NodeIdAndSpan { id: expr.id, span: expr.span }
327 }
328
329 pub struct BuilderRef_res {
330     pub b: BuilderRef,
331 }
332
333 impl Drop for BuilderRef_res {
334     fn drop(&mut self) {
335         unsafe {
336             llvm::LLVMDisposeBuilder(self.b);
337         }
338     }
339 }
340
341 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
342     BuilderRef_res {
343         b: b
344     }
345 }
346
347 pub type ExternMap = FnvHashMap<String, ValueRef>;
348
349 pub fn validate_substs(substs: &Substs) {
350     assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
351 }
352
353 // work around bizarre resolve errors
354 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
355 type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
356
357 // Function context.  Every LLVM function we create will have one of
358 // these.
359 pub struct FunctionContext<'a, 'tcx: 'a> {
360     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
361     // address of the first instruction in the sequence of
362     // instructions for this function that will go in the .text
363     // section of the executable we're generating.
364     pub llfn: ValueRef,
365
366     // always an empty parameter-environment
367     pub param_env: ty::ParameterEnvironment<'a, 'tcx>,
368
369     // The environment argument in a closure.
370     pub llenv: Option<ValueRef>,
371
372     // A pointer to where to store the return value. If the return type is
373     // immediate, this points to an alloca in the function. Otherwise, it's a
374     // pointer to the hidden first parameter of the function. After function
375     // construction, this should always be Some.
376     pub llretslotptr: Cell<Option<ValueRef>>,
377
378     // These pub elements: "hoisted basic blocks" containing
379     // administrative activities that have to happen in only one place in
380     // the function, due to LLVM's quirks.
381     // A marker for the place where we want to insert the function's static
382     // allocas, so that LLVM will coalesce them into a single alloca call.
383     pub alloca_insert_pt: Cell<Option<ValueRef>>,
384     pub llreturn: Cell<Option<BasicBlockRef>>,
385
386     // If the function has any nested return's, including something like:
387     // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
388     // we use a separate alloca for each return
389     pub needs_ret_allocas: bool,
390
391     // The a value alloca'd for calls to upcalls.rust_personality. Used when
392     // outputting the resume instruction.
393     pub personality: Cell<Option<ValueRef>>,
394
395     // True if the caller expects this fn to use the out pointer to
396     // return. Either way, your code should write into the slot llretslotptr
397     // points to, but if this value is false, that slot will be a local alloca.
398     pub caller_expects_out_pointer: bool,
399
400     // Maps the DefId's for local variables to the allocas created for
401     // them in llallocas.
402     pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>,
403
404     // Same as above, but for closure upvars
405     pub llupvars: RefCell<NodeMap<ValueRef>>,
406
407     // The NodeId of the function, or -1 if it doesn't correspond to
408     // a user-defined function.
409     pub id: ast::NodeId,
410
411     // If this function is being monomorphized, this contains the type
412     // substitutions used.
413     pub param_substs: &'a Substs<'tcx>,
414
415     // The source span and nesting context where this function comes from, for
416     // error reporting and symbol generation.
417     pub span: Option<Span>,
418
419     // The arena that blocks are allocated from.
420     pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
421
422     // This function's enclosing crate context.
423     pub ccx: &'a CrateContext<'a, 'tcx>,
424
425     // Used and maintained by the debuginfo module.
426     pub debug_context: debuginfo::FunctionDebugContext,
427
428     // Cleanup scopes.
429     pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
430
431     pub cfg: Option<cfg::CFG>,
432 }
433
434 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
435     pub fn arg_pos(&self, arg: uint) -> uint {
436         let arg = self.env_arg_pos() + arg;
437         if self.llenv.is_some() {
438             arg + 1
439         } else {
440             arg
441         }
442     }
443
444     pub fn env_arg_pos(&self) -> uint {
445         if self.caller_expects_out_pointer {
446             1u
447         } else {
448             0u
449         }
450     }
451
452     pub fn cleanup(&self) {
453         unsafe {
454             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
455                                                      .get()
456                                                      .unwrap());
457         }
458     }
459
460     pub fn get_llreturn(&self) -> BasicBlockRef {
461         if self.llreturn.get().is_none() {
462
463             self.llreturn.set(Some(unsafe {
464                 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn,
465                                                     "return\0".as_ptr() as *const _)
466             }))
467         }
468
469         self.llreturn.get().unwrap()
470     }
471
472     pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
473                         output: ty::FnOutput<'tcx>,
474                         name: &str) -> ValueRef {
475         if self.needs_ret_allocas {
476             base::alloca_no_lifetime(bcx, match output {
477                 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
478                 ty::FnDiverging => Type::void(bcx.ccx())
479             }, name)
480         } else {
481             self.llretslotptr.get().unwrap()
482         }
483     }
484
485     pub fn new_block(&'a self,
486                      is_lpad: bool,
487                      name: &str,
488                      opt_node_id: Option<ast::NodeId>)
489                      -> Block<'a, 'tcx> {
490         unsafe {
491             let name = CString::from_slice(name.as_bytes());
492             let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
493                                                            self.llfn,
494                                                            name.as_ptr());
495             BlockS::new(llbb, is_lpad, opt_node_id, self)
496         }
497     }
498
499     pub fn new_id_block(&'a self,
500                         name: &str,
501                         node_id: ast::NodeId)
502                         -> Block<'a, 'tcx> {
503         self.new_block(false, name, Some(node_id))
504     }
505
506     pub fn new_temp_block(&'a self,
507                           name: &str)
508                           -> Block<'a, 'tcx> {
509         self.new_block(false, name, None)
510     }
511
512     pub fn join_blocks(&'a self,
513                        id: ast::NodeId,
514                        in_cxs: &[Block<'a, 'tcx>])
515                        -> Block<'a, 'tcx> {
516         let out = self.new_id_block("join", id);
517         let mut reachable = false;
518         for bcx in in_cxs.iter() {
519             if !bcx.unreachable.get() {
520                 build::Br(*bcx, out.llbb, DebugLoc::None);
521                 reachable = true;
522             }
523         }
524         if !reachable {
525             build::Unreachable(out);
526         }
527         return out;
528     }
529
530     pub fn monomorphize<T>(&self, value: &T) -> T
531         where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
532     {
533         monomorphize::apply_param_substs(self.ccx.tcx(),
534                                          self.param_substs,
535                                          value)
536     }
537 }
538
539 // Basic block context.  We create a block context for each basic block
540 // (single-entry, single-exit sequence of instructions) we generate from Rust
541 // code.  Each basic block we generate is attached to a function, typically
542 // with many basic blocks per function.  All the basic blocks attached to a
543 // function are organized as a directed graph.
544 pub struct BlockS<'blk, 'tcx: 'blk> {
545     // The BasicBlockRef returned from a call to
546     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
547     // block to the function pointed to by llfn.  We insert
548     // instructions into that block by way of this block context.
549     // The block pointing to this one in the function's digraph.
550     pub llbb: BasicBlockRef,
551     pub terminated: Cell<bool>,
552     pub unreachable: Cell<bool>,
553
554     // Is this block part of a landing pad?
555     pub is_lpad: bool,
556
557     // AST node-id associated with this block, if any. Used for
558     // debugging purposes only.
559     pub opt_node_id: Option<ast::NodeId>,
560
561     // The function context for the function to which this block is
562     // attached.
563     pub fcx: &'blk FunctionContext<'blk, 'tcx>,
564 }
565
566 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
567
568 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
569     pub fn new(llbb: BasicBlockRef,
570                is_lpad: bool,
571                opt_node_id: Option<ast::NodeId>,
572                fcx: &'blk FunctionContext<'blk, 'tcx>)
573                -> Block<'blk, 'tcx> {
574         fcx.block_arena.alloc(BlockS {
575             llbb: llbb,
576             terminated: Cell::new(false),
577             unreachable: Cell::new(false),
578             is_lpad: is_lpad,
579             opt_node_id: opt_node_id,
580             fcx: fcx
581         })
582     }
583
584     pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
585         self.fcx.ccx
586     }
587     pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
588         self.fcx.ccx.tcx()
589     }
590     pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
591
592     pub fn ident(&self, ident: Ident) -> String {
593         token::get_ident(ident).get().to_string()
594     }
595
596     pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
597         self.tcx().map.node_to_string(id).to_string()
598     }
599
600     pub fn expr_to_string(&self, e: &ast::Expr) -> String {
601         e.repr(self.tcx())
602     }
603
604     pub fn def(&self, nid: ast::NodeId) -> def::Def {
605         match self.tcx().def_map.borrow().get(&nid) {
606             Some(v) => v.clone(),
607             None => {
608                 self.tcx().sess.bug(&format!(
609                     "no def associated with node id {}", nid)[]);
610             }
611         }
612     }
613
614     pub fn val_to_string(&self, val: ValueRef) -> String {
615         self.ccx().tn().val_to_string(val)
616     }
617
618     pub fn llty_str(&self, ty: Type) -> String {
619         self.ccx().tn().type_to_string(ty)
620     }
621
622     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
623         t.repr(self.tcx())
624     }
625
626     pub fn to_str(&self) -> String {
627         format!("[block {:p}]", self)
628     }
629
630     pub fn monomorphize<T>(&self, value: &T) -> T
631         where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
632     {
633         monomorphize::apply_param_substs(self.tcx(),
634                                          self.fcx.param_substs,
635                                          value)
636     }
637 }
638
639 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
640     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
641         self.tcx()
642     }
643
644     fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
645         Ok(node_id_type(self, id))
646     }
647
648     fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
649         Ok(expr_ty_adjusted(self, expr))
650     }
651
652     fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
653         self.tcx()
654             .method_map
655             .borrow()
656             .get(&method_call)
657             .map(|method| monomorphize_type(self, method.ty))
658     }
659
660     fn node_method_origin(&self, method_call: ty::MethodCall)
661                           -> Option<ty::MethodOrigin<'tcx>>
662     {
663         self.tcx()
664             .method_map
665             .borrow()
666             .get(&method_call)
667             .map(|method| method.origin.clone())
668     }
669
670     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
671         &self.tcx().adjustments
672     }
673
674     fn is_method_call(&self, id: ast::NodeId) -> bool {
675         self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id))
676     }
677
678     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
679         self.tcx().region_maps.temporary_scope(rvalue_id)
680     }
681
682     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> {
683         Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone())
684     }
685
686     fn capture_mode(&self, closure_expr_id: ast::NodeId)
687                     -> ast::CaptureClause {
688         self.tcx().capture_modes.borrow()[closure_expr_id].clone()
689     }
690
691     fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
692         self.fcx.param_env.type_moves_by_default(span, ty)
693     }
694 }
695
696 impl<'blk, 'tcx> ty::UnboxedClosureTyper<'tcx> for BlockS<'blk, 'tcx> {
697     fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> {
698         &self.fcx.param_env
699     }
700
701     fn unboxed_closure_kind(&self,
702                             def_id: ast::DefId)
703                             -> ty::UnboxedClosureKind
704     {
705         let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
706         typer.unboxed_closure_kind(def_id)
707     }
708
709     fn unboxed_closure_type(&self,
710                             def_id: ast::DefId,
711                             substs: &subst::Substs<'tcx>)
712                             -> ty::ClosureTy<'tcx>
713     {
714         let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
715         typer.unboxed_closure_type(def_id, substs)
716     }
717
718     fn unboxed_closure_upvars(&self,
719                               def_id: ast::DefId,
720                               substs: &Substs<'tcx>)
721                               -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>>
722     {
723         let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
724         typer.unboxed_closure_upvars(def_id, substs)
725     }
726 }
727
728 pub struct Result<'blk, 'tcx: 'blk> {
729     pub bcx: Block<'blk, 'tcx>,
730     pub val: ValueRef
731 }
732
733 impl<'b, 'tcx> Result<'b, 'tcx> {
734     pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
735         Result {
736             bcx: bcx,
737             val: val,
738         }
739     }
740 }
741
742 pub fn val_ty(v: ValueRef) -> Type {
743     unsafe {
744         Type::from_ref(llvm::LLVMTypeOf(v))
745     }
746 }
747
748 // LLVM constant constructors.
749 pub fn C_null(t: Type) -> ValueRef {
750     unsafe {
751         llvm::LLVMConstNull(t.to_ref())
752     }
753 }
754
755 pub fn C_undef(t: Type) -> ValueRef {
756     unsafe {
757         llvm::LLVMGetUndef(t.to_ref())
758     }
759 }
760
761 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
762     unsafe {
763         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
764     }
765 }
766
767 pub fn C_floating(s: &str, t: Type) -> ValueRef {
768     unsafe {
769         let s = CString::from_slice(s.as_bytes());
770         llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr())
771     }
772 }
773
774 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
775     C_struct(ccx, &[], false)
776 }
777
778 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
779     C_integral(Type::i1(ccx), val as u64, false)
780 }
781
782 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
783     C_integral(Type::i32(ccx), i as u64, true)
784 }
785
786 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
787     C_integral(Type::i64(ccx), i as u64, true)
788 }
789
790 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
791     C_integral(Type::i64(ccx), i, false)
792 }
793
794 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
795     let v = i.as_i64();
796
797     match machine::llbitsize_of_real(ccx, ccx.int_type()) {
798         32 => assert!(v < (1<<31) && v >= -(1<<31)),
799         64 => {},
800         n => panic!("unsupported target size: {}", n)
801     }
802
803     C_integral(ccx.int_type(), v as u64, true)
804 }
805
806 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
807     let v = i.as_u64();
808
809     match machine::llbitsize_of_real(ccx, ccx.int_type()) {
810         32 => assert!(v < (1<<32)),
811         64 => {},
812         n => panic!("unsupported target size: {}", n)
813     }
814
815     C_integral(ccx.int_type(), v, false)
816 }
817
818 pub trait AsI64 { fn as_i64(self) -> i64; }
819 pub trait AsU64 { fn as_u64(self) -> u64; }
820
821 // FIXME: remove the intptr conversions, because they
822 // are host-architecture-dependent
823 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
824 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
825 impl AsI64 for int { fn as_i64(self) -> i64 { self as i64 }}
826
827 impl AsU64 for u64  { fn as_u64(self) -> u64 { self as u64 }}
828 impl AsU64 for u32  { fn as_u64(self) -> u64 { self as u64 }}
829 impl AsU64 for uint { fn as_u64(self) -> u64 { self as u64 }}
830
831 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
832     C_integral(Type::i8(ccx), i as u64, false)
833 }
834
835
836 // This is a 'c-like' raw string, which differs from
837 // our boxed-and-length-annotated strings.
838 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
839     unsafe {
840         match cx.const_cstr_cache().borrow().get(&s) {
841             Some(&llval) => return llval,
842             None => ()
843         }
844
845         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
846                                                 s.get().as_ptr() as *const c_char,
847                                                 s.get().len() as c_uint,
848                                                 !null_terminated as Bool);
849
850         let gsym = token::gensym("str");
851         let buf = CString::from_vec(format!("str{}", gsym.usize()).into_bytes());
852         let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr());
853         llvm::LLVMSetInitializer(g, sc);
854         llvm::LLVMSetGlobalConstant(g, True);
855         llvm::SetLinkage(g, llvm::InternalLinkage);
856
857         cx.const_cstr_cache().borrow_mut().insert(s, g);
858         g
859     }
860 }
861
862 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
863 // you will be kicked off fast isel. See issue #4352 for an example of this.
864 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
865     let len = s.get().len();
866     let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
867     C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
868 }
869
870 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
871     unsafe {
872         let len = data.len();
873         let lldata = C_bytes(cx, data);
874
875         let gsym = token::gensym("binary");
876         let name = format!("binary{}", gsym.usize());
877         let name = CString::from_vec(name.into_bytes());
878         let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(),
879                                     name.as_ptr());
880         llvm::LLVMSetInitializer(g, lldata);
881         llvm::LLVMSetGlobalConstant(g, True);
882         llvm::SetLinkage(g, llvm::InternalLinkage);
883
884         let cs = consts::ptrcast(g, Type::i8p(cx));
885         C_struct(cx, &[cs, C_uint(cx, len)], false)
886     }
887 }
888
889 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
890     C_struct_in_context(cx.llcx(), elts, packed)
891 }
892
893 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
894     unsafe {
895         llvm::LLVMConstStructInContext(llcx,
896                                        elts.as_ptr(), elts.len() as c_uint,
897                                        packed as Bool)
898     }
899 }
900
901 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
902     unsafe {
903         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
904     }
905 }
906
907 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
908     unsafe {
909         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
910     }
911 }
912
913 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
914     C_bytes_in_context(cx.llcx(), bytes)
915 }
916
917 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
918     unsafe {
919         let ptr = bytes.as_ptr() as *const c_char;
920         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
921     }
922 }
923
924 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
925               -> ValueRef {
926     unsafe {
927         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
928
929         debug!("const_get_elt(v={}, us={:?}, r={})",
930                cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
931
932         return r;
933     }
934 }
935
936 pub fn is_const(v: ValueRef) -> bool {
937     unsafe {
938         llvm::LLVMIsConstant(v) == True
939     }
940 }
941
942 pub fn const_to_int(v: ValueRef) -> i64 {
943     unsafe {
944         llvm::LLVMConstIntGetSExtValue(v)
945     }
946 }
947
948 pub fn const_to_uint(v: ValueRef) -> u64 {
949     unsafe {
950         llvm::LLVMConstIntGetZExtValue(v)
951     }
952 }
953
954 pub fn is_undef(val: ValueRef) -> bool {
955     unsafe {
956         llvm::LLVMIsUndef(val) != False
957     }
958 }
959
960 #[allow(dead_code)] // potentially useful
961 pub fn is_null(val: ValueRef) -> bool {
962     unsafe {
963         llvm::LLVMIsNull(val) != False
964     }
965 }
966
967 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
968     bcx.fcx.monomorphize(&t)
969 }
970
971 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
972     let tcx = bcx.tcx();
973     let t = ty::node_id_to_type(tcx, id);
974     monomorphize_type(bcx, t)
975 }
976
977 pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
978     node_id_type(bcx, ex.id)
979 }
980
981 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
982     monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
983 }
984
985 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
986 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
987 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
988 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
989                                 span: Span,
990                                 trait_ref: ty::PolyTraitRef<'tcx>)
991                                 -> traits::Vtable<'tcx, ()>
992 {
993     let tcx = ccx.tcx();
994
995     // Remove any references to regions; this helps improve caching.
996     let trait_ref = erase_regions(tcx, &trait_ref);
997
998     // First check the cache.
999     match ccx.trait_cache().borrow().get(&trait_ref) {
1000         Some(vtable) => {
1001             info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
1002             return (*vtable).clone();
1003         }
1004         None => { }
1005     }
1006
1007     debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx()));
1008
1009     ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id());
1010     let infcx = infer::new_infer_ctxt(tcx);
1011
1012     // Do the initial selection for the obligation. This yields the
1013     // shallow result we are looking for -- that is, what specific impl.
1014     let typer = NormalizingUnboxedClosureTyper::new(tcx);
1015     let mut selcx = traits::SelectionContext::new(&infcx, &typer);
1016     let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
1017                                              trait_ref.to_poly_trait_predicate());
1018     let selection = match selcx.select(&obligation) {
1019         Ok(Some(selection)) => selection,
1020         Ok(None) => {
1021             // Ambiguity can happen when monomorphizing during trans
1022             // expands to some humongo type that never occurred
1023             // statically -- this humongo type can then overflow,
1024             // leading to an ambiguous result. So report this as an
1025             // overflow bug, since I believe this is the only case
1026             // where ambiguity can result.
1027             debug!("Encountered ambiguity selecting `{}` during trans, \
1028                     presuming due to overflow",
1029                    trait_ref.repr(tcx));
1030             ccx.sess().span_fatal(
1031                 span,
1032                 "reached the recursion limit during monomorphization");
1033         }
1034         Err(e) => {
1035             tcx.sess.span_bug(
1036                 span,
1037                 &format!("Encountered error `{}` selecting `{}` during trans",
1038                         e.repr(tcx),
1039                         trait_ref.repr(tcx))[])
1040         }
1041     };
1042
1043     // Currently, we use a fulfillment context to completely resolve
1044     // all nested obligations. This is because they can inform the
1045     // inference of the impl's type parameters.
1046     let mut fulfill_cx = traits::FulfillmentContext::new();
1047     let vtable = selection.map_move_nested(|predicate| {
1048         fulfill_cx.register_predicate_obligation(&infcx, predicate);
1049     });
1050     let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable);
1051
1052     info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
1053     ccx.trait_cache().borrow_mut().insert(trait_ref,
1054                                           vtable.clone());
1055
1056     vtable
1057 }
1058
1059 pub struct NormalizingUnboxedClosureTyper<'a,'tcx:'a> {
1060     param_env: ty::ParameterEnvironment<'a, 'tcx>
1061 }
1062
1063 impl<'a,'tcx> NormalizingUnboxedClosureTyper<'a,'tcx> {
1064     pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> {
1065         // Parameter environment is used to give details about type parameters,
1066         // but since we are in trans, everything is fully monomorphized.
1067         NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) }
1068     }
1069 }
1070
1071 impl<'a,'tcx> ty::UnboxedClosureTyper<'tcx> for NormalizingUnboxedClosureTyper<'a,'tcx> {
1072     fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1073         &self.param_env
1074     }
1075
1076     fn unboxed_closure_kind(&self,
1077                             def_id: ast::DefId)
1078                             -> ty::UnboxedClosureKind
1079     {
1080         self.param_env.tcx.unboxed_closure_kind(def_id)
1081     }
1082
1083     fn unboxed_closure_type(&self,
1084                             def_id: ast::DefId,
1085                             substs: &subst::Substs<'tcx>)
1086                             -> ty::ClosureTy<'tcx>
1087     {
1088         // the substitutions in `substs` are already monomorphized,
1089         // but we still must normalize associated types
1090         let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs);
1091         monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty)
1092     }
1093
1094     fn unboxed_closure_upvars(&self,
1095                               def_id: ast::DefId,
1096                               substs: &Substs<'tcx>)
1097                               -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>>
1098     {
1099         // the substitutions in `substs` are already monomorphized,
1100         // but we still must normalize associated types
1101         let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs);
1102         monomorphize::normalize_associated_type(self.param_env.tcx, &result)
1103     }
1104 }
1105
1106 pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span,
1107                                    infcx: &infer::InferCtxt<'a,'tcx>,
1108                                    fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
1109                                    result: &T)
1110                                    -> T
1111     where T : TypeFoldable<'tcx> + Repr<'tcx>
1112 {
1113     debug!("drain_fulfillment_cx(result={})",
1114            result.repr(infcx.tcx));
1115
1116     // In principle, we only need to do this so long as `result`
1117     // contains unbound type parameters. It could be a slight
1118     // optimization to stop iterating early.
1119     let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx);
1120     match fulfill_cx.select_all_or_error(infcx, &typer) {
1121         Ok(()) => { }
1122         Err(errors) => {
1123             if errors.iter().all(|e| e.is_overflow()) {
1124                 // See Ok(None) case above.
1125                 infcx.tcx.sess.span_fatal(
1126                     span,
1127                     "reached the recursion limit during monomorphization");
1128             } else {
1129                 infcx.tcx.sess.span_bug(
1130                     span,
1131                     &format!("Encountered errors `{}` fulfilling during trans",
1132                             errors.repr(infcx.tcx))[]);
1133             }
1134         }
1135     }
1136
1137     // Use freshen to simultaneously replace all type variables with
1138     // their bindings and replace all regions with 'static.  This is
1139     // sort of overkill because we do not expect there to be any
1140     // unbound type variables, hence no `TyFresh` types should ever be
1141     // inserted.
1142     result.fold_with(&mut infcx.freshener())
1143 }
1144
1145 // Key used to lookup values supplied for type parameters in an expr.
1146 #[derive(Copy, PartialEq, Show)]
1147 pub enum ExprOrMethodCall {
1148     // Type parameters for a path like `None::<int>`
1149     ExprId(ast::NodeId),
1150
1151     // Type parameters for a method call like `a.foo::<int>()`
1152     MethodCallKey(ty::MethodCall)
1153 }
1154
1155 pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1156                             node: ExprOrMethodCall,
1157                             param_substs: &subst::Substs<'tcx>)
1158                             -> subst::Substs<'tcx> {
1159     let tcx = ccx.tcx();
1160
1161     let substs = match node {
1162         ExprId(id) => {
1163             ty::node_id_item_substs(tcx, id).substs
1164         }
1165         MethodCallKey(method_call) => {
1166             (*tcx.method_map.borrow())[method_call].substs.clone()
1167         }
1168     };
1169
1170     if substs.types.any(|t| ty::type_needs_infer(*t)) {
1171             tcx.sess.bug(&format!("type parameters for node {:?} include inference types: {:?}",
1172                                  node, substs.repr(tcx))[]);
1173         }
1174
1175         monomorphize::apply_param_substs(tcx,
1176                                          param_substs,
1177                                          &substs.erase_regions())
1178 }
1179
1180 pub fn langcall(bcx: Block,
1181                 span: Option<Span>,
1182                 msg: &str,
1183                 li: LangItem)
1184                 -> ast::DefId {
1185     match bcx.tcx().lang_items.require(li) {
1186         Ok(id) => id,
1187         Err(s) => {
1188             let msg = format!("{} {}", msg, s);
1189             match span {
1190                 Some(span) => bcx.tcx().sess.span_fatal(span, &msg[]),
1191                 None => bcx.tcx().sess.fatal(&msg[]),
1192             }
1193         }
1194     }
1195 }