]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
librustc: Stop generating visit glue and remove from TyDesc.
[rust.git] / src / librustc / middle / 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 use driver::session::Session;
16 use llvm;
17 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef};
18 use llvm::{True, False, Bool};
19 use middle::def;
20 use middle::lang_items::LangItem;
21 use middle::mem_categorization as mc;
22 use middle::subst;
23 use middle::subst::Subst;
24 use middle::trans::base;
25 use middle::trans::build;
26 use middle::trans::cleanup;
27 use middle::trans::datum;
28 use middle::trans::debuginfo;
29 use middle::trans::type_::Type;
30 use middle::trans::type_of;
31 use middle::traits;
32 use middle::ty;
33 use middle::ty_fold;
34 use middle::ty_fold::TypeFoldable;
35 use middle::typeck;
36 use middle::typeck::infer;
37 use util::ppaux::Repr;
38 use util::nodemap::{DefIdMap, NodeMap};
39
40 use arena::TypedArena;
41 use std::collections::HashMap;
42 use libc::{c_uint, c_longlong, c_ulonglong, c_char};
43 use std::c_str::ToCStr;
44 use std::cell::{Cell, RefCell};
45 use std::rc::Rc;
46 use std::vec::Vec;
47 use syntax::ast::Ident;
48 use syntax::ast;
49 use syntax::ast_map::{PathElem, PathName};
50 use syntax::codemap::Span;
51 use syntax::parse::token::InternedString;
52 use syntax::parse::token;
53
54 pub use middle::trans::context::CrateContext;
55
56 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
57     match ty::get(ty).sty {
58         ty::ty_struct(def_id, ref substs) => {
59             let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
60             fields.len() == 1 &&
61                 fields.get(0).ident.name ==
62                     token::special_idents::unnamed_field.name &&
63                 type_is_immediate(ccx, fields.get(0).mt.ty)
64         }
65         _ => false
66     }
67 }
68
69 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
70     use middle::trans::machine::llsize_of_alloc;
71     use middle::trans::type_of::sizing_type_of;
72
73     let tcx = ccx.tcx();
74     let simple = ty::type_is_scalar(ty) ||
75         ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
76         type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
77         ty::type_is_simd(tcx, ty);
78     if simple && !ty::type_is_fat_ptr(tcx, ty) {
79         return true;
80     }
81     if !ty::type_is_sized(tcx, ty) {
82         return false;
83     }
84     match ty::get(ty).sty {
85         ty::ty_bot => true,
86         ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) |
87         ty::ty_unboxed_closure(..) => {
88             let llty = sizing_type_of(ccx, ty);
89             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
90         }
91         _ => type_is_zero_size(ccx, ty)
92     }
93 }
94
95 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
96     /*!
97      * Identify types which have size zero at runtime.
98      */
99
100     use middle::trans::machine::llsize_of_alloc;
101     use middle::trans::type_of::sizing_type_of;
102     let llty = sizing_type_of(ccx, ty);
103     llsize_of_alloc(ccx, llty) == 0
104 }
105
106 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
107     /*!
108      * Identifies types which we declare to be equivalent to `void`
109      * in C for the purpose of function return types. These are
110      * `()`, bot, and uninhabited enums. Note that all such types
111      * are also zero-size, but not all zero-size types use a `void`
112      * return type (in order to aid with C ABI compatibility).
113      */
114
115     ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx(), ty)
116 }
117
118 /// Generates a unique symbol based off the name given. This is used to create
119 /// unique symbols for things like closures.
120 pub fn gensym_name(name: &str) -> PathElem {
121     let num = token::gensym(name).uint();
122     // use one colon which will get translated to a period by the mangler, and
123     // we're guaranteed that `num` is globally unique for this crate.
124     PathName(token::gensym(format!("{}:{}", name, num).as_slice()))
125 }
126
127 pub struct tydesc_info {
128     pub ty: ty::t,
129     pub tydesc: ValueRef,
130     pub size: ValueRef,
131     pub align: ValueRef,
132     pub name: ValueRef,
133 }
134
135 /*
136  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
137  *
138  * An "extern" is an LLVM symbol we wind up emitting an undefined external
139  * reference to. This means "we don't have the thing in this compilation unit,
140  * please make sure you link it in at runtime". This could be a reference to
141  * C code found in a C library, or rust code found in a rust crate.
142  *
143  * Most "externs" are implicitly declared (automatically) as a result of a
144  * user declaring an extern _module_ dependency; this causes the rust driver
145  * to locate an extern crate, scan its compilation metadata, and emit extern
146  * declarations for any symbols used by the declaring crate.
147  *
148  * A "foreign" is an extern that references C (or other non-rust ABI) code.
149  * There is no metadata to scan for extern references so in these cases either
150  * a header-digester like bindgen, or manual function prototypes, have to
151  * serve as declarators. So these are usually given explicitly as prototype
152  * declarations, in rust code, with ABI attributes on them noting which ABI to
153  * link via.
154  *
155  * An "upcall" is a foreign call generated by the compiler (not corresponding
156  * to any user-written call in the code) into the runtime library, to perform
157  * some helper task such as bringing a task to life, allocating memory, etc.
158  *
159  */
160
161 pub struct NodeInfo {
162     pub id: ast::NodeId,
163     pub span: Span,
164 }
165
166 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
167     NodeInfo { id: expr.id, span: expr.span }
168 }
169
170 pub struct BuilderRef_res {
171     pub b: BuilderRef,
172 }
173
174 impl Drop for BuilderRef_res {
175     fn drop(&mut self) {
176         unsafe {
177             llvm::LLVMDisposeBuilder(self.b);
178         }
179     }
180 }
181
182 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
183     BuilderRef_res {
184         b: b
185     }
186 }
187
188 pub type ExternMap = HashMap<String, ValueRef>;
189
190 // Here `self_ty` is the real type of the self parameter to this method. It
191 // will only be set in the case of default methods.
192 pub struct param_substs {
193     pub substs: subst::Substs,
194 }
195
196 impl param_substs {
197     pub fn empty() -> param_substs {
198         param_substs {
199             substs: subst::Substs::trans_empty(),
200         }
201     }
202
203     pub fn validate(&self) {
204         assert!(self.substs.types.all(|t| !ty::type_needs_infer(*t)));
205     }
206 }
207
208 impl Repr for param_substs {
209     fn repr(&self, tcx: &ty::ctxt) -> String {
210         self.substs.repr(tcx)
211     }
212 }
213
214 pub trait SubstP {
215     fn substp(&self, tcx: &ty::ctxt, param_substs: &param_substs)
216               -> Self;
217 }
218
219 impl<T:Subst+Clone> SubstP for T {
220     fn substp(&self, tcx: &ty::ctxt, substs: &param_substs) -> T {
221         self.subst(tcx, &substs.substs)
222     }
223 }
224
225 // work around bizarre resolve errors
226 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
227 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
228
229 // Function context.  Every LLVM function we create will have one of
230 // these.
231 pub struct FunctionContext<'a, 'tcx: 'a> {
232     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
233     // address of the first instruction in the sequence of
234     // instructions for this function that will go in the .text
235     // section of the executable we're generating.
236     pub llfn: ValueRef,
237
238     // The environment argument in a closure.
239     pub llenv: Option<ValueRef>,
240
241     // A pointer to where to store the return value. If the return type is
242     // immediate, this points to an alloca in the function. Otherwise, it's a
243     // pointer to the hidden first parameter of the function. After function
244     // construction, this should always be Some.
245     pub llretslotptr: Cell<Option<ValueRef>>,
246
247     // These pub elements: "hoisted basic blocks" containing
248     // administrative activities that have to happen in only one place in
249     // the function, due to LLVM's quirks.
250     // A marker for the place where we want to insert the function's static
251     // allocas, so that LLVM will coalesce them into a single alloca call.
252     pub alloca_insert_pt: Cell<Option<ValueRef>>,
253     pub llreturn: Cell<Option<BasicBlockRef>>,
254
255     // If the function has any nested return's, including something like:
256     // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
257     // we use a separate alloca for each return
258     pub needs_ret_allocas: bool,
259
260     // The a value alloca'd for calls to upcalls.rust_personality. Used when
261     // outputting the resume instruction.
262     pub personality: Cell<Option<ValueRef>>,
263
264     // True if the caller expects this fn to use the out pointer to
265     // return. Either way, your code should write into the slot llretslotptr
266     // points to, but if this value is false, that slot will be a local alloca.
267     pub caller_expects_out_pointer: bool,
268
269     // Maps the DefId's for local variables to the allocas created for
270     // them in llallocas.
271     pub lllocals: RefCell<NodeMap<LvalueDatum>>,
272
273     // Same as above, but for closure upvars
274     pub llupvars: RefCell<NodeMap<ValueRef>>,
275
276     // The NodeId of the function, or -1 if it doesn't correspond to
277     // a user-defined function.
278     pub id: ast::NodeId,
279
280     // If this function is being monomorphized, this contains the type
281     // substitutions used.
282     pub param_substs: &'a param_substs,
283
284     // The source span and nesting context where this function comes from, for
285     // error reporting and symbol generation.
286     pub span: Option<Span>,
287
288     // The arena that blocks are allocated from.
289     pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
290
291     // This function's enclosing crate context.
292     pub ccx: &'a CrateContext<'a, 'tcx>,
293
294     // Used and maintained by the debuginfo module.
295     pub debug_context: debuginfo::FunctionDebugContext,
296
297     // Cleanup scopes.
298     pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
299 }
300
301 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
302     pub fn arg_pos(&self, arg: uint) -> uint {
303         let arg = self.env_arg_pos() + arg;
304         if self.llenv.is_some() {
305             arg + 1
306         } else {
307             arg
308         }
309     }
310
311     pub fn out_arg_pos(&self) -> uint {
312         assert!(self.caller_expects_out_pointer);
313         0u
314     }
315
316     pub fn env_arg_pos(&self) -> uint {
317         if self.caller_expects_out_pointer {
318             1u
319         } else {
320             0u
321         }
322     }
323
324     pub fn cleanup(&self) {
325         unsafe {
326             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
327                                                      .get()
328                                                      .unwrap());
329         }
330     }
331
332     pub fn get_llreturn(&self) -> BasicBlockRef {
333         if self.llreturn.get().is_none() {
334
335             self.llreturn.set(Some(unsafe {
336                 "return".with_c_str(|buf| {
337                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, buf)
338                 })
339             }))
340         }
341
342         self.llreturn.get().unwrap()
343     }
344
345     pub fn get_ret_slot(&self, bcx: Block, ty: ty::t, name: &str) -> ValueRef {
346         if self.needs_ret_allocas {
347             base::alloca_no_lifetime(bcx, type_of::type_of(bcx.ccx(), ty), name)
348         } else {
349             self.llretslotptr.get().unwrap()
350         }
351     }
352
353     pub fn new_block(&'a self,
354                      is_lpad: bool,
355                      name: &str,
356                      opt_node_id: Option<ast::NodeId>)
357                      -> Block<'a, 'tcx> {
358         unsafe {
359             let llbb = name.with_c_str(|buf| {
360                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
361                                                         self.llfn,
362                                                         buf)
363                 });
364             BlockS::new(llbb, is_lpad, opt_node_id, self)
365         }
366     }
367
368     pub fn new_id_block(&'a self,
369                         name: &str,
370                         node_id: ast::NodeId)
371                         -> Block<'a, 'tcx> {
372         self.new_block(false, name, Some(node_id))
373     }
374
375     pub fn new_temp_block(&'a self,
376                           name: &str)
377                           -> Block<'a, 'tcx> {
378         self.new_block(false, name, None)
379     }
380
381     pub fn join_blocks(&'a self,
382                        id: ast::NodeId,
383                        in_cxs: &[Block<'a, 'tcx>])
384                        -> Block<'a, 'tcx> {
385         let out = self.new_id_block("join", id);
386         let mut reachable = false;
387         for bcx in in_cxs.iter() {
388             if !bcx.unreachable.get() {
389                 build::Br(*bcx, out.llbb);
390                 reachable = true;
391             }
392         }
393         if !reachable {
394             build::Unreachable(out);
395         }
396         return out;
397     }
398 }
399
400 // Basic block context.  We create a block context for each basic block
401 // (single-entry, single-exit sequence of instructions) we generate from Rust
402 // code.  Each basic block we generate is attached to a function, typically
403 // with many basic blocks per function.  All the basic blocks attached to a
404 // function are organized as a directed graph.
405 pub struct BlockS<'blk, 'tcx: 'blk> {
406     // The BasicBlockRef returned from a call to
407     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
408     // block to the function pointed to by llfn.  We insert
409     // instructions into that block by way of this block context.
410     // The block pointing to this one in the function's digraph.
411     pub llbb: BasicBlockRef,
412     pub terminated: Cell<bool>,
413     pub unreachable: Cell<bool>,
414
415     // Is this block part of a landing pad?
416     pub is_lpad: bool,
417
418     // AST node-id associated with this block, if any. Used for
419     // debugging purposes only.
420     pub opt_node_id: Option<ast::NodeId>,
421
422     // The function context for the function to which this block is
423     // attached.
424     pub fcx: &'blk FunctionContext<'blk, 'tcx>,
425 }
426
427 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
428
429 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
430     pub fn new(llbb: BasicBlockRef,
431                is_lpad: bool,
432                opt_node_id: Option<ast::NodeId>,
433                fcx: &'blk FunctionContext<'blk, 'tcx>)
434                -> Block<'blk, 'tcx> {
435         fcx.block_arena.alloc(BlockS {
436             llbb: llbb,
437             terminated: Cell::new(false),
438             unreachable: Cell::new(false),
439             is_lpad: is_lpad,
440             opt_node_id: opt_node_id,
441             fcx: fcx
442         })
443     }
444
445     pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
446         self.fcx.ccx
447     }
448     pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
449         self.fcx.ccx.tcx()
450     }
451     pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
452
453     pub fn ident(&self, ident: Ident) -> String {
454         token::get_ident(ident).get().to_string()
455     }
456
457     pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
458         self.tcx().map.node_to_string(id).to_string()
459     }
460
461     pub fn expr_to_string(&self, e: &ast::Expr) -> String {
462         e.repr(self.tcx())
463     }
464
465     pub fn def(&self, nid: ast::NodeId) -> def::Def {
466         match self.tcx().def_map.borrow().find(&nid) {
467             Some(v) => v.clone(),
468             None => {
469                 self.tcx().sess.bug(format!(
470                     "no def associated with node id {}", nid).as_slice());
471             }
472         }
473     }
474
475     pub fn val_to_string(&self, val: ValueRef) -> String {
476         self.ccx().tn().val_to_string(val)
477     }
478
479     pub fn llty_str(&self, ty: Type) -> String {
480         self.ccx().tn().type_to_string(ty)
481     }
482
483     pub fn ty_to_string(&self, t: ty::t) -> String {
484         t.repr(self.tcx())
485     }
486
487     pub fn to_str(&self) -> String {
488         format!("[block {:p}]", self)
489     }
490 }
491
492 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
493     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
494         self.tcx()
495     }
496
497     fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
498         Ok(node_id_type(self, id))
499     }
500
501     fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
502         self.tcx().method_map.borrow().find(&method_call).map(|method| method.ty)
503     }
504
505     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
506         &self.tcx().adjustments
507     }
508
509     fn is_method_call(&self, id: ast::NodeId) -> bool {
510         self.tcx().method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
511     }
512
513     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
514         self.tcx().region_maps.temporary_scope(rvalue_id)
515     }
516
517     fn unboxed_closures<'a>(&'a self)
518                         -> &'a RefCell<DefIdMap<ty::UnboxedClosure>> {
519         &self.tcx().unboxed_closures
520     }
521
522     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
523         self.tcx().upvar_borrow_map.borrow().get_copy(&upvar_id)
524     }
525
526     fn capture_mode(&self, closure_expr_id: ast::NodeId)
527                     -> ast::CaptureClause {
528         self.tcx().capture_modes.borrow().get_copy(&closure_expr_id)
529     }
530 }
531
532 pub struct Result<'blk, 'tcx: 'blk> {
533     pub bcx: Block<'blk, 'tcx>,
534     pub val: ValueRef
535 }
536
537 impl<'b, 'tcx> Result<'b, 'tcx> {
538     pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
539         Result {
540             bcx: bcx,
541             val: val,
542         }
543     }
544 }
545
546 pub fn val_ty(v: ValueRef) -> Type {
547     unsafe {
548         Type::from_ref(llvm::LLVMTypeOf(v))
549     }
550 }
551
552 // LLVM constant constructors.
553 pub fn C_null(t: Type) -> ValueRef {
554     unsafe {
555         llvm::LLVMConstNull(t.to_ref())
556     }
557 }
558
559 pub fn C_undef(t: Type) -> ValueRef {
560     unsafe {
561         llvm::LLVMGetUndef(t.to_ref())
562     }
563 }
564
565 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
566     unsafe {
567         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
568     }
569 }
570
571 pub fn C_floating(s: &str, t: Type) -> ValueRef {
572     unsafe {
573         s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
574     }
575 }
576
577 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
578     C_struct(ccx, [], false)
579 }
580
581 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
582     C_integral(Type::i1(ccx), val as u64, false)
583 }
584
585 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
586     C_integral(Type::i32(ccx), i as u64, true)
587 }
588
589 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
590     C_integral(Type::i64(ccx), i as u64, true)
591 }
592
593 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
594     C_integral(Type::i64(ccx), i, false)
595 }
596
597 pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
598     C_integral(ccx.int_type(), i as u64, true)
599 }
600
601 pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
602     C_integral(ccx.int_type(), i as u64, false)
603 }
604
605 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
606     C_integral(Type::i8(ccx), i as u64, false)
607 }
608
609
610 // This is a 'c-like' raw string, which differs from
611 // our boxed-and-length-annotated strings.
612 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
613     unsafe {
614         match cx.const_cstr_cache().borrow().find(&s) {
615             Some(&llval) => return llval,
616             None => ()
617         }
618
619         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
620                                                 s.get().as_ptr() as *const c_char,
621                                                 s.get().len() as c_uint,
622                                                 !null_terminated as Bool);
623
624         let gsym = token::gensym("str");
625         let g = format!("str{}", gsym.uint()).with_c_str(|buf| {
626             llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf)
627         });
628         llvm::LLVMSetInitializer(g, sc);
629         llvm::LLVMSetGlobalConstant(g, True);
630         llvm::SetLinkage(g, llvm::InternalLinkage);
631
632         cx.const_cstr_cache().borrow_mut().insert(s, g);
633         g
634     }
635 }
636
637 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
638 // you will be kicked off fast isel. See issue #4352 for an example of this.
639 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
640     unsafe {
641         let len = s.get().len();
642         let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false),
643                                             Type::i8p(cx).to_ref());
644         C_named_struct(cx.tn().find_type("str_slice").unwrap(), [cs, C_uint(cx, len)])
645     }
646 }
647
648 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
649     unsafe {
650         let len = data.len();
651         let lldata = C_bytes(cx, data);
652
653         let gsym = token::gensym("binary");
654         let g = format!("binary{}", gsym.uint()).with_c_str(|buf| {
655             llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), buf)
656         });
657         llvm::LLVMSetInitializer(g, lldata);
658         llvm::LLVMSetGlobalConstant(g, True);
659         llvm::SetLinkage(g, llvm::InternalLinkage);
660
661         let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
662         C_struct(cx, [cs, C_uint(cx, len)], false)
663     }
664 }
665
666 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
667     C_struct_in_context(cx.llcx(), elts, packed)
668 }
669
670 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
671     unsafe {
672         llvm::LLVMConstStructInContext(llcx,
673                                        elts.as_ptr(), elts.len() as c_uint,
674                                        packed as Bool)
675     }
676 }
677
678 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
679     unsafe {
680         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
681     }
682 }
683
684 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
685     unsafe {
686         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
687     }
688 }
689
690 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
691     C_bytes_in_context(cx.llcx(), bytes)
692 }
693
694 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
695     unsafe {
696         let ptr = bytes.as_ptr() as *const c_char;
697         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
698     }
699 }
700
701 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
702                   -> ValueRef {
703     unsafe {
704         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
705
706         debug!("const_get_elt(v={}, us={}, r={})",
707                cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
708
709         return r;
710     }
711 }
712
713 pub fn is_const(v: ValueRef) -> bool {
714     unsafe {
715         llvm::LLVMIsConstant(v) == True
716     }
717 }
718
719 pub fn const_to_int(v: ValueRef) -> c_longlong {
720     unsafe {
721         llvm::LLVMConstIntGetSExtValue(v)
722     }
723 }
724
725 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
726     unsafe {
727         llvm::LLVMConstIntGetZExtValue(v)
728     }
729 }
730
731 pub fn is_undef(val: ValueRef) -> bool {
732     unsafe {
733         llvm::LLVMIsUndef(val) != False
734     }
735 }
736
737 pub fn is_null(val: ValueRef) -> bool {
738     unsafe {
739         llvm::LLVMIsNull(val) != False
740     }
741 }
742
743 pub fn monomorphize_type(bcx: &BlockS, t: ty::t) -> ty::t {
744     t.subst(bcx.tcx(), &bcx.fcx.param_substs.substs)
745 }
746
747 pub fn node_id_type(bcx: &BlockS, id: ast::NodeId) -> ty::t {
748     let tcx = bcx.tcx();
749     let t = ty::node_id_to_type(tcx, id);
750     monomorphize_type(bcx, t)
751 }
752
753 pub fn expr_ty(bcx: Block, ex: &ast::Expr) -> ty::t {
754     node_id_type(bcx, ex.id)
755 }
756
757 pub fn expr_ty_adjusted(bcx: Block, ex: &ast::Expr) -> ty::t {
758     monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
759 }
760
761 pub fn fulfill_obligation(ccx: &CrateContext,
762                           span: Span,
763                           trait_ref: Rc<ty::TraitRef>)
764                           -> traits::Vtable<()>
765 {
766     /*!
767      * Attempts to resolve an obligation. The result is a shallow
768      * vtable resolution -- meaning that we do not (necessarily) resolve
769      * all nested obligations on the impl. Note that type check should
770      * guarantee to us that all nested obligations *could be* resolved
771      * if we wanted to.
772      */
773
774     let tcx = ccx.tcx();
775
776     // Remove any references to regions; this helps improve caching.
777     let trait_ref = ty_fold::erase_regions(tcx, trait_ref);
778
779     // First check the cache.
780     match ccx.trait_cache().borrow().find(&trait_ref) {
781         Some(vtable) => {
782             info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
783             return (*vtable).clone();
784         }
785         None => { }
786     }
787
788     ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id);
789     let infcx = infer::new_infer_ctxt(tcx);
790
791     // Parameter environment is used to give details about type parameters,
792     // but since we are in trans, everything is fully monomorphized.
793     let param_env = ty::empty_parameter_environment();
794
795     // Do the initial selection for the obligation. This yields the
796     // shallow result we are looking for -- that is, what specific impl.
797     let mut selcx = traits::SelectionContext::new(&infcx, &param_env, tcx);
798     let obligation = traits::Obligation::misc(span, trait_ref.clone());
799     let selection = match selcx.select(&obligation) {
800         Ok(Some(selection)) => selection,
801         Ok(None) => {
802             // Ambiguity can happen when monomorphizing during trans
803             // expands to some humongo type that never occurred
804             // statically -- this humongo type can then overflow,
805             // leading to an ambiguous result. So report this as an
806             // overflow bug, since I believe this is the only case
807             // where ambiguity can result.
808             debug!("Encountered ambiguity selecting `{}` during trans, \
809                     presuming due to overflow",
810                    trait_ref.repr(tcx));
811             ccx.sess().span_fatal(
812                 span,
813                 "reached the recursion limit during monomorphization");
814         }
815         Err(e) => {
816             tcx.sess.span_bug(
817                 span,
818                 format!("Encountered error `{}` selecting `{}` during trans",
819                         e.repr(tcx),
820                         trait_ref.repr(tcx)).as_slice())
821         }
822     };
823
824     // Currently, we use a fulfillment context to completely resolve
825     // all nested obligations. This is because they can inform the
826     // inference of the impl's type parameters. However, in principle,
827     // we only need to do this until the impl's type parameters are
828     // fully bound. It could be a slight optimization to stop
829     // iterating early.
830     let mut fulfill_cx = traits::FulfillmentContext::new();
831     let vtable = selection.map_move_nested(|obligation| {
832         fulfill_cx.register_obligation(tcx, obligation);
833     });
834     match fulfill_cx.select_all_or_error(&infcx, &param_env, tcx) {
835         Ok(()) => { }
836         Err(errors) => {
837             if errors.iter().all(|e| e.is_overflow()) {
838                 // See Ok(None) case above.
839                 ccx.sess().span_fatal(
840                     span,
841                     "reached the recursion limit during monomorphization");
842             } else {
843                 tcx.sess.span_bug(
844                     span,
845                     format!("Encountered errors `{}` fulfilling `{}` during trans",
846                             errors.repr(tcx),
847                             trait_ref.repr(tcx)).as_slice());
848             }
849         }
850     }
851
852     // Use skolemize to simultaneously replace all type variables with
853     // their bindings and replace all regions with 'static.  This is
854     // sort of overkill because we do not expect there to be any
855     // unbound type variables, hence no skolemized types should ever
856     // be inserted.
857     let vtable = vtable.fold_with(&mut infcx.skolemizer());
858
859     info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
860     ccx.trait_cache().borrow_mut().insert(trait_ref,
861                                           vtable.clone());
862
863     vtable
864 }
865
866 // Key used to lookup values supplied for type parameters in an expr.
867 #[deriving(PartialEq, Show)]
868 pub enum ExprOrMethodCall {
869     // Type parameters for a path like `None::<int>`
870     ExprId(ast::NodeId),
871
872     // Type parameters for a method call like `a.foo::<int>()`
873     MethodCall(typeck::MethodCall)
874 }
875
876 pub fn node_id_substs(bcx: Block,
877                       node: ExprOrMethodCall)
878                       -> subst::Substs
879 {
880     let tcx = bcx.tcx();
881
882     let substs = match node {
883         ExprId(id) => {
884             ty::node_id_item_substs(tcx, id).substs
885         }
886         MethodCall(method_call) => {
887             tcx.method_map.borrow().get(&method_call).substs.clone()
888         }
889     };
890
891     if substs.types.any(|t| ty::type_needs_infer(*t)) {
892         bcx.sess().bug(
893             format!("type parameters for node {} include inference types: \
894                      {}",
895                     node,
896                     substs.repr(bcx.tcx())).as_slice());
897     }
898
899     let substs = substs.erase_regions();
900     substs.substp(tcx, bcx.fcx.param_substs)
901 }
902
903 pub fn langcall(bcx: Block,
904                 span: Option<Span>,
905                 msg: &str,
906                 li: LangItem)
907                 -> ast::DefId {
908     match bcx.tcx().lang_items.require(li) {
909         Ok(id) => id,
910         Err(s) => {
911             let msg = format!("{} {}", msg, s);
912             match span {
913                 Some(span) => bcx.tcx().sess.span_fatal(span, msg.as_slice()),
914                 None => bcx.tcx().sess.fatal(msg.as_slice()),
915             }
916         }
917     }
918 }