]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/common.rs
Remove alternate stack with sigaltstack before unmapping it.
[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, TypeKind};
20 use llvm::{True, False, Bool, OperandBundleDef};
21 use middle::cfg;
22 use middle::def::Def;
23 use middle::def_id::DefId;
24 use middle::infer;
25 use middle::lang_items::LangItem;
26 use middle::subst::{self, Substs};
27 use trans::base;
28 use trans::build;
29 use trans::builder::Builder;
30 use trans::callee;
31 use trans::cleanup;
32 use trans::consts;
33 use trans::datum;
34 use trans::debuginfo::{self, DebugLoc};
35 use trans::declare;
36 use trans::machine;
37 use trans::monomorphize;
38 use trans::type_::Type;
39 use trans::type_of;
40 use middle::traits;
41 use middle::ty::{self, Ty};
42 use middle::ty::fold::{TypeFolder, TypeFoldable};
43 use rustc_front::hir;
44 use rustc::mir::repr::Mir;
45 use util::nodemap::{FnvHashMap, NodeMap};
46
47 use arena::TypedArena;
48 use libc::{c_uint, c_char};
49 use std::ops::Deref;
50 use std::ffi::CString;
51 use std::cell::{Cell, RefCell};
52 use std::vec::Vec;
53 use syntax::ast;
54 use syntax::codemap::{DUMMY_SP, Span};
55 use syntax::parse::token::InternedString;
56 use syntax::parse::token;
57
58 pub use trans::context::CrateContext;
59
60 /// Is the type's representation size known at compile time?
61 pub fn type_is_sized<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
62     ty.is_sized(&tcx.empty_parameter_environment(), DUMMY_SP)
63 }
64
65 pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
66     match ty.sty {
67         ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
68         ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
69         ty::TyBox(ty) => {
70             !type_is_sized(cx, ty)
71         }
72         _ => {
73             false
74         }
75     }
76 }
77
78 fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
79     match ty.sty {
80         ty::TyStruct(def, substs) => {
81             let fields = &def.struct_variant().fields;
82             fields.len() == 1 && {
83                 type_is_immediate(ccx, monomorphize::field_ty(ccx.tcx(), substs, &fields[0]))
84             }
85         }
86         _ => false
87     }
88 }
89
90 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
91     use trans::machine::llsize_of_alloc;
92     use trans::type_of::sizing_type_of;
93
94     let tcx = ccx.tcx();
95     let simple = ty.is_scalar() ||
96         ty.is_unique() || ty.is_region_ptr() ||
97         type_is_newtype_immediate(ccx, ty) ||
98         ty.is_simd();
99     if simple && !type_is_fat_ptr(tcx, ty) {
100         return true;
101     }
102     if !type_is_sized(tcx, ty) {
103         return false;
104     }
105     match ty.sty {
106         ty::TyStruct(..) | ty::TyEnum(..) | ty::TyTuple(..) | ty::TyArray(_, _) |
107         ty::TyClosure(..) => {
108             let llty = sizing_type_of(ccx, ty);
109             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
110         }
111         _ => type_is_zero_size(ccx, ty)
112     }
113 }
114
115 /// Identify types which have size zero at runtime.
116 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
117     use trans::machine::llsize_of_alloc;
118     use trans::type_of::sizing_type_of;
119     let llty = sizing_type_of(ccx, ty);
120     llsize_of_alloc(ccx, llty) == 0
121 }
122
123 /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function
124 /// return types. These are `()`, bot, uninhabited enums and all other zero-sized types.
125 pub fn return_type_is_void<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
126     ty.is_nil() || ty.is_empty(ccx.tcx()) || type_is_zero_size(ccx, ty)
127 }
128
129 /// Generates a unique symbol based off the name given. This is used to create
130 /// unique symbols for things like closures.
131 pub fn gensym_name(name: &str) -> ast::Name {
132     let num = token::gensym(name).0;
133     // use one colon which will get translated to a period by the mangler, and
134     // we're guaranteed that `num` is globally unique for this crate.
135     token::gensym(&format!("{}:{}", name, num))
136 }
137
138 /*
139 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
140 *
141 * An "extern" is an LLVM symbol we wind up emitting an undefined external
142 * reference to. This means "we don't have the thing in this compilation unit,
143 * please make sure you link it in at runtime". This could be a reference to
144 * C code found in a C library, or rust code found in a rust crate.
145 *
146 * Most "externs" are implicitly declared (automatically) as a result of a
147 * user declaring an extern _module_ dependency; this causes the rust driver
148 * to locate an extern crate, scan its compilation metadata, and emit extern
149 * declarations for any symbols used by the declaring crate.
150 *
151 * A "foreign" is an extern that references C (or other non-rust ABI) code.
152 * There is no metadata to scan for extern references so in these cases either
153 * a header-digester like bindgen, or manual function prototypes, have to
154 * serve as declarators. So these are usually given explicitly as prototype
155 * declarations, in rust code, with ABI attributes on them noting which ABI to
156 * link via.
157 *
158 * An "upcall" is a foreign call generated by the compiler (not corresponding
159 * to any user-written call in the code) into the runtime library, to perform
160 * some helper task such as bringing a task to life, allocating memory, etc.
161 *
162 */
163
164 use trans::Disr;
165
166 #[derive(Copy, Clone)]
167 pub struct NodeIdAndSpan {
168     pub id: ast::NodeId,
169     pub span: Span,
170 }
171
172 pub fn expr_info(expr: &hir::Expr) -> NodeIdAndSpan {
173     NodeIdAndSpan { id: expr.id, span: expr.span }
174 }
175
176 /// The concrete version of ty::FieldDef. The name is the field index if
177 /// the field is numeric.
178 pub struct Field<'tcx>(pub ast::Name, pub Ty<'tcx>);
179
180 /// The concrete version of ty::VariantDef
181 pub struct VariantInfo<'tcx> {
182     pub discr: Disr,
183     pub fields: Vec<Field<'tcx>>
184 }
185
186 impl<'tcx> VariantInfo<'tcx> {
187     pub fn from_ty(tcx: &ty::ctxt<'tcx>,
188                    ty: Ty<'tcx>,
189                    opt_def: Option<Def>)
190                    -> Self
191     {
192         match ty.sty {
193             ty::TyStruct(adt, substs) | ty::TyEnum(adt, substs) => {
194                 let variant = match opt_def {
195                     None => adt.struct_variant(),
196                     Some(def) => adt.variant_of_def(def)
197                 };
198
199                 VariantInfo {
200                     discr: Disr::from(variant.disr_val),
201                     fields: variant.fields.iter().map(|f| {
202                         Field(f.name, monomorphize::field_ty(tcx, substs, f))
203                     }).collect()
204                 }
205             }
206
207             ty::TyTuple(ref v) => {
208                 VariantInfo {
209                     discr: Disr(0),
210                     fields: v.iter().enumerate().map(|(i, &t)| {
211                         Field(token::intern(&i.to_string()), t)
212                     }).collect()
213                 }
214             }
215
216             _ => {
217                 tcx.sess.bug(&format!(
218                     "cannot get field types from the type {:?}",
219                     ty));
220             }
221         }
222     }
223
224     /// Return the variant corresponding to a given node (e.g. expr)
225     pub fn of_node(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>, id: ast::NodeId) -> Self {
226         let node_def = tcx.def_map.borrow().get(&id).map(|v| v.full_def());
227         Self::from_ty(tcx, ty, node_def)
228     }
229
230     pub fn field_index(&self, name: ast::Name) -> usize {
231         self.fields.iter().position(|&Field(n,_)| n == name).unwrap_or_else(|| {
232             panic!("unknown field `{}`", name)
233         })
234     }
235 }
236
237 pub struct BuilderRef_res {
238     pub b: BuilderRef,
239 }
240
241 impl Drop for BuilderRef_res {
242     fn drop(&mut self) {
243         unsafe {
244             llvm::LLVMDisposeBuilder(self.b);
245         }
246     }
247 }
248
249 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
250     BuilderRef_res {
251         b: b
252     }
253 }
254
255 pub type ExternMap = FnvHashMap<String, ValueRef>;
256
257 pub fn validate_substs(substs: &Substs) {
258     assert!(!substs.types.needs_infer());
259 }
260
261 // work around bizarre resolve errors
262 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
263 pub type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
264
265 #[derive(Clone, Debug)]
266 struct HintEntry<'tcx> {
267     // The datum for the dropflag-hint itself; note that many
268     // source-level Lvalues will be associated with the same
269     // dropflag-hint datum.
270     datum: cleanup::DropHintDatum<'tcx>,
271 }
272
273 pub struct DropFlagHintsMap<'tcx> {
274     // Maps NodeId for expressions that read/write unfragmented state
275     // to that state's drop-flag "hint."  (A stack-local hint
276     // indicates either that (1.) it is certain that no-drop is
277     // needed, or (2.)  inline drop-flag must be consulted.)
278     node_map: NodeMap<HintEntry<'tcx>>,
279 }
280
281 impl<'tcx> DropFlagHintsMap<'tcx> {
282     pub fn new() -> DropFlagHintsMap<'tcx> { DropFlagHintsMap { node_map: NodeMap() } }
283     pub fn has_hint(&self, id: ast::NodeId) -> bool { self.node_map.contains_key(&id) }
284     pub fn insert(&mut self, id: ast::NodeId, datum: cleanup::DropHintDatum<'tcx>) {
285         self.node_map.insert(id, HintEntry { datum: datum });
286     }
287     pub fn hint_datum(&self, id: ast::NodeId) -> Option<cleanup::DropHintDatum<'tcx>> {
288         self.node_map.get(&id).map(|t|t.datum)
289     }
290 }
291
292 // Function context.  Every LLVM function we create will have one of
293 // these.
294 pub struct FunctionContext<'a, 'tcx: 'a> {
295     // The MIR for this function. At present, this is optional because
296     // we only have MIR available for things that are local to the
297     // crate.
298     pub mir: Option<&'a Mir<'tcx>>,
299
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 NOTE: @jroesch another use of ParamEnv
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     // When working with landingpad-based exceptions this value is alloca'd and
332     // later loaded when using the resume instruction. This ends up being
333     // critical to chaining landing pads and resuing already-translated
334     // cleanups.
335     //
336     // Note that for cleanuppad-based exceptions this is not used.
337     pub landingpad_alloca: Cell<Option<ValueRef>>,
338
339     // True if the caller expects this fn to use the out pointer to
340     // return. Either way, your code should write into the slot llretslotptr
341     // points to, but if this value is false, that slot will be a local alloca.
342     pub caller_expects_out_pointer: bool,
343
344     // Maps the DefId's for local variables to the allocas created for
345     // them in llallocas.
346     pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>,
347
348     // Same as above, but for closure upvars
349     pub llupvars: RefCell<NodeMap<ValueRef>>,
350
351     // Carries info about drop-flags for local bindings (longer term,
352     // paths) for the code being compiled.
353     pub lldropflag_hints: RefCell<DropFlagHintsMap<'tcx>>,
354
355     // The NodeId of the function, or -1 if it doesn't correspond to
356     // a user-defined function.
357     pub id: ast::NodeId,
358
359     // If this function is being monomorphized, this contains the type
360     // substitutions used.
361     pub param_substs: &'tcx Substs<'tcx>,
362
363     // The source span and nesting context where this function comes from, for
364     // error reporting and symbol generation.
365     pub span: Option<Span>,
366
367     // The arena that blocks are allocated from.
368     pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
369
370     // The arena that landing pads are allocated from.
371     pub lpad_arena: TypedArena<LandingPad>,
372
373     // This function's enclosing crate context.
374     pub ccx: &'a CrateContext<'a, 'tcx>,
375
376     // Used and maintained by the debuginfo module.
377     pub debug_context: debuginfo::FunctionDebugContext,
378
379     // Cleanup scopes.
380     pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
381
382     pub cfg: Option<cfg::CFG>,
383 }
384
385 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
386     pub fn mir(&self) -> &'a Mir<'tcx> {
387         self.mir.unwrap()
388     }
389
390     pub fn arg_offset(&self) -> usize {
391         self.env_arg_pos() + if self.llenv.is_some() { 1 } else { 0 }
392     }
393
394     pub fn env_arg_pos(&self) -> usize {
395         if self.caller_expects_out_pointer {
396             1
397         } else {
398             0
399         }
400     }
401
402     pub fn cleanup(&self) {
403         unsafe {
404             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
405                                                      .get()
406                                                      .unwrap());
407         }
408     }
409
410     pub fn get_llreturn(&self) -> BasicBlockRef {
411         if self.llreturn.get().is_none() {
412
413             self.llreturn.set(Some(unsafe {
414                 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn,
415                                                     "return\0".as_ptr() as *const _)
416             }))
417         }
418
419         self.llreturn.get().unwrap()
420     }
421
422     pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
423                         output: ty::FnOutput<'tcx>,
424                         name: &str) -> ValueRef {
425         if self.needs_ret_allocas {
426             base::alloca(bcx, match output {
427                 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
428                 ty::FnDiverging => Type::void(bcx.ccx())
429             }, name)
430         } else {
431             self.llretslotptr.get().unwrap()
432         }
433     }
434
435     pub fn new_block(&'a self,
436                      name: &str,
437                      opt_node_id: Option<ast::NodeId>)
438                      -> Block<'a, 'tcx> {
439         unsafe {
440             let name = CString::new(name).unwrap();
441             let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
442                                                            self.llfn,
443                                                            name.as_ptr());
444             BlockS::new(llbb, opt_node_id, self)
445         }
446     }
447
448     pub fn new_id_block(&'a self,
449                         name: &str,
450                         node_id: ast::NodeId)
451                         -> Block<'a, 'tcx> {
452         self.new_block(name, Some(node_id))
453     }
454
455     pub fn new_temp_block(&'a self,
456                           name: &str)
457                           -> Block<'a, 'tcx> {
458         self.new_block(name, None)
459     }
460
461     pub fn join_blocks(&'a self,
462                        id: ast::NodeId,
463                        in_cxs: &[Block<'a, 'tcx>])
464                        -> Block<'a, 'tcx> {
465         let out = self.new_id_block("join", id);
466         let mut reachable = false;
467         for bcx in in_cxs {
468             if !bcx.unreachable.get() {
469                 build::Br(*bcx, out.llbb, DebugLoc::None);
470                 reachable = true;
471             }
472         }
473         if !reachable {
474             build::Unreachable(out);
475         }
476         return out;
477     }
478
479     pub fn monomorphize<T>(&self, value: &T) -> T
480         where T : TypeFoldable<'tcx>
481     {
482         monomorphize::apply_param_substs(self.ccx.tcx(),
483                                          self.param_substs,
484                                          value)
485     }
486
487     /// This is the same as `common::type_needs_drop`, except that it
488     /// may use or update caches within this `FunctionContext`.
489     pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
490         self.ccx.tcx().type_needs_drop_given_env(ty, &self.param_env)
491     }
492
493     pub fn eh_personality(&self) -> ValueRef {
494         // The exception handling personality function.
495         //
496         // If our compilation unit has the `eh_personality` lang item somewhere
497         // within it, then we just need to translate that. Otherwise, we're
498         // building an rlib which will depend on some upstream implementation of
499         // this function, so we just codegen a generic reference to it. We don't
500         // specify any of the types for the function, we just make it a symbol
501         // that LLVM can later use.
502         //
503         // Note that MSVC is a little special here in that we don't use the
504         // `eh_personality` lang item at all. Currently LLVM has support for
505         // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
506         // *name of the personality function* to decide what kind of unwind side
507         // tables/landing pads to emit. It looks like Dwarf is used by default,
508         // injecting a dependency on the `_Unwind_Resume` symbol for resuming
509         // an "exception", but for MSVC we want to force SEH. This means that we
510         // can't actually have the personality function be our standard
511         // `rust_eh_personality` function, but rather we wired it up to the
512         // CRT's custom personality function, which forces LLVM to consider
513         // landing pads as "landing pads for SEH".
514         let target = &self.ccx.sess().target.target;
515         match self.ccx.tcx().lang_items.eh_personality() {
516             Some(def_id) if !base::wants_msvc_seh(self.ccx.sess()) => {
517                 callee::trans_fn_ref(self.ccx, def_id, ExprId(0),
518                                      self.param_substs).val
519             }
520             _ => {
521                 let mut personality = self.ccx.eh_personality().borrow_mut();
522                 match *personality {
523                     Some(llpersonality) => llpersonality,
524                     None => {
525                         let name = if !base::wants_msvc_seh(self.ccx.sess()) {
526                             "rust_eh_personality"
527                         } else if target.arch == "x86" {
528                             "_except_handler3"
529                         } else {
530                             "__C_specific_handler"
531                         };
532                         let fty = Type::variadic_func(&[], &Type::i32(self.ccx));
533                         let f = declare::declare_cfn(self.ccx, name, fty,
534                                                      self.ccx.tcx().types.i32);
535                         *personality = Some(f);
536                         f
537                     }
538                 }
539             }
540         }
541     }
542
543     // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined,
544     // otherwise declares it as an external function.
545     pub fn eh_unwind_resume(&self) -> ValueRef {
546         use trans::attributes;
547         assert!(self.ccx.sess().target.target.options.custom_unwind_resume);
548         match self.ccx.tcx().lang_items.eh_unwind_resume() {
549             Some(def_id) => {
550                 callee::trans_fn_ref(self.ccx, def_id, ExprId(0),
551                                      self.param_substs).val
552             }
553             None => {
554                 let mut unwresume = self.ccx.eh_unwind_resume().borrow_mut();
555                 match *unwresume {
556                     Some(llfn) => llfn,
557                     None => {
558                         let fty = Type::func(&[Type::i8p(self.ccx)], &Type::void(self.ccx));
559                         let llfn = declare::declare_fn(self.ccx,
560                                                        "rust_eh_unwind_resume",
561                                                        llvm::CCallConv,
562                                                        fty, ty::FnDiverging);
563                         attributes::unwind(llfn, true);
564                         *unwresume = Some(llfn);
565                         llfn
566                     }
567                 }
568             }
569         }
570     }
571 }
572
573 // Basic block context.  We create a block context for each basic block
574 // (single-entry, single-exit sequence of instructions) we generate from Rust
575 // code.  Each basic block we generate is attached to a function, typically
576 // with many basic blocks per function.  All the basic blocks attached to a
577 // function are organized as a directed graph.
578 pub struct BlockS<'blk, 'tcx: 'blk> {
579     // The BasicBlockRef returned from a call to
580     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
581     // block to the function pointed to by llfn.  We insert
582     // instructions into that block by way of this block context.
583     // The block pointing to this one in the function's digraph.
584     pub llbb: BasicBlockRef,
585     pub terminated: Cell<bool>,
586     pub unreachable: Cell<bool>,
587
588     // If this block part of a landing pad, then this is `Some` indicating what
589     // kind of landing pad its in, otherwise this is none.
590     pub lpad: Cell<Option<&'blk LandingPad>>,
591
592     // AST node-id associated with this block, if any. Used for
593     // debugging purposes only.
594     pub opt_node_id: Option<ast::NodeId>,
595
596     // The function context for the function to which this block is
597     // attached.
598     pub fcx: &'blk FunctionContext<'blk, 'tcx>,
599 }
600
601 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
602
603 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
604     pub fn new(llbb: BasicBlockRef,
605                opt_node_id: Option<ast::NodeId>,
606                fcx: &'blk FunctionContext<'blk, 'tcx>)
607                -> Block<'blk, 'tcx> {
608         fcx.block_arena.alloc(BlockS {
609             llbb: llbb,
610             terminated: Cell::new(false),
611             unreachable: Cell::new(false),
612             lpad: Cell::new(None),
613             opt_node_id: opt_node_id,
614             fcx: fcx
615         })
616     }
617
618     pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
619         self.fcx.ccx
620     }
621     pub fn fcx(&self) -> &'blk FunctionContext<'blk, 'tcx> {
622         self.fcx
623     }
624     pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
625         self.fcx.ccx.tcx()
626     }
627     pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
628
629     pub fn lpad(&self) -> Option<&'blk LandingPad> {
630         self.lpad.get()
631     }
632
633     pub fn mir(&self) -> &'blk Mir<'tcx> {
634         self.fcx.mir()
635     }
636
637     pub fn name(&self, name: ast::Name) -> String {
638         name.to_string()
639     }
640
641     pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
642         self.tcx().map.node_to_string(id).to_string()
643     }
644
645     pub fn def(&self, nid: ast::NodeId) -> Def {
646         match self.tcx().def_map.borrow().get(&nid) {
647             Some(v) => v.full_def(),
648             None => {
649                 self.tcx().sess.bug(&format!(
650                     "no def associated with node id {}", nid));
651             }
652         }
653     }
654
655     pub fn val_to_string(&self, val: ValueRef) -> String {
656         self.ccx().tn().val_to_string(val)
657     }
658
659     pub fn llty_str(&self, ty: Type) -> String {
660         self.ccx().tn().type_to_string(ty)
661     }
662
663     pub fn to_str(&self) -> String {
664         format!("[block {:p}]", self)
665     }
666
667     pub fn monomorphize<T>(&self, value: &T) -> T
668         where T : TypeFoldable<'tcx>
669     {
670         monomorphize::apply_param_substs(self.tcx(),
671                                          self.fcx.param_substs,
672                                          value)
673     }
674
675     pub fn build(&'blk self) -> BlockAndBuilder<'blk, 'tcx> {
676         BlockAndBuilder::new(self, OwnedBuilder::new_with_ccx(self.ccx()))
677     }
678 }
679
680 pub struct OwnedBuilder<'blk, 'tcx: 'blk> {
681     builder: Builder<'blk, 'tcx>
682 }
683
684 impl<'blk, 'tcx> OwnedBuilder<'blk, 'tcx> {
685     pub fn new_with_ccx(ccx: &'blk CrateContext<'blk, 'tcx>) -> Self {
686         // Create a fresh builder from the crate context.
687         let llbuilder = unsafe {
688             llvm::LLVMCreateBuilderInContext(ccx.llcx())
689         };
690         OwnedBuilder {
691             builder: Builder {
692                 llbuilder: llbuilder,
693                 ccx: ccx,
694             }
695         }
696     }
697 }
698
699 impl<'blk, 'tcx> Drop for OwnedBuilder<'blk, 'tcx> {
700     fn drop(&mut self) {
701         unsafe {
702             llvm::LLVMDisposeBuilder(self.builder.llbuilder);
703         }
704     }
705 }
706
707 pub struct BlockAndBuilder<'blk, 'tcx: 'blk> {
708     bcx: Block<'blk, 'tcx>,
709     owned_builder: OwnedBuilder<'blk, 'tcx>,
710 }
711
712 impl<'blk, 'tcx> BlockAndBuilder<'blk, 'tcx> {
713     pub fn new(bcx: Block<'blk, 'tcx>, owned_builder: OwnedBuilder<'blk, 'tcx>) -> Self {
714         // Set the builder's position to this block's end.
715         owned_builder.builder.position_at_end(bcx.llbb);
716         BlockAndBuilder {
717             bcx: bcx,
718             owned_builder: owned_builder,
719         }
720     }
721
722     pub fn with_block<F, R>(&self, f: F) -> R
723         where F: FnOnce(Block<'blk, 'tcx>) -> R
724     {
725         let result = f(self.bcx);
726         self.position_at_end(self.bcx.llbb);
727         result
728     }
729
730     pub fn map_block<F>(self, f: F) -> Self
731         where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
732     {
733         let BlockAndBuilder { bcx, owned_builder } = self;
734         let bcx = f(bcx);
735         BlockAndBuilder::new(bcx, owned_builder)
736     }
737
738     // Methods delegated to bcx
739
740     pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
741         self.bcx.ccx()
742     }
743     pub fn fcx(&self) -> &'blk FunctionContext<'blk, 'tcx> {
744         self.bcx.fcx()
745     }
746     pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
747         self.bcx.tcx()
748     }
749     pub fn sess(&self) -> &'blk Session {
750         self.bcx.sess()
751     }
752
753     pub fn llbb(&self) -> BasicBlockRef {
754         self.bcx.llbb
755     }
756
757     pub fn mir(&self) -> &'blk Mir<'tcx> {
758         self.bcx.mir()
759     }
760
761     pub fn val_to_string(&self, val: ValueRef) -> String {
762         self.bcx.val_to_string(val)
763     }
764
765     pub fn monomorphize<T>(&self, value: &T) -> T
766         where T: TypeFoldable<'tcx>
767     {
768         self.bcx.monomorphize(value)
769     }
770 }
771
772 impl<'blk, 'tcx> Deref for BlockAndBuilder<'blk, 'tcx> {
773     type Target = Builder<'blk, 'tcx>;
774     fn deref(&self) -> &Self::Target {
775         &self.owned_builder.builder
776     }
777 }
778
779 /// A structure representing an active landing pad for the duration of a basic
780 /// block.
781 ///
782 /// Each `Block` may contain an instance of this, indicating whether the block
783 /// is part of a landing pad or not. This is used to make decision about whether
784 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
785 /// use `invoke`) and also about various function call metadata.
786 ///
787 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
788 /// just a bunch of `None` instances (not too interesting), but for MSVC
789 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
790 /// When inside of a landing pad, each function call in LLVM IR needs to be
791 /// annotated with which landing pad it's a part of. This is accomplished via
792 /// the `OperandBundleDef` value created for MSVC landing pads.
793 pub struct LandingPad {
794     cleanuppad: Option<ValueRef>,
795     operand: Option<OperandBundleDef>,
796 }
797
798 impl LandingPad {
799     pub fn gnu() -> LandingPad {
800         LandingPad { cleanuppad: None, operand: None }
801     }
802
803     pub fn msvc(cleanuppad: ValueRef) -> LandingPad {
804         LandingPad {
805             cleanuppad: Some(cleanuppad),
806             operand: Some(OperandBundleDef::new("funclet", &[cleanuppad])),
807         }
808     }
809
810     pub fn bundle(&self) -> Option<&OperandBundleDef> {
811         self.operand.as_ref()
812     }
813 }
814
815 impl Clone for LandingPad {
816     fn clone(&self) -> LandingPad {
817         LandingPad {
818             cleanuppad: self.cleanuppad,
819             operand: self.cleanuppad.map(|p| {
820                 OperandBundleDef::new("funclet", &[p])
821             }),
822         }
823     }
824 }
825
826 pub struct Result<'blk, 'tcx: 'blk> {
827     pub bcx: Block<'blk, 'tcx>,
828     pub val: ValueRef
829 }
830
831 impl<'b, 'tcx> Result<'b, 'tcx> {
832     pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
833         Result {
834             bcx: bcx,
835             val: val,
836         }
837     }
838 }
839
840 pub fn val_ty(v: ValueRef) -> Type {
841     unsafe {
842         Type::from_ref(llvm::LLVMTypeOf(v))
843     }
844 }
845
846 // LLVM constant constructors.
847 pub fn C_null(t: Type) -> ValueRef {
848     unsafe {
849         llvm::LLVMConstNull(t.to_ref())
850     }
851 }
852
853 pub fn C_undef(t: Type) -> ValueRef {
854     unsafe {
855         llvm::LLVMGetUndef(t.to_ref())
856     }
857 }
858
859 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
860     unsafe {
861         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
862     }
863 }
864
865 pub fn C_floating(s: &str, t: Type) -> ValueRef {
866     unsafe {
867         let s = CString::new(s).unwrap();
868         llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr())
869     }
870 }
871
872 pub fn C_floating_f64(f: f64, t: Type) -> ValueRef {
873     unsafe {
874         llvm::LLVMConstReal(t.to_ref(), f)
875     }
876 }
877
878 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
879     C_struct(ccx, &[], false)
880 }
881
882 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
883     C_integral(Type::i1(ccx), val as u64, false)
884 }
885
886 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
887     C_integral(Type::i32(ccx), i as u64, true)
888 }
889
890 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
891     C_integral(Type::i32(ccx), i as u64, false)
892 }
893
894 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
895     C_integral(Type::i64(ccx), i, false)
896 }
897
898 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
899     let v = i.as_i64();
900
901     let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type());
902
903     if bit_size < 64 {
904         // make sure it doesn't overflow
905         assert!(v < (1<<(bit_size-1)) && v >= -(1<<(bit_size-1)));
906     }
907
908     C_integral(ccx.int_type(), v as u64, true)
909 }
910
911 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
912     let v = i.as_u64();
913
914     let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type());
915
916     if bit_size < 64 {
917         // make sure it doesn't overflow
918         assert!(v < (1<<bit_size));
919     }
920
921     C_integral(ccx.int_type(), v, false)
922 }
923
924 pub trait AsI64 { fn as_i64(self) -> i64; }
925 pub trait AsU64 { fn as_u64(self) -> u64; }
926
927 // FIXME: remove the intptr conversions, because they
928 // are host-architecture-dependent
929 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
930 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
931 impl AsI64 for isize { fn as_i64(self) -> i64 { self as i64 }}
932
933 impl AsU64 for u64  { fn as_u64(self) -> u64 { self as u64 }}
934 impl AsU64 for u32  { fn as_u64(self) -> u64 { self as u64 }}
935 impl AsU64 for usize { fn as_u64(self) -> u64 { self as u64 }}
936
937 pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef {
938     C_integral(Type::i8(ccx), i as u64, false)
939 }
940
941
942 // This is a 'c-like' raw string, which differs from
943 // our boxed-and-length-annotated strings.
944 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
945     unsafe {
946         match cx.const_cstr_cache().borrow().get(&s) {
947             Some(&llval) => return llval,
948             None => ()
949         }
950
951         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
952                                                 s.as_ptr() as *const c_char,
953                                                 s.len() as c_uint,
954                                                 !null_terminated as Bool);
955
956         let gsym = token::gensym("str");
957         let sym = format!("str{}", gsym.0);
958         let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
959             cx.sess().bug(&format!("symbol `{}` is already defined", sym));
960         });
961         llvm::LLVMSetInitializer(g, sc);
962         llvm::LLVMSetGlobalConstant(g, True);
963         llvm::SetLinkage(g, llvm::InternalLinkage);
964
965         cx.const_cstr_cache().borrow_mut().insert(s, g);
966         g
967     }
968 }
969
970 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
971 // you will be kicked off fast isel. See issue #4352 for an example of this.
972 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
973     let len = s.len();
974     let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
975     C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
976 }
977
978 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
979     C_struct_in_context(cx.llcx(), elts, packed)
980 }
981
982 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
983     unsafe {
984         llvm::LLVMConstStructInContext(llcx,
985                                        elts.as_ptr(), elts.len() as c_uint,
986                                        packed as Bool)
987     }
988 }
989
990 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
991     unsafe {
992         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
993     }
994 }
995
996 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
997     unsafe {
998         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
999     }
1000 }
1001
1002 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
1003     unsafe {
1004         return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
1005     }
1006 }
1007
1008 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
1009     C_bytes_in_context(cx.llcx(), bytes)
1010 }
1011
1012 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
1013     unsafe {
1014         let ptr = bytes.as_ptr() as *const c_char;
1015         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
1016     }
1017 }
1018
1019 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
1020               -> ValueRef {
1021     unsafe {
1022         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
1023
1024         debug!("const_get_elt(v={}, us={:?}, r={})",
1025                cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
1026
1027         return r;
1028     }
1029 }
1030
1031 pub fn const_to_int(v: ValueRef) -> i64 {
1032     unsafe {
1033         llvm::LLVMConstIntGetSExtValue(v)
1034     }
1035 }
1036
1037 pub fn const_to_uint(v: ValueRef) -> u64 {
1038     unsafe {
1039         llvm::LLVMConstIntGetZExtValue(v)
1040     }
1041 }
1042
1043 fn is_const_integral(v: ValueRef) -> bool {
1044     unsafe {
1045         !llvm::LLVMIsAConstantInt(v).is_null()
1046     }
1047 }
1048
1049 pub fn const_to_opt_int(v: ValueRef) -> Option<i64> {
1050     unsafe {
1051         if is_const_integral(v) {
1052             Some(llvm::LLVMConstIntGetSExtValue(v))
1053         } else {
1054             None
1055         }
1056     }
1057 }
1058
1059 pub fn const_to_opt_uint(v: ValueRef) -> Option<u64> {
1060     unsafe {
1061         if is_const_integral(v) {
1062             Some(llvm::LLVMConstIntGetZExtValue(v))
1063         } else {
1064             None
1065         }
1066     }
1067 }
1068
1069 pub fn is_undef(val: ValueRef) -> bool {
1070     unsafe {
1071         llvm::LLVMIsUndef(val) != False
1072     }
1073 }
1074
1075 #[allow(dead_code)] // potentially useful
1076 pub fn is_null(val: ValueRef) -> bool {
1077     unsafe {
1078         llvm::LLVMIsNull(val) != False
1079     }
1080 }
1081
1082 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
1083     bcx.fcx.monomorphize(&t)
1084 }
1085
1086 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
1087     let tcx = bcx.tcx();
1088     let t = tcx.node_id_to_type(id);
1089     monomorphize_type(bcx, t)
1090 }
1091
1092 pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &hir::Expr) -> Ty<'tcx> {
1093     node_id_type(bcx, ex.id)
1094 }
1095
1096 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &hir::Expr) -> Ty<'tcx> {
1097     monomorphize_type(bcx, bcx.tcx().expr_ty_adjusted(ex))
1098 }
1099
1100 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
1101 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
1102 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
1103 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1104                                     span: Span,
1105                                     trait_ref: ty::PolyTraitRef<'tcx>)
1106                                     -> traits::Vtable<'tcx, ()>
1107 {
1108     let tcx = ccx.tcx();
1109
1110     // Remove any references to regions; this helps improve caching.
1111     let trait_ref = tcx.erase_regions(&trait_ref);
1112
1113     // First check the cache.
1114     match ccx.trait_cache().borrow().get(&trait_ref) {
1115         Some(vtable) => {
1116             info!("Cache hit: {:?}", trait_ref);
1117             return (*vtable).clone();
1118         }
1119         None => { }
1120     }
1121
1122     debug!("trans fulfill_obligation: trait_ref={:?} def_id={:?}",
1123            trait_ref, trait_ref.def_id());
1124
1125
1126     // Do the initial selection for the obligation. This yields the
1127     // shallow result we are looking for -- that is, what specific impl.
1128     let infcx = infer::normalizing_infer_ctxt(tcx, &tcx.tables);
1129     let mut selcx = traits::SelectionContext::new(&infcx);
1130
1131     let obligation =
1132         traits::Obligation::new(traits::ObligationCause::misc(span, ast::DUMMY_NODE_ID),
1133                                 trait_ref.to_poly_trait_predicate());
1134     let selection = match selcx.select(&obligation) {
1135         Ok(Some(selection)) => selection,
1136         Ok(None) => {
1137             // Ambiguity can happen when monomorphizing during trans
1138             // expands to some humongo type that never occurred
1139             // statically -- this humongo type can then overflow,
1140             // leading to an ambiguous result. So report this as an
1141             // overflow bug, since I believe this is the only case
1142             // where ambiguity can result.
1143             debug!("Encountered ambiguity selecting `{:?}` during trans, \
1144                     presuming due to overflow",
1145                    trait_ref);
1146             ccx.sess().span_fatal(
1147                 span,
1148                 "reached the recursion limit during monomorphization (selection ambiguity)");
1149         }
1150         Err(e) => {
1151             tcx.sess.span_bug(
1152                 span,
1153                 &format!("Encountered error `{:?}` selecting `{:?}` during trans",
1154                         e,
1155                         trait_ref))
1156         }
1157     };
1158
1159     // Currently, we use a fulfillment context to completely resolve
1160     // all nested obligations. This is because they can inform the
1161     // inference of the impl's type parameters.
1162     let mut fulfill_cx = traits::FulfillmentContext::new();
1163     let vtable = selection.map(|predicate| {
1164         fulfill_cx.register_predicate_obligation(&infcx, predicate);
1165     });
1166     let vtable = infer::drain_fulfillment_cx_or_panic(
1167         span, &infcx, &mut fulfill_cx, &vtable
1168     );
1169
1170     info!("Cache miss: {:?} => {:?}", trait_ref, vtable);
1171
1172     ccx.trait_cache().borrow_mut().insert(trait_ref, vtable.clone());
1173
1174     vtable
1175 }
1176
1177 /// Normalizes the predicates and checks whether they hold.  If this
1178 /// returns false, then either normalize encountered an error or one
1179 /// of the predicates did not hold. Used when creating vtables to
1180 /// check for unsatisfiable methods.
1181 pub fn normalize_and_test_predicates<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1182                                                predicates: Vec<ty::Predicate<'tcx>>)
1183                                                -> bool
1184 {
1185     debug!("normalize_and_test_predicates(predicates={:?})",
1186            predicates);
1187
1188     let tcx = ccx.tcx();
1189     let infcx = infer::normalizing_infer_ctxt(tcx, &tcx.tables);
1190     let mut selcx = traits::SelectionContext::new(&infcx);
1191     let mut fulfill_cx = traits::FulfillmentContext::new();
1192     let cause = traits::ObligationCause::dummy();
1193     let traits::Normalized { value: predicates, obligations } =
1194         traits::normalize(&mut selcx, cause.clone(), &predicates);
1195     for obligation in obligations {
1196         fulfill_cx.register_predicate_obligation(&infcx, obligation);
1197     }
1198     for predicate in predicates {
1199         let obligation = traits::Obligation::new(cause.clone(), predicate);
1200         fulfill_cx.register_predicate_obligation(&infcx, obligation);
1201     }
1202
1203     infer::drain_fulfillment_cx(&infcx, &mut fulfill_cx, &()).is_ok()
1204 }
1205
1206 // Key used to lookup values supplied for type parameters in an expr.
1207 #[derive(Copy, Clone, PartialEq, Debug)]
1208 pub enum ExprOrMethodCall {
1209     // Type parameters for a path like `None::<int>`
1210     ExprId(ast::NodeId),
1211
1212     // Type parameters for a method call like `a.foo::<int>()`
1213     MethodCallKey(ty::MethodCall)
1214 }
1215
1216 pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1217                                 node: ExprOrMethodCall,
1218                                 param_substs: &subst::Substs<'tcx>)
1219                                 -> subst::Substs<'tcx> {
1220     let tcx = ccx.tcx();
1221
1222     let substs = match node {
1223         ExprId(id) => {
1224             tcx.node_id_item_substs(id).substs
1225         }
1226         MethodCallKey(method_call) => {
1227             tcx.tables.borrow().method_map[&method_call].substs.clone()
1228         }
1229     };
1230
1231     if substs.types.needs_infer() {
1232         tcx.sess.bug(&format!("type parameters for node {:?} include inference types: {:?}",
1233                               node, substs));
1234     }
1235
1236     monomorphize::apply_param_substs(tcx,
1237                                      param_substs,
1238                                      &substs.erase_regions())
1239 }
1240
1241 pub fn langcall(bcx: Block,
1242                 span: Option<Span>,
1243                 msg: &str,
1244                 li: LangItem)
1245                 -> DefId {
1246     match bcx.tcx().lang_items.require(li) {
1247         Ok(id) => id,
1248         Err(s) => {
1249             let msg = format!("{} {}", msg, s);
1250             match span {
1251                 Some(span) => bcx.tcx().sess.span_fatal(span, &msg[..]),
1252                 None => bcx.tcx().sess.fatal(&msg[..]),
1253             }
1254         }
1255     }
1256 }
1257
1258 /// Return the VariantDef corresponding to an inlined variant node
1259 pub fn inlined_variant_def<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1260                                      inlined_vid: ast::NodeId)
1261                                      -> ty::VariantDef<'tcx>
1262 {
1263
1264     let ctor_ty = ccx.tcx().node_id_to_type(inlined_vid);
1265     debug!("inlined_variant_def: ctor_ty={:?} inlined_vid={:?}", ctor_ty,
1266            inlined_vid);
1267     let adt_def = match ctor_ty.sty {
1268         ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
1269             output: ty::FnConverging(ty), ..
1270         }), ..}) => ty,
1271         _ => ctor_ty
1272     }.ty_adt_def().unwrap();
1273     let inlined_vid_def_id = ccx.tcx().map.local_def_id(inlined_vid);
1274     adt_def.variants.iter().find(|v| {
1275         inlined_vid_def_id == v.did ||
1276             ccx.external().borrow().get(&v.did) == Some(&Some(inlined_vid))
1277     }).unwrap_or_else(|| {
1278         ccx.sess().bug(&format!("no variant for {:?}::{}", adt_def, inlined_vid))
1279     })
1280 }
1281
1282 // To avoid UB from LLVM, these two functions mask RHS with an
1283 // appropriate mask unconditionally (i.e. the fallback behavior for
1284 // all shifts). For 32- and 64-bit types, this matches the semantics
1285 // of Java. (See related discussion on #1877 and #10183.)
1286
1287 pub fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1288                                           lhs: ValueRef,
1289                                           rhs: ValueRef,
1290                                           binop_debug_loc: DebugLoc) -> ValueRef {
1291     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
1292     // #1877, #10183: Ensure that input is always valid
1293     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
1294     build::Shl(bcx, lhs, rhs, binop_debug_loc)
1295 }
1296
1297 pub fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1298                                           lhs_t: Ty<'tcx>,
1299                                           lhs: ValueRef,
1300                                           rhs: ValueRef,
1301                                           binop_debug_loc: DebugLoc) -> ValueRef {
1302     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
1303     // #1877, #10183: Ensure that input is always valid
1304     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
1305     let is_signed = lhs_t.is_signed();
1306     if is_signed {
1307         build::AShr(bcx, lhs, rhs, binop_debug_loc)
1308     } else {
1309         build::LShr(bcx, lhs, rhs, binop_debug_loc)
1310     }
1311 }
1312
1313 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1314                               rhs: ValueRef,
1315                               debug_loc: DebugLoc) -> ValueRef {
1316     let rhs_llty = val_ty(rhs);
1317     build::And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
1318 }
1319
1320 pub fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1321                               llty: Type,
1322                               mask_llty: Type,
1323                               invert: bool) -> ValueRef {
1324     let kind = llty.kind();
1325     match kind {
1326         TypeKind::Integer => {
1327             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
1328             let val = llty.int_width() - 1;
1329             if invert {
1330                 C_integral(mask_llty, !val, true)
1331             } else {
1332                 C_integral(mask_llty, val, false)
1333             }
1334         },
1335         TypeKind::Vector => {
1336             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
1337             build::VectorSplat(bcx, mask_llty.vector_length(), mask)
1338         },
1339         _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
1340     }
1341 }
1342
1343 pub fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1344                             did: DefId,
1345                             ty: Ty<'tcx>)
1346                             -> ValueRef {
1347     if let Some(node_id) = ccx.tcx().map.as_local_node_id(did) {
1348         base::get_item_val(ccx, node_id)
1349     } else {
1350         base::get_extern_const(ccx, did, ty)
1351     }
1352 }