]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/builder.rs
Auto merge of #66730 - hermitcore:master, r=alexcrichton
[rust.git] / src / librustc_codegen_llvm / builder.rs
1 use crate::llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope};
2 use crate::llvm::{self, False, BasicBlock};
3 use crate::common::Funclet;
4 use crate::context::CodegenCx;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
8 use rustc_codegen_ssa::common::{IntPredicate, TypeKind, RealPredicate};
9 use rustc_codegen_ssa::MemFlags;
10 use libc::{c_uint, c_char};
11 use rustc::ty::{self, Ty, TyCtxt};
12 use rustc::ty::layout::{self, Align, Size, TyLayout};
13 use rustc::hir::def_id::DefId;
14 use rustc::session::config;
15 use rustc_data_structures::small_c_str::SmallCStr;
16 use rustc_codegen_ssa::traits::*;
17 use rustc_codegen_ssa::base::to_immediate;
18 use rustc_codegen_ssa::mir::operand::{OperandValue, OperandRef};
19 use rustc_codegen_ssa::mir::place::PlaceRef;
20 use rustc_target::spec::{HasTargetSpec, Target};
21 use std::borrow::Cow;
22 use std::ffi::CStr;
23 use std::ops::{Deref, Range};
24 use std::ptr;
25 use std::iter::TrustedLen;
26
27 // All Builders must have an llfn associated with them
28 #[must_use]
29 pub struct Builder<'a, 'll, 'tcx> {
30     pub llbuilder: &'ll mut llvm::Builder<'ll>,
31     pub cx: &'a CodegenCx<'ll, 'tcx>,
32 }
33
34 impl Drop for Builder<'a, 'll, 'tcx> {
35     fn drop(&mut self) {
36         unsafe {
37             llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
38         }
39     }
40 }
41
42 // FIXME(eddyb) use a checked constructor when they become `const fn`.
43 const EMPTY_C_STR: &CStr = unsafe {
44     CStr::from_bytes_with_nul_unchecked(b"\0")
45 };
46
47 /// Empty string, to be used where LLVM expects an instruction name, indicating
48 /// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
49 // FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
50 const UNNAMED: *const c_char = EMPTY_C_STR.as_ptr();
51
52 impl BackendTypes for Builder<'_, 'll, 'tcx> {
53     type Value = <CodegenCx<'ll, 'tcx> as BackendTypes>::Value;
54     type Function = <CodegenCx<'ll, 'tcx> as BackendTypes>::Function;
55     type BasicBlock = <CodegenCx<'ll, 'tcx> as BackendTypes>::BasicBlock;
56     type Type = <CodegenCx<'ll, 'tcx> as BackendTypes>::Type;
57     type Funclet = <CodegenCx<'ll, 'tcx> as BackendTypes>::Funclet;
58
59     type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
60 }
61
62 impl ty::layout::HasDataLayout for Builder<'_, '_, '_> {
63     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
64         self.cx.data_layout()
65     }
66 }
67
68 impl ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
69     fn tcx(&self) -> TyCtxt<'tcx> {
70         self.cx.tcx
71     }
72 }
73
74 impl ty::layout::HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
75     fn param_env(&self) -> ty::ParamEnv<'tcx> {
76         self.cx.param_env()
77     }
78 }
79
80 impl HasTargetSpec for Builder<'_, '_, 'tcx> {
81     fn target_spec(&self) -> &Target {
82         &self.cx.target_spec()
83     }
84 }
85
86 impl ty::layout::LayoutOf for Builder<'_, '_, 'tcx> {
87     type Ty = Ty<'tcx>;
88     type TyLayout = TyLayout<'tcx>;
89
90     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
91         self.cx.layout_of(ty)
92     }
93 }
94
95 impl Deref for Builder<'_, 'll, 'tcx> {
96     type Target = CodegenCx<'ll, 'tcx>;
97
98     fn deref(&self) -> &Self::Target {
99         self.cx
100     }
101 }
102
103 impl HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
104     type CodegenCx = CodegenCx<'ll, 'tcx>;
105 }
106
107 macro_rules! builder_methods_for_value_instructions {
108     ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
109         $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
110             unsafe {
111                 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
112             }
113         })+
114     }
115 }
116
117 impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
118     fn new_block<'b>(
119         cx: &'a CodegenCx<'ll, 'tcx>,
120         llfn: &'ll Value,
121         name: &'b str
122     ) -> Self {
123         let mut bx = Builder::with_cx(cx);
124         let llbb = unsafe {
125             let name = SmallCStr::new(name);
126             llvm::LLVMAppendBasicBlockInContext(
127                 cx.llcx,
128                 llfn,
129                 name.as_ptr()
130             )
131         };
132         bx.position_at_end(llbb);
133         bx
134     }
135
136     fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
137         // Create a fresh builder from the crate context.
138         let llbuilder = unsafe {
139             llvm::LLVMCreateBuilderInContext(cx.llcx)
140         };
141         Builder {
142             llbuilder,
143             cx,
144         }
145     }
146
147     fn build_sibling_block(&self, name: &str) -> Self {
148         Builder::new_block(self.cx, self.llfn(), name)
149     }
150
151     fn llbb(&self) -> &'ll BasicBlock {
152         unsafe {
153             llvm::LLVMGetInsertBlock(self.llbuilder)
154         }
155     }
156
157     fn position_at_end(&mut self, llbb: &'ll BasicBlock) {
158         unsafe {
159             llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
160         }
161     }
162
163     fn ret_void(&mut self) {
164         unsafe {
165             llvm::LLVMBuildRetVoid(self.llbuilder);
166         }
167     }
168
169     fn ret(&mut self, v: &'ll Value) {
170         unsafe {
171             llvm::LLVMBuildRet(self.llbuilder, v);
172         }
173     }
174
175     fn br(&mut self, dest: &'ll BasicBlock) {
176         unsafe {
177             llvm::LLVMBuildBr(self.llbuilder, dest);
178         }
179     }
180
181     fn cond_br(
182         &mut self,
183         cond: &'ll Value,
184         then_llbb: &'ll BasicBlock,
185         else_llbb: &'ll BasicBlock,
186     ) {
187         unsafe {
188             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
189         }
190     }
191
192     fn switch(
193         &mut self,
194         v: &'ll Value,
195         else_llbb: &'ll BasicBlock,
196         cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)> + TrustedLen,
197     ) {
198         let switch = unsafe {
199             llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint)
200         };
201         for (on_val, dest) in cases {
202             let on_val = self.const_uint_big(self.val_ty(v), on_val);
203             unsafe {
204                 llvm::LLVMAddCase(switch, on_val, dest)
205             }
206         }
207     }
208
209     fn invoke(
210         &mut self,
211         llfn: &'ll Value,
212         args: &[&'ll Value],
213         then: &'ll BasicBlock,
214         catch: &'ll BasicBlock,
215         funclet: Option<&Funclet<'ll>>,
216     ) -> &'ll Value {
217
218         debug!("invoke {:?} with args ({:?})",
219                llfn,
220                args);
221
222         let args = self.check_call("invoke", llfn, args);
223         let bundle = funclet.map(|funclet| funclet.bundle());
224         let bundle = bundle.as_ref().map(|b| &*b.raw);
225
226         unsafe {
227             llvm::LLVMRustBuildInvoke(self.llbuilder,
228                                       llfn,
229                                       args.as_ptr(),
230                                       args.len() as c_uint,
231                                       then,
232                                       catch,
233                                       bundle,
234                                       UNNAMED)
235         }
236     }
237
238     fn unreachable(&mut self) {
239         unsafe {
240             llvm::LLVMBuildUnreachable(self.llbuilder);
241         }
242     }
243
244     builder_methods_for_value_instructions! {
245         add(a, b) => LLVMBuildAdd,
246         fadd(a, b) => LLVMBuildFAdd,
247         sub(a, b) => LLVMBuildSub,
248         fsub(a, b) => LLVMBuildFSub,
249         mul(a, b) => LLVMBuildMul,
250         fmul(a, b) => LLVMBuildFMul,
251         udiv(a, b) => LLVMBuildUDiv,
252         exactudiv(a, b) => LLVMBuildExactUDiv,
253         sdiv(a, b) => LLVMBuildSDiv,
254         exactsdiv(a, b) => LLVMBuildExactSDiv,
255         fdiv(a, b) => LLVMBuildFDiv,
256         urem(a, b) => LLVMBuildURem,
257         srem(a, b) => LLVMBuildSRem,
258         frem(a, b) => LLVMBuildFRem,
259         shl(a, b) => LLVMBuildShl,
260         lshr(a, b) => LLVMBuildLShr,
261         ashr(a, b) => LLVMBuildAShr,
262         and(a, b) => LLVMBuildAnd,
263         or(a, b) => LLVMBuildOr,
264         xor(a, b) => LLVMBuildXor,
265         neg(x) => LLVMBuildNeg,
266         fneg(x) => LLVMBuildFNeg,
267         not(x) => LLVMBuildNot,
268         unchecked_sadd(x, y) => LLVMBuildNSWAdd,
269         unchecked_uadd(x, y) => LLVMBuildNUWAdd,
270         unchecked_ssub(x, y) => LLVMBuildNSWSub,
271         unchecked_usub(x, y) => LLVMBuildNUWSub,
272         unchecked_smul(x, y) => LLVMBuildNSWMul,
273         unchecked_umul(x, y) => LLVMBuildNUWMul,
274     }
275
276     fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
277         unsafe {
278             let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED);
279             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
280             instr
281         }
282     }
283
284     fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285         unsafe {
286             let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED);
287             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
288             instr
289         }
290     }
291
292     fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
293         unsafe {
294             let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED);
295             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
296             instr
297         }
298     }
299
300     fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
301         unsafe {
302             let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED);
303             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
304             instr
305         }
306     }
307
308     fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
309         unsafe {
310             let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED);
311             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
312             instr
313         }
314     }
315
316     fn checked_binop(
317         &mut self,
318         oop: OverflowOp,
319         ty: Ty<'_>,
320         lhs: Self::Value,
321         rhs: Self::Value,
322     ) -> (Self::Value, Self::Value) {
323         use syntax::ast::IntTy::*;
324         use syntax::ast::UintTy::*;
325         use rustc::ty::{Int, Uint};
326
327         let new_kind = match ty.kind {
328             Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.ptr_width)),
329             Uint(t @ Usize) => Uint(t.normalize(self.tcx.sess.target.ptr_width)),
330             ref t @ Uint(_) | ref t @ Int(_) => t.clone(),
331             _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
332         };
333
334         let name = match oop {
335             OverflowOp::Add => match new_kind {
336                 Int(I8) => "llvm.sadd.with.overflow.i8",
337                 Int(I16) => "llvm.sadd.with.overflow.i16",
338                 Int(I32) => "llvm.sadd.with.overflow.i32",
339                 Int(I64) => "llvm.sadd.with.overflow.i64",
340                 Int(I128) => "llvm.sadd.with.overflow.i128",
341
342                 Uint(U8) => "llvm.uadd.with.overflow.i8",
343                 Uint(U16) => "llvm.uadd.with.overflow.i16",
344                 Uint(U32) => "llvm.uadd.with.overflow.i32",
345                 Uint(U64) => "llvm.uadd.with.overflow.i64",
346                 Uint(U128) => "llvm.uadd.with.overflow.i128",
347
348                 _ => unreachable!(),
349             },
350             OverflowOp::Sub => match new_kind {
351                 Int(I8) => "llvm.ssub.with.overflow.i8",
352                 Int(I16) => "llvm.ssub.with.overflow.i16",
353                 Int(I32) => "llvm.ssub.with.overflow.i32",
354                 Int(I64) => "llvm.ssub.with.overflow.i64",
355                 Int(I128) => "llvm.ssub.with.overflow.i128",
356
357                 Uint(U8) => "llvm.usub.with.overflow.i8",
358                 Uint(U16) => "llvm.usub.with.overflow.i16",
359                 Uint(U32) => "llvm.usub.with.overflow.i32",
360                 Uint(U64) => "llvm.usub.with.overflow.i64",
361                 Uint(U128) => "llvm.usub.with.overflow.i128",
362
363                 _ => unreachable!(),
364             },
365             OverflowOp::Mul => match new_kind {
366                 Int(I8) => "llvm.smul.with.overflow.i8",
367                 Int(I16) => "llvm.smul.with.overflow.i16",
368                 Int(I32) => "llvm.smul.with.overflow.i32",
369                 Int(I64) => "llvm.smul.with.overflow.i64",
370                 Int(I128) => "llvm.smul.with.overflow.i128",
371
372                 Uint(U8) => "llvm.umul.with.overflow.i8",
373                 Uint(U16) => "llvm.umul.with.overflow.i16",
374                 Uint(U32) => "llvm.umul.with.overflow.i32",
375                 Uint(U64) => "llvm.umul.with.overflow.i64",
376                 Uint(U128) => "llvm.umul.with.overflow.i128",
377
378                 _ => unreachable!(),
379             },
380         };
381
382         let intrinsic = self.get_intrinsic(&name);
383         let res = self.call(intrinsic, &[lhs, rhs], None);
384         (
385             self.extract_value(res, 0),
386             self.extract_value(res, 1),
387         )
388     }
389
390     fn alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
391         let mut bx = Builder::with_cx(self.cx);
392         bx.position_at_start(unsafe {
393             llvm::LLVMGetFirstBasicBlock(self.llfn())
394         });
395         bx.dynamic_alloca(ty, align)
396     }
397
398     fn dynamic_alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
399         unsafe {
400             let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
401             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
402             alloca
403         }
404     }
405
406     fn array_alloca(&mut self,
407                         ty: &'ll Type,
408                         len: &'ll Value,
409                         align: Align) -> &'ll Value {
410         unsafe {
411             let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, UNNAMED);
412             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
413             alloca
414         }
415     }
416
417     fn load(&mut self, ptr: &'ll Value, align: Align) -> &'ll Value {
418         unsafe {
419             let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
420             llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
421             load
422         }
423     }
424
425     fn volatile_load(&mut self, ptr: &'ll Value) -> &'ll Value {
426         unsafe {
427             let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
428             llvm::LLVMSetVolatile(load, llvm::True);
429             load
430         }
431     }
432
433     fn atomic_load(
434         &mut self,
435         ptr: &'ll Value,
436         order: rustc_codegen_ssa::common::AtomicOrdering,
437         size: Size,
438     ) -> &'ll Value {
439         unsafe {
440             let load = llvm::LLVMRustBuildAtomicLoad(
441                 self.llbuilder,
442                 ptr,
443                 UNNAMED,
444                 AtomicOrdering::from_generic(order),
445             );
446             // LLVM requires the alignment of atomic loads to be at least the size of the type.
447             llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
448             load
449         }
450     }
451
452     fn load_operand(
453         &mut self,
454         place: PlaceRef<'tcx, &'ll Value>
455     ) -> OperandRef<'tcx, &'ll Value> {
456         debug!("PlaceRef::load: {:?}", place);
457
458         assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
459
460         if place.layout.is_zst() {
461             return OperandRef::new_zst(self, place.layout);
462         }
463
464         fn scalar_load_metadata<'a, 'll, 'tcx>(
465             bx: &mut Builder<'a, 'll, 'tcx>,
466             load: &'ll Value,
467             scalar: &layout::Scalar
468         ) {
469             let vr = scalar.valid_range.clone();
470             match scalar.value {
471                 layout::Int(..) => {
472                     let range = scalar.valid_range_exclusive(bx);
473                     if range.start != range.end {
474                         bx.range_metadata(load, range);
475                     }
476                 }
477                 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
478                     bx.nonnull_metadata(load);
479                 }
480                 _ => {}
481             }
482         }
483
484         let val = if let Some(llextra) = place.llextra {
485             OperandValue::Ref(place.llval, Some(llextra), place.align)
486         } else if place.layout.is_llvm_immediate() {
487             let mut const_llval = None;
488             unsafe {
489                 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
490                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
491                         const_llval = llvm::LLVMGetInitializer(global);
492                     }
493                 }
494             }
495             let llval = const_llval.unwrap_or_else(|| {
496                 let load = self.load(place.llval, place.align);
497                 if let layout::Abi::Scalar(ref scalar) = place.layout.abi {
498                     scalar_load_metadata(self, load, scalar);
499                 }
500                 load
501             });
502             OperandValue::Immediate(to_immediate(self, llval, place.layout))
503         } else if let layout::Abi::ScalarPair(ref a, ref b) = place.layout.abi {
504             let b_offset = a.value.size(self).align_to(b.value.align(self).abi);
505
506             let mut load = |i, scalar: &layout::Scalar, align| {
507                 let llptr = self.struct_gep(place.llval, i as u64);
508                 let load = self.load(llptr, align);
509                 scalar_load_metadata(self, load, scalar);
510                 if scalar.is_bool() {
511                     self.trunc(load, self.type_i1())
512                 } else {
513                     load
514                 }
515             };
516
517             OperandValue::Pair(
518                 load(0, a, place.align),
519                 load(1, b, place.align.restrict_for_offset(b_offset)),
520             )
521         } else {
522             OperandValue::Ref(place.llval, None, place.align)
523         };
524
525         OperandRef { val, layout: place.layout }
526     }
527
528     fn write_operand_repeatedly(
529         mut self,
530         cg_elem: OperandRef<'tcx, &'ll Value>,
531         count: u64,
532         dest: PlaceRef<'tcx, &'ll Value>,
533     ) -> Self {
534         let zero = self.const_usize(0);
535         let count = self.const_usize(count);
536         let start = dest.project_index(&mut self, zero).llval;
537         let end = dest.project_index(&mut self, count).llval;
538
539         let mut header_bx = self.build_sibling_block("repeat_loop_header");
540         let mut body_bx = self.build_sibling_block("repeat_loop_body");
541         let next_bx = self.build_sibling_block("repeat_loop_next");
542
543         self.br(header_bx.llbb());
544         let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
545
546         let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
547         header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
548
549         let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
550         cg_elem.val.store(&mut body_bx,
551             PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
552
553         let next = body_bx.inbounds_gep(current, &[self.const_usize(1)]);
554         body_bx.br(header_bx.llbb());
555         header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
556
557         next_bx
558     }
559
560     fn range_metadata(&mut self, load: &'ll Value, range: Range<u128>) {
561         if self.sess().target.target.arch == "amdgpu" {
562             // amdgpu/LLVM does something weird and thinks a i64 value is
563             // split into a v2i32, halving the bitwidth LLVM expects,
564             // tripping an assertion. So, for now, just disable this
565             // optimization.
566             return;
567         }
568
569         unsafe {
570             let llty = self.cx.val_ty(load);
571             let v = [
572                 self.cx.const_uint_big(llty, range.start),
573                 self.cx.const_uint_big(llty, range.end)
574             ];
575
576             llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
577                                   llvm::LLVMMDNodeInContext(self.cx.llcx,
578                                                             v.as_ptr(),
579                                                             v.len() as c_uint));
580         }
581     }
582
583     fn nonnull_metadata(&mut self, load: &'ll Value) {
584         unsafe {
585             llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
586                                   llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
587         }
588     }
589
590     fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
591         self.store_with_flags(val, ptr, align, MemFlags::empty())
592     }
593
594     fn store_with_flags(
595         &mut self,
596         val: &'ll Value,
597         ptr: &'ll Value,
598         align: Align,
599         flags: MemFlags,
600     ) -> &'ll Value {
601         debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
602         let ptr = self.check_store(val, ptr);
603         unsafe {
604             let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
605             let align = if flags.contains(MemFlags::UNALIGNED) {
606                 1
607             } else {
608                 align.bytes() as c_uint
609             };
610             llvm::LLVMSetAlignment(store, align);
611             if flags.contains(MemFlags::VOLATILE) {
612                 llvm::LLVMSetVolatile(store, llvm::True);
613             }
614             if flags.contains(MemFlags::NONTEMPORAL) {
615                 // According to LLVM [1] building a nontemporal store must
616                 // *always* point to a metadata value of the integer 1.
617                 //
618                 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
619                 let one = self.cx.const_i32(1);
620                 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
621                 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
622             }
623             store
624         }
625     }
626
627    fn atomic_store(&mut self, val: &'ll Value, ptr: &'ll Value,
628                    order: rustc_codegen_ssa::common::AtomicOrdering, size: Size) {
629         debug!("Store {:?} -> {:?}", val, ptr);
630         let ptr = self.check_store(val, ptr);
631         unsafe {
632             let store = llvm::LLVMRustBuildAtomicStore(
633                 self.llbuilder,
634                 val,
635                 ptr,
636                 AtomicOrdering::from_generic(order),
637             );
638             // LLVM requires the alignment of atomic stores to be at least the size of the type.
639             llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
640         }
641     }
642
643     fn gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
644         unsafe {
645             llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
646                                indices.len() as c_uint, UNNAMED)
647         }
648     }
649
650     fn inbounds_gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
651         unsafe {
652             llvm::LLVMBuildInBoundsGEP(
653                 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, UNNAMED)
654         }
655     }
656
657     fn struct_gep(&mut self, ptr: &'ll Value, idx: u64) -> &'ll Value {
658         assert_eq!(idx as c_uint as u64, idx);
659         unsafe {
660             llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, UNNAMED)
661         }
662     }
663
664     /* Casts */
665     fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
666         unsafe {
667             llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED)
668         }
669     }
670
671     fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
672         unsafe {
673             llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED)
674         }
675     }
676
677     fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
678         unsafe {
679             llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED)
680         }
681     }
682
683     fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
684         unsafe {
685             llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty,UNNAMED)
686         }
687     }
688
689     fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
690         unsafe {
691             llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED)
692         }
693     }
694
695     fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
696         unsafe {
697             llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED)
698         }
699     }
700
701     fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
702         unsafe {
703             llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED)
704         }
705     }
706
707     fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
708         unsafe {
709             llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED)
710         }
711     }
712
713     fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
714         unsafe {
715             llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED)
716         }
717     }
718
719     fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
720         unsafe {
721             llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED)
722         }
723     }
724
725     fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
726         unsafe {
727             llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED)
728         }
729     }
730
731
732     fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
733         unsafe {
734             llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed)
735         }
736     }
737
738     fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
739         unsafe {
740             llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED)
741         }
742     }
743
744     /* Comparisons */
745     fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
746         let op = llvm::IntPredicate::from_generic(op);
747         unsafe {
748             llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED)
749         }
750     }
751
752     fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
753         unsafe {
754             llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED)
755         }
756     }
757
758     /* Miscellaneous instructions */
759     fn memcpy(&mut self, dst: &'ll Value, dst_align: Align,
760                   src: &'ll Value, src_align: Align,
761                   size: &'ll Value, flags: MemFlags) {
762         if flags.contains(MemFlags::NONTEMPORAL) {
763             // HACK(nox): This is inefficient but there is no nontemporal memcpy.
764             let val = self.load(src, src_align);
765             let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
766             self.store_with_flags(val, ptr, dst_align, flags);
767             return;
768         }
769         let size = self.intcast(size, self.type_isize(), false);
770         let is_volatile = flags.contains(MemFlags::VOLATILE);
771         let dst = self.pointercast(dst, self.type_i8p());
772         let src = self.pointercast(src, self.type_i8p());
773         unsafe {
774             llvm::LLVMRustBuildMemCpy(self.llbuilder, dst, dst_align.bytes() as c_uint,
775                                       src, src_align.bytes() as c_uint, size, is_volatile);
776         }
777     }
778
779     fn memmove(&mut self, dst: &'ll Value, dst_align: Align,
780                   src: &'ll Value, src_align: Align,
781                   size: &'ll Value, flags: MemFlags) {
782         if flags.contains(MemFlags::NONTEMPORAL) {
783             // HACK(nox): This is inefficient but there is no nontemporal memmove.
784             let val = self.load(src, src_align);
785             let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
786             self.store_with_flags(val, ptr, dst_align, flags);
787             return;
788         }
789         let size = self.intcast(size, self.type_isize(), false);
790         let is_volatile = flags.contains(MemFlags::VOLATILE);
791         let dst = self.pointercast(dst, self.type_i8p());
792         let src = self.pointercast(src, self.type_i8p());
793         unsafe {
794             llvm::LLVMRustBuildMemMove(self.llbuilder, dst, dst_align.bytes() as c_uint,
795                                       src, src_align.bytes() as c_uint, size, is_volatile);
796         }
797     }
798
799     fn memset(
800         &mut self,
801         ptr: &'ll Value,
802         fill_byte: &'ll Value,
803         size: &'ll Value,
804         align: Align,
805         flags: MemFlags,
806     ) {
807         let ptr_width = &self.sess().target.target.target_pointer_width;
808         let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
809         let llintrinsicfn = self.get_intrinsic(&intrinsic_key);
810         let ptr = self.pointercast(ptr, self.type_i8p());
811         let align = self.const_u32(align.bytes() as u32);
812         let volatile = self.const_bool(flags.contains(MemFlags::VOLATILE));
813         self.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None);
814     }
815
816     fn select(
817         &mut self, cond: &'ll Value,
818         then_val: &'ll Value,
819         else_val: &'ll Value,
820     ) -> &'ll Value {
821         unsafe {
822             llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED)
823         }
824     }
825
826     #[allow(dead_code)]
827     fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
828         unsafe {
829             llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED)
830         }
831     }
832
833     fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
834         unsafe {
835             llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED)
836         }
837     }
838
839     fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
840         unsafe {
841             let elt_ty = self.cx.val_ty(elt);
842             let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
843             let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
844             let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
845             self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
846         }
847     }
848
849     fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
850         assert_eq!(idx as c_uint as u64, idx);
851         unsafe {
852             llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED)
853         }
854     }
855
856     fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value,
857                        idx: u64) -> &'ll Value {
858         assert_eq!(idx as c_uint as u64, idx);
859         unsafe {
860             llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
861                                        UNNAMED)
862         }
863     }
864
865     fn landing_pad(&mut self, ty: &'ll Type, pers_fn: &'ll Value,
866                        num_clauses: usize) -> &'ll Value {
867         unsafe {
868             llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn,
869                                       num_clauses as c_uint, UNNAMED)
870         }
871     }
872
873     fn set_cleanup(&mut self, landing_pad: &'ll Value) {
874         unsafe {
875             llvm::LLVMSetCleanup(landing_pad, llvm::True);
876         }
877     }
878
879     fn resume(&mut self, exn: &'ll Value) -> &'ll Value {
880         unsafe {
881             llvm::LLVMBuildResume(self.llbuilder, exn)
882         }
883     }
884
885     fn cleanup_pad(&mut self,
886                        parent: Option<&'ll Value>,
887                        args: &[&'ll Value]) -> Funclet<'ll> {
888         let name = const_cstr!("cleanuppad");
889         let ret = unsafe {
890             llvm::LLVMRustBuildCleanupPad(self.llbuilder,
891                                           parent,
892                                           args.len() as c_uint,
893                                           args.as_ptr(),
894                                           name.as_ptr())
895         };
896         Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
897     }
898
899     fn cleanup_ret(
900         &mut self, funclet: &Funclet<'ll>,
901         unwind: Option<&'ll BasicBlock>,
902     ) -> &'ll Value {
903         let ret = unsafe {
904             llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
905         };
906         ret.expect("LLVM does not have support for cleanupret")
907     }
908
909     fn catch_pad(&mut self,
910                      parent: &'ll Value,
911                      args: &[&'ll Value]) -> Funclet<'ll> {
912         let name = const_cstr!("catchpad");
913         let ret = unsafe {
914             llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
915                                         args.len() as c_uint, args.as_ptr(),
916                                         name.as_ptr())
917         };
918         Funclet::new(ret.expect("LLVM does not have support for catchpad"))
919     }
920
921     fn catch_switch(
922         &mut self,
923         parent: Option<&'ll Value>,
924         unwind: Option<&'ll BasicBlock>,
925         num_handlers: usize,
926     ) -> &'ll Value {
927         let name = const_cstr!("catchswitch");
928         let ret = unsafe {
929             llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
930                                            num_handlers as c_uint,
931                                            name.as_ptr())
932         };
933         ret.expect("LLVM does not have support for catchswitch")
934     }
935
936     fn add_handler(&mut self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
937         unsafe {
938             llvm::LLVMRustAddHandler(catch_switch, handler);
939         }
940     }
941
942     fn set_personality_fn(&mut self, personality: &'ll Value) {
943         unsafe {
944             llvm::LLVMSetPersonalityFn(self.llfn(), personality);
945         }
946     }
947
948     // Atomic Operations
949     fn atomic_cmpxchg(
950         &mut self,
951         dst: &'ll Value,
952         cmp: &'ll Value,
953         src: &'ll Value,
954         order: rustc_codegen_ssa::common::AtomicOrdering,
955         failure_order: rustc_codegen_ssa::common::AtomicOrdering,
956         weak: bool,
957     ) -> &'ll Value {
958         let weak = if weak { llvm::True } else { llvm::False };
959         unsafe {
960             llvm::LLVMRustBuildAtomicCmpXchg(
961                 self.llbuilder,
962                 dst,
963                 cmp,
964                 src,
965                 AtomicOrdering::from_generic(order),
966                 AtomicOrdering::from_generic(failure_order),
967                 weak
968             )
969         }
970     }
971     fn atomic_rmw(
972         &mut self,
973         op: rustc_codegen_ssa::common::AtomicRmwBinOp,
974         dst: &'ll Value,
975         src: &'ll Value,
976         order: rustc_codegen_ssa::common::AtomicOrdering,
977     ) -> &'ll Value {
978         unsafe {
979             llvm::LLVMBuildAtomicRMW(
980                 self.llbuilder,
981                 AtomicRmwBinOp::from_generic(op),
982                 dst,
983                 src,
984                 AtomicOrdering::from_generic(order),
985                 False)
986         }
987     }
988
989     fn atomic_fence(
990         &mut self,
991         order: rustc_codegen_ssa::common::AtomicOrdering,
992         scope: rustc_codegen_ssa::common::SynchronizationScope
993     ) {
994         unsafe {
995             llvm::LLVMRustBuildAtomicFence(
996                 self.llbuilder,
997                 AtomicOrdering::from_generic(order),
998                 SynchronizationScope::from_generic(scope)
999             );
1000         }
1001     }
1002
1003     fn set_invariant_load(&mut self, load: &'ll Value) {
1004         unsafe {
1005             llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1006                                   llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1007         }
1008     }
1009
1010     fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1011         self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1012     }
1013
1014     fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1015         self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1016     }
1017
1018     fn call(
1019         &mut self,
1020         llfn: &'ll Value,
1021         args: &[&'ll Value],
1022         funclet: Option<&Funclet<'ll>>,
1023     ) -> &'ll Value {
1024
1025         debug!("call {:?} with args ({:?})",
1026                llfn,
1027                args);
1028
1029         let args = self.check_call("call", llfn, args);
1030         let bundle = funclet.map(|funclet| funclet.bundle());
1031         let bundle = bundle.as_ref().map(|b| &*b.raw);
1032
1033         unsafe {
1034             llvm::LLVMRustBuildCall(
1035                 self.llbuilder,
1036                 llfn,
1037                 args.as_ptr() as *const &llvm::Value,
1038                 args.len() as c_uint,
1039                 bundle, UNNAMED
1040             )
1041         }
1042     }
1043
1044     fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1045         unsafe {
1046             llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED)
1047         }
1048     }
1049
1050
1051     fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
1052         self.cx
1053     }
1054
1055     unsafe fn delete_basic_block(&mut self, bb: &'ll BasicBlock) {
1056         llvm::LLVMDeleteBasicBlock(bb);
1057     }
1058
1059     fn do_not_inline(&mut self, llret: &'ll Value) {
1060         llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
1061     }
1062 }
1063
1064 impl StaticBuilderMethods for Builder<'a, 'll, 'tcx> {
1065     fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1066         // Forward to the `get_static` method of `CodegenCx`
1067         self.cx().get_static(def_id)
1068     }
1069 }
1070
1071 impl Builder<'a, 'll, 'tcx> {
1072     pub fn llfn(&self) -> &'ll Value {
1073         unsafe {
1074             llvm::LLVMGetBasicBlockParent(self.llbb())
1075         }
1076     }
1077
1078     fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1079         unsafe {
1080             llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1081         }
1082     }
1083
1084     pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1085         unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1086     }
1087
1088     pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1089         unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1090     }
1091
1092     pub fn insert_element(
1093         &mut self, vec: &'ll Value,
1094         elt: &'ll Value,
1095         idx: &'ll Value,
1096     ) -> &'ll Value {
1097         unsafe {
1098             llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED)
1099         }
1100     }
1101
1102     pub fn shuffle_vector(
1103         &mut self,
1104         v1: &'ll Value,
1105         v2: &'ll Value,
1106         mask: &'ll Value,
1107     ) -> &'ll Value {
1108         unsafe {
1109             llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED)
1110         }
1111     }
1112
1113     pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1114         unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1115     }
1116     pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1117         unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1118     }
1119     pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1120         unsafe {
1121             let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1122             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1123             instr
1124         }
1125     }
1126     pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1127         unsafe {
1128             let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1129             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1130             instr
1131         }
1132     }
1133     pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1134         unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1135     }
1136     pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1137         unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1138     }
1139     pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1140         unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1141     }
1142     pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1143         unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1144     }
1145     pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1146         unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1147     }
1148     pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1149         unsafe { llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false) }
1150     }
1151     pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1152         unsafe { llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false) }
1153     }
1154     pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1155         unsafe {
1156             let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1157             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1158             instr
1159         }
1160     }
1161     pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1162         unsafe {
1163             let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1164             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1165             instr
1166         }
1167     }
1168     pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1169         unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1170     }
1171     pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1172         unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1173     }
1174
1175     pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1176         unsafe {
1177             llvm::LLVMAddClause(landing_pad, clause);
1178         }
1179     }
1180
1181     pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1182         let ret = unsafe {
1183             llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind)
1184         };
1185         ret.expect("LLVM does not have support for catchret")
1186     }
1187
1188     fn check_store(&mut self, val: &'ll Value, ptr: &'ll Value) -> &'ll Value {
1189         let dest_ptr_ty = self.cx.val_ty(ptr);
1190         let stored_ty = self.cx.val_ty(val);
1191         let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
1192
1193         assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1194
1195         if dest_ptr_ty == stored_ptr_ty {
1196             ptr
1197         } else {
1198             debug!("type mismatch in store. \
1199                     Expected {:?}, got {:?}; inserting bitcast",
1200                    dest_ptr_ty, stored_ptr_ty);
1201             self.bitcast(ptr, stored_ptr_ty)
1202         }
1203     }
1204
1205     fn check_call<'b>(&mut self,
1206                       typ: &str,
1207                       llfn: &'ll Value,
1208                       args: &'b [&'ll Value]) -> Cow<'b, [&'ll Value]> {
1209         let mut fn_ty = self.cx.val_ty(llfn);
1210         // Strip off pointers
1211         while self.cx.type_kind(fn_ty) == TypeKind::Pointer {
1212             fn_ty = self.cx.element_type(fn_ty);
1213         }
1214
1215         assert!(self.cx.type_kind(fn_ty) == TypeKind::Function,
1216                 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1217
1218         let param_tys = self.cx.func_params_types(fn_ty);
1219
1220         let all_args_match = param_tys.iter()
1221             .zip(args.iter().map(|&v| self.val_ty(v)))
1222             .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1223
1224         if all_args_match {
1225             return Cow::Borrowed(args);
1226         }
1227
1228         let casted_args: Vec<_> = param_tys.into_iter()
1229             .zip(args.iter())
1230             .enumerate()
1231             .map(|(i, (expected_ty, &actual_val))| {
1232                 let actual_ty = self.val_ty(actual_val);
1233                 if expected_ty != actual_ty {
1234                     debug!("type mismatch in function call of {:?}. \
1235                             Expected {:?} for param {}, got {:?}; injecting bitcast",
1236                            llfn, expected_ty, i, actual_ty);
1237                     self.bitcast(actual_val, expected_ty)
1238                 } else {
1239                     actual_val
1240                 }
1241             })
1242             .collect();
1243
1244         Cow::Owned(casted_args)
1245     }
1246
1247     pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1248         unsafe {
1249             llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED)
1250         }
1251     }
1252
1253     fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1254         if self.cx.sess().opts.optimize == config::OptLevel::No {
1255             return;
1256         }
1257
1258         let size = size.bytes();
1259         if size == 0 {
1260             return;
1261         }
1262
1263         let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1264
1265         let ptr = self.pointercast(ptr, self.cx.type_i8p());
1266         self.call(lifetime_intrinsic, &[self.cx.const_u64(size), ptr], None);
1267     }
1268
1269     fn phi(&mut self, ty: &'ll Type, vals: &[&'ll Value], bbs: &[&'ll BasicBlock]) -> &'ll Value {
1270         assert_eq!(vals.len(), bbs.len());
1271         let phi = unsafe {
1272             llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED)
1273         };
1274         unsafe {
1275             llvm::LLVMAddIncoming(phi, vals.as_ptr(),
1276                                   bbs.as_ptr(),
1277                                   vals.len() as c_uint);
1278             phi
1279         }
1280     }
1281
1282     fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1283         unsafe {
1284             llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1285         }
1286     }
1287 }