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