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