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;
22 use std::ops::{Deref, Range};
24 use std::iter::TrustedLen;
26 // All Builders must have an llfn associated with them
28 pub struct Builder<'a, 'll: 'a, 'tcx: 'll> {
29 pub llbuilder: &'ll mut llvm::Builder<'ll>,
30 pub cx: &'a CodegenCx<'ll, 'tcx>,
33 impl Drop for Builder<'a, 'll, 'tcx> {
36 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
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;
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;
54 type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
57 impl ty::layout::HasDataLayout for Builder<'_, '_, '_> {
58 fn data_layout(&self) -> &ty::layout::TargetDataLayout {
63 impl ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
64 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
69 impl ty::layout::LayoutOf for Builder<'_, '_, 'tcx> {
71 type TyLayout = TyLayout<'tcx>;
73 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
78 impl Deref for Builder<'_, 'll, 'tcx> {
79 type Target = CodegenCx<'ll, 'tcx>;
81 fn deref(&self) -> &Self::Target {
86 impl HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
87 type CodegenCx = CodegenCx<'ll, 'tcx>;
90 impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
92 cx: &'a CodegenCx<'ll, 'tcx>,
96 let mut bx = Builder::with_cx(cx);
98 let name = SmallCStr::new(name);
99 llvm::LLVMAppendBasicBlockInContext(
105 bx.position_at_end(llbb);
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)
120 fn build_sibling_block<'b>(&self, name: &'b str) -> Self {
121 Builder::new_block(self.cx, self.llfn(), name)
124 fn llbb(&self) -> &'ll BasicBlock {
126 llvm::LLVMGetInsertBlock(self.llbuilder)
130 fn position_at_end(&mut self, llbb: &'ll BasicBlock) {
132 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
136 fn ret_void(&mut self) {
137 self.count_insn("retvoid");
139 llvm::LLVMBuildRetVoid(self.llbuilder);
143 fn ret(&mut self, v: &'ll Value) {
144 self.count_insn("ret");
146 llvm::LLVMBuildRet(self.llbuilder, v);
150 fn br(&mut self, dest: &'ll BasicBlock) {
151 self.count_insn("br");
153 llvm::LLVMBuildBr(self.llbuilder, dest);
160 then_llbb: &'ll BasicBlock,
161 else_llbb: &'ll BasicBlock,
163 self.count_insn("condbr");
165 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
172 else_llbb: &'ll BasicBlock,
173 cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)> + TrustedLen,
175 let switch = unsafe {
176 llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint)
178 for (on_val, dest) in cases {
179 let on_val = self.const_uint_big(self.val_ty(v), on_val);
181 llvm::LLVMAddCase(switch, on_val, dest)
190 then: &'ll BasicBlock,
191 catch: &'ll BasicBlock,
192 funclet: Option<&Funclet<'ll>>,
194 self.count_insn("invoke");
196 debug!("Invoke {:?} with args ({:?})",
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);
205 llvm::LLVMRustBuildInvoke(self.llbuilder,
208 args.len() as c_uint,
216 fn unreachable(&mut self) {
217 self.count_insn("unreachable");
219 llvm::LLVMBuildUnreachable(self.llbuilder);
224 fn add(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
225 self.count_insn("add");
227 llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
231 fn fadd(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
232 self.count_insn("fadd");
234 llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
238 fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
239 self.count_insn("fadd");
241 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
242 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
247 fn sub(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
248 self.count_insn("sub");
250 llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
254 fn fsub(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
255 self.count_insn("fsub");
257 llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
261 fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
262 self.count_insn("fsub");
264 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
265 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
270 fn mul(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
271 self.count_insn("mul");
273 llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
277 fn fmul(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
278 self.count_insn("fmul");
280 llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
284 fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285 self.count_insn("fmul");
287 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
288 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
294 fn udiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
295 self.count_insn("udiv");
297 llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
301 fn exactudiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
302 self.count_insn("exactudiv");
304 llvm::LLVMBuildExactUDiv(self.llbuilder, lhs, rhs, noname())
308 fn sdiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
309 self.count_insn("sdiv");
311 llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
315 fn exactsdiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
316 self.count_insn("exactsdiv");
318 llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
322 fn fdiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
323 self.count_insn("fdiv");
325 llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
329 fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
330 self.count_insn("fdiv");
332 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
333 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
338 fn urem(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
339 self.count_insn("urem");
341 llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
345 fn srem(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
346 self.count_insn("srem");
348 llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
352 fn frem(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
353 self.count_insn("frem");
355 llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
359 fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
360 self.count_insn("frem");
362 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
363 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
368 fn shl(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
369 self.count_insn("shl");
371 llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
375 fn lshr(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
376 self.count_insn("lshr");
378 llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
382 fn ashr(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
383 self.count_insn("ashr");
385 llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
389 fn and(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
390 self.count_insn("and");
392 llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
396 fn or(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
397 self.count_insn("or");
399 llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
403 fn xor(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
404 self.count_insn("xor");
406 llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
410 fn neg(&mut self, v: &'ll Value) -> &'ll Value {
411 self.count_insn("neg");
413 llvm::LLVMBuildNeg(self.llbuilder, v, noname())
417 fn fneg(&mut self, v: &'ll Value) -> &'ll Value {
418 self.count_insn("fneg");
420 llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
424 fn not(&mut self, v: &'ll Value) -> &'ll Value {
425 self.count_insn("not");
427 llvm::LLVMBuildNot(self.llbuilder, v, noname())
437 ) -> (Self::Value, Self::Value) {
438 use syntax::ast::IntTy::*;
439 use syntax::ast::UintTy::*;
440 use rustc::ty::{Int, Uint};
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")
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",
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",
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",
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",
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",
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",
497 let intrinsic = self.get_intrinsic(&name);
498 let res = self.call(intrinsic, &[lhs, rhs], None);
500 self.extract_value(res, 0),
501 self.extract_value(res, 1),
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())
510 bx.dynamic_alloca(ty, name, align)
513 fn dynamic_alloca(&mut self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
514 self.count_insn("alloca");
516 let alloca = if name.is_empty() {
517 llvm::LLVMBuildAlloca(self.llbuilder, ty, noname())
519 let name = SmallCStr::new(name);
520 llvm::LLVMBuildAlloca(self.llbuilder, ty,
523 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
528 fn array_alloca(&mut self,
532 align: Align) -> &'ll Value {
533 self.count_insn("alloca");
535 let alloca = if name.is_empty() {
536 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, noname())
538 let name = SmallCStr::new(name);
539 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len,
542 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
547 fn load(&mut self, ptr: &'ll Value, align: Align) -> &'ll Value {
548 self.count_insn("load");
550 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
551 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
556 fn volatile_load(&mut self, ptr: &'ll Value) -> &'ll Value {
557 self.count_insn("load.volatile");
559 let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
560 llvm::LLVMSetVolatile(insn, llvm::True);
568 order: rustc_codegen_ssa::common::AtomicOrdering,
571 self.count_insn("load.atomic");
573 let load = llvm::LLVMRustBuildAtomicLoad(
577 AtomicOrdering::from_generic(order),
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);
587 place: PlaceRef<'tcx, &'ll Value>
588 ) -> OperandRef<'tcx, &'ll Value> {
589 debug!("PlaceRef::load: {:?}", place);
591 assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
593 if place.layout.is_zst() {
594 return OperandRef::new_zst(self, place.layout);
597 fn scalar_load_metadata<'a, 'll, 'tcx>(
598 bx: &mut Builder<'a, 'll, 'tcx>,
600 scalar: &layout::Scalar
602 let vr = scalar.valid_range.clone();
605 let range = scalar.valid_range_exclusive(bx);
606 if range.start != range.end {
607 bx.range_metadata(load, range);
610 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
611 bx.nonnull_metadata(load);
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;
622 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
623 if llvm::LLVMIsGlobalConstant(global) == llvm::True {
624 const_llval = llvm::LLVMGetInitializer(global);
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);
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);
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())
651 load(0, a, place.align),
652 load(1, b, place.align.restrict_for_offset(b_offset)),
655 OperandValue::Ref(place.llval, None, place.align)
658 OperandRef { val, layout: place.layout }
661 fn write_operand_repeatedly(
663 cg_elem: OperandRef<'tcx, &'ll Value>,
665 dest: PlaceRef<'tcx, &'ll Value>,
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;
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");
676 self.br(header_bx.llbb());
677 let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
679 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
680 header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
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));
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());
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
703 let llty = self.cx.val_ty(load);
705 self.cx.const_uint_big(llty, range.start),
706 self.cx.const_uint_big(llty, range.end)
709 llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
710 llvm::LLVMMDNodeInContext(self.cx.llcx,
716 fn nonnull_metadata(&mut self, load: &'ll Value) {
718 llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
719 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
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())
734 debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
735 self.count_insn("store");
736 let ptr = self.check_store(val, ptr);
738 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
739 let align = if flags.contains(MemFlags::UNALIGNED) {
742 align.bytes() as c_uint
744 llvm::LLVMSetAlignment(store, align);
745 if flags.contains(MemFlags::VOLATILE) {
746 llvm::LLVMSetVolatile(store, llvm::True);
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.
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);
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);
767 let store = llvm::LLVMRustBuildAtomicStore(
771 AtomicOrdering::from_generic(order),
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);
778 fn gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
779 self.count_insn("gep");
781 llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
782 indices.len() as c_uint, noname())
786 fn inbounds_gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
787 self.count_insn("inboundsgep");
789 llvm::LLVMBuildInBoundsGEP(
790 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
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);
798 llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
803 fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
804 self.count_insn("trunc");
806 llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, noname())
810 fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
811 self.count_insn("sext");
813 llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, noname())
817 fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
818 self.count_insn("fptoui");
820 llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, noname())
824 fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
825 self.count_insn("fptosi");
827 llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty,noname())
831 fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
832 self.count_insn("uitofp");
834 llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, noname())
838 fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
839 self.count_insn("sitofp");
841 llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, noname())
845 fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
846 self.count_insn("fptrunc");
848 llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, noname())
852 fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
853 self.count_insn("fpext");
855 llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, noname())
859 fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
860 self.count_insn("ptrtoint");
862 llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, noname())
866 fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
867 self.count_insn("inttoptr");
869 llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, noname())
873 fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
874 self.count_insn("bitcast");
876 llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, noname())
881 fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
882 self.count_insn("intcast");
884 llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed)
888 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
889 self.count_insn("pointercast");
891 llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, noname())
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);
900 llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
904 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
905 self.count_insn("fcmp");
907 llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
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);
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());
927 llvm::LLVMRustBuildMemCpy(self.llbuilder, dst, dst_align.bytes() as c_uint,
928 src, src_align.bytes() as c_uint, size, is_volatile);
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);
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());
947 llvm::LLVMRustBuildMemMove(self.llbuilder, dst, dst_align.bytes() as c_uint,
948 src, src_align.bytes() as c_uint, size, is_volatile);
955 fill_byte: &'ll Value,
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);
970 &mut self, cond: &'ll Value,
971 then_val: &'ll Value,
972 else_val: &'ll Value,
974 self.count_insn("select");
976 llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
981 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
982 self.count_insn("vaarg");
984 llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
988 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
989 self.count_insn("extractelement");
991 llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
995 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
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))
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);
1009 llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
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);
1018 llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
1023 fn landing_pad(&mut self, ty: &'ll Type, pers_fn: &'ll Value,
1024 num_clauses: usize) -> &'ll Value {
1025 self.count_insn("landingpad");
1027 llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn,
1028 num_clauses as c_uint, noname())
1032 fn set_cleanup(&mut self, landing_pad: &'ll Value) {
1033 self.count_insn("setcleanup");
1035 llvm::LLVMSetCleanup(landing_pad, llvm::True);
1039 fn resume(&mut self, exn: &'ll Value) -> &'ll Value {
1040 self.count_insn("resume");
1042 llvm::LLVMBuildResume(self.llbuilder, exn)
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");
1052 llvm::LLVMRustBuildCleanupPad(self.llbuilder,
1054 args.len() as c_uint,
1058 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1062 &mut self, funclet: &Funclet<'ll>,
1063 unwind: Option<&'ll BasicBlock>,
1065 self.count_insn("cleanupret");
1067 llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1069 ret.expect("LLVM does not have support for cleanupret")
1072 fn catch_pad(&mut self,
1074 args: &[&'ll Value]) -> Funclet<'ll> {
1075 self.count_insn("catchpad");
1076 let name = const_cstr!("catchpad");
1078 llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1079 args.len() as c_uint, args.as_ptr(),
1082 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1087 parent: Option<&'ll Value>,
1088 unwind: Option<&'ll BasicBlock>,
1089 num_handlers: usize,
1091 self.count_insn("catchswitch");
1092 let name = const_cstr!("catchswitch");
1094 llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1095 num_handlers as c_uint,
1098 ret.expect("LLVM does not have support for catchswitch")
1101 fn add_handler(&mut self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1103 llvm::LLVMRustAddHandler(catch_switch, handler);
1107 fn set_personality_fn(&mut self, personality: &'ll Value) {
1109 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1113 // Atomic Operations
1119 order: rustc_codegen_ssa::common::AtomicOrdering,
1120 failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1123 let weak = if weak { llvm::True } else { llvm::False };
1125 llvm::LLVMRustBuildAtomicCmpXchg(
1130 AtomicOrdering::from_generic(order),
1131 AtomicOrdering::from_generic(failure_order),
1138 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1141 order: rustc_codegen_ssa::common::AtomicOrdering,
1144 llvm::LLVMBuildAtomicRMW(
1146 AtomicRmwBinOp::from_generic(op),
1149 AtomicOrdering::from_generic(order),
1156 order: rustc_codegen_ssa::common::AtomicOrdering,
1157 scope: rustc_codegen_ssa::common::SynchronizationScope
1160 llvm::LLVMRustBuildAtomicFence(
1162 AtomicOrdering::from_generic(order),
1163 SynchronizationScope::from_generic(scope)
1168 fn set_invariant_load(&mut self, load: &'ll Value) {
1170 llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1171 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1175 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1176 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1179 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1180 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1186 args: &[&'ll Value],
1187 funclet: Option<&Funclet<'ll>>,
1189 self.count_insn("call");
1191 debug!("Call {:?} with args ({:?})",
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);
1200 llvm::LLVMRustBuildCall(
1203 args.as_ptr() as *const &llvm::Value,
1204 args.len() as c_uint,
1210 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1211 self.count_insn("zext");
1213 llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, noname())
1218 fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
1222 unsafe fn delete_basic_block(&mut self, bb: &'ll BasicBlock) {
1223 llvm::LLVMDeleteBasicBlock(bb);
1226 fn do_not_inline(&mut self, llret: &'ll Value) {
1227 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
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)
1237 fn static_panic_msg(
1239 msg: Option<LocalInternedString>,
1240 filename: LocalInternedString,
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);
1249 let filename = self.const_str_slice(filename);
1251 let with_msg_components;
1252 let without_msg_components;
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 &[_]
1259 without_msg_components = [filename, line, col];
1260 &without_msg_components as &[_]
1263 let struct_ = self.const_struct(&components, false);
1264 self.static_addr_of(struct_, align, Some(kind))
1268 impl Builder<'a, 'll, 'tcx> {
1269 pub fn llfn(&self) -> &'ll Value {
1271 llvm::LLVMGetBasicBlockParent(self.llbb())
1275 fn count_insn(&self, category: &str) {
1276 if self.sess().codegen_stats() {
1277 self.stats.borrow_mut().n_llvm_insns += 1;
1279 if self.sess().count_llvm_insns() {
1283 .entry(category.to_string())
1288 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1290 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
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) }
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) }
1304 pub fn insert_element(
1305 &mut self, vec: &'ll Value,
1309 self.count_insn("insertelement");
1311 llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
1315 pub fn shuffle_vector(
1321 self.count_insn("shufflevector");
1323 llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
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");
1330 // FIXME: add a non-fast math version once
1331 // https://bugs.llvm.org/show_bug.cgi?id=36732
1333 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1334 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
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");
1341 // FIXME: add a non-fast math version once
1342 // https://bugs.llvm.org/show_bug.cgi?id=36732
1344 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1345 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
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) }
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) }
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) }
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) }
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) }
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) }
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) }
1377 pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1378 self.count_insn("vector.reduce.fmin_fast");
1380 let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1381 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1385 pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1386 self.count_insn("vector.reduce.fmax_fast");
1388 let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1389 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
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) }
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) }
1402 pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1404 llvm::LLVMAddClause(landing_pad, clause);
1408 pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1409 self.count_insn("catchret");
1411 llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind)
1413 ret.expect("LLVM does not have support for catchret")
1416 fn check_store<'b>(&mut self,
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);
1423 assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1425 if dest_ptr_ty == stored_ptr_ty {
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)
1435 fn check_call<'b>(&mut self,
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);
1445 assert!(self.cx.type_kind(fn_ty) == TypeKind::Function,
1446 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1448 let param_tys = self.cx.func_params_types(fn_ty);
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);
1455 return Cow::Borrowed(args);
1458 let casted_args: Vec<_> = param_tys.into_iter()
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)
1474 Cow::Owned(casted_args)
1477 pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1478 self.count_insn("vaarg");
1480 llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
1484 fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1485 if self.cx.sess().opts.optimize == config::OptLevel::No {
1489 let size = size.bytes();
1494 let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1496 let ptr = self.pointercast(ptr, self.cx.type_i8p());
1497 self.call(lifetime_intrinsic, &[self.cx.const_u64(size), ptr], None);
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());
1504 llvm::LLVMBuildPhi(self.llbuilder, ty, noname())
1507 llvm::LLVMAddIncoming(phi, vals.as_ptr(),
1509 vals.len() as c_uint);
1514 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1515 self.count_insn("addincoming");
1517 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);