1 use crate::common::Funclet;
2 use crate::context::CodegenCx;
3 use crate::llvm::{self, BasicBlock, False};
4 use crate::llvm::{AtomicOrdering, AtomicRmwBinOp, SynchronizationScope};
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
9 use libc::{c_char, c_uint};
10 use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, TypeKind};
11 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
12 use rustc_codegen_ssa::mir::place::PlaceRef;
13 use rustc_codegen_ssa::traits::*;
14 use rustc_codegen_ssa::MemFlags;
15 use rustc_data_structures::small_c_str::SmallCStr;
16 use rustc_hir::def_id::DefId;
17 use rustc_middle::ty::layout::TyAndLayout;
18 use rustc_middle::ty::{self, Ty, TyCtxt};
19 use rustc_span::{sym, Span};
20 use rustc_target::abi::{self, Align, Size};
21 use rustc_target::spec::{HasTargetSpec, Target};
25 use std::ops::{Deref, Range};
29 // All Builders must have an llfn associated with them
31 pub struct Builder<'a, 'll, 'tcx> {
32 pub llbuilder: &'ll mut llvm::Builder<'ll>,
33 pub cx: &'a CodegenCx<'ll, 'tcx>,
36 impl Drop for Builder<'a, 'll, 'tcx> {
39 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
44 // FIXME(eddyb) use a checked constructor when they become `const fn`.
45 const EMPTY_C_STR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"\0") };
47 /// Empty string, to be used where LLVM expects an instruction name, indicating
48 /// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
49 // FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
50 const UNNAMED: *const c_char = EMPTY_C_STR.as_ptr();
52 impl BackendTypes for Builder<'_, 'll, 'tcx> {
53 type Value = <CodegenCx<'ll, 'tcx> as BackendTypes>::Value;
54 type Function = <CodegenCx<'ll, 'tcx> as BackendTypes>::Function;
55 type BasicBlock = <CodegenCx<'ll, 'tcx> as BackendTypes>::BasicBlock;
56 type Type = <CodegenCx<'ll, 'tcx> as BackendTypes>::Type;
57 type Funclet = <CodegenCx<'ll, 'tcx> as BackendTypes>::Funclet;
59 type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
60 type DILocation = <CodegenCx<'ll, 'tcx> as BackendTypes>::DILocation;
61 type DIVariable = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIVariable;
64 impl abi::HasDataLayout for Builder<'_, '_, '_> {
65 fn data_layout(&self) -> &abi::TargetDataLayout {
70 impl ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
71 fn tcx(&self) -> TyCtxt<'tcx> {
76 impl ty::layout::HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
77 fn param_env(&self) -> ty::ParamEnv<'tcx> {
82 impl HasTargetSpec for Builder<'_, '_, 'tcx> {
83 fn target_spec(&self) -> &Target {
84 &self.cx.target_spec()
88 impl abi::LayoutOf for Builder<'_, '_, 'tcx> {
90 type TyAndLayout = TyAndLayout<'tcx>;
92 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
97 impl Deref for Builder<'_, 'll, 'tcx> {
98 type Target = CodegenCx<'ll, 'tcx>;
100 fn deref(&self) -> &Self::Target {
105 impl HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
106 type CodegenCx = CodegenCx<'ll, 'tcx>;
109 macro_rules! builder_methods_for_value_instructions {
110 ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
111 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
113 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
119 impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
120 fn new_block<'b>(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &'b str) -> Self {
121 let mut bx = Builder::with_cx(cx);
123 let name = SmallCStr::new(name);
124 llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
126 bx.position_at_end(llbb);
130 fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
131 // Create a fresh builder from the crate context.
132 let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(cx.llcx) };
133 Builder { llbuilder, cx }
136 fn build_sibling_block(&self, name: &str) -> Self {
137 Builder::new_block(self.cx, self.llfn(), name)
140 fn llbb(&self) -> &'ll BasicBlock {
141 unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
144 fn set_span(&mut self, _span: Span) {}
146 fn position_at_end(&mut self, llbb: &'ll BasicBlock) {
148 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
152 fn ret_void(&mut self) {
154 llvm::LLVMBuildRetVoid(self.llbuilder);
158 fn ret(&mut self, v: &'ll Value) {
160 llvm::LLVMBuildRet(self.llbuilder, v);
164 fn br(&mut self, dest: &'ll BasicBlock) {
166 llvm::LLVMBuildBr(self.llbuilder, dest);
173 then_llbb: &'ll BasicBlock,
174 else_llbb: &'ll BasicBlock,
177 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
184 else_llbb: &'ll BasicBlock,
185 cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
188 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
189 for (on_val, dest) in cases {
190 let on_val = self.const_uint_big(self.val_ty(v), on_val);
191 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
199 then: &'ll BasicBlock,
200 catch: &'ll BasicBlock,
201 funclet: Option<&Funclet<'ll>>,
203 debug!("invoke {:?} with args ({:?})", llfn, args);
205 let args = self.check_call("invoke", llfn, args);
206 let bundle = funclet.map(|funclet| funclet.bundle());
207 let bundle = bundle.as_ref().map(|b| &*b.raw);
210 llvm::LLVMRustBuildInvoke(
214 args.len() as c_uint,
223 fn unreachable(&mut self) {
225 llvm::LLVMBuildUnreachable(self.llbuilder);
229 builder_methods_for_value_instructions! {
230 add(a, b) => LLVMBuildAdd,
231 fadd(a, b) => LLVMBuildFAdd,
232 sub(a, b) => LLVMBuildSub,
233 fsub(a, b) => LLVMBuildFSub,
234 mul(a, b) => LLVMBuildMul,
235 fmul(a, b) => LLVMBuildFMul,
236 udiv(a, b) => LLVMBuildUDiv,
237 exactudiv(a, b) => LLVMBuildExactUDiv,
238 sdiv(a, b) => LLVMBuildSDiv,
239 exactsdiv(a, b) => LLVMBuildExactSDiv,
240 fdiv(a, b) => LLVMBuildFDiv,
241 urem(a, b) => LLVMBuildURem,
242 srem(a, b) => LLVMBuildSRem,
243 frem(a, b) => LLVMBuildFRem,
244 shl(a, b) => LLVMBuildShl,
245 lshr(a, b) => LLVMBuildLShr,
246 ashr(a, b) => LLVMBuildAShr,
247 and(a, b) => LLVMBuildAnd,
248 or(a, b) => LLVMBuildOr,
249 xor(a, b) => LLVMBuildXor,
250 neg(x) => LLVMBuildNeg,
251 fneg(x) => LLVMBuildFNeg,
252 not(x) => LLVMBuildNot,
253 unchecked_sadd(x, y) => LLVMBuildNSWAdd,
254 unchecked_uadd(x, y) => LLVMBuildNUWAdd,
255 unchecked_ssub(x, y) => LLVMBuildNSWSub,
256 unchecked_usub(x, y) => LLVMBuildNUWSub,
257 unchecked_smul(x, y) => LLVMBuildNSWMul,
258 unchecked_umul(x, y) => LLVMBuildNUWMul,
261 fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
263 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED);
264 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
269 fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
271 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED);
272 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
277 fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
279 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED);
280 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
285 fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
287 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED);
288 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
293 fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
295 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED);
296 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
307 ) -> (Self::Value, Self::Value) {
308 use rustc_middle::ty::{Int, Uint};
309 use rustc_middle::ty::{IntTy::*, UintTy::*};
311 let new_kind = match ty.kind() {
312 Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.pointer_width)),
313 Uint(t @ Usize) => Uint(t.normalize(self.tcx.sess.target.pointer_width)),
314 t @ (Uint(_) | Int(_)) => t.clone(),
315 _ => panic!("tried to get overflow intrinsic for op applied to non-int type"),
318 let name = match oop {
319 OverflowOp::Add => match new_kind {
320 Int(I8) => "llvm.sadd.with.overflow.i8",
321 Int(I16) => "llvm.sadd.with.overflow.i16",
322 Int(I32) => "llvm.sadd.with.overflow.i32",
323 Int(I64) => "llvm.sadd.with.overflow.i64",
324 Int(I128) => "llvm.sadd.with.overflow.i128",
326 Uint(U8) => "llvm.uadd.with.overflow.i8",
327 Uint(U16) => "llvm.uadd.with.overflow.i16",
328 Uint(U32) => "llvm.uadd.with.overflow.i32",
329 Uint(U64) => "llvm.uadd.with.overflow.i64",
330 Uint(U128) => "llvm.uadd.with.overflow.i128",
334 OverflowOp::Sub => match new_kind {
335 Int(I8) => "llvm.ssub.with.overflow.i8",
336 Int(I16) => "llvm.ssub.with.overflow.i16",
337 Int(I32) => "llvm.ssub.with.overflow.i32",
338 Int(I64) => "llvm.ssub.with.overflow.i64",
339 Int(I128) => "llvm.ssub.with.overflow.i128",
341 Uint(U8) => "llvm.usub.with.overflow.i8",
342 Uint(U16) => "llvm.usub.with.overflow.i16",
343 Uint(U32) => "llvm.usub.with.overflow.i32",
344 Uint(U64) => "llvm.usub.with.overflow.i64",
345 Uint(U128) => "llvm.usub.with.overflow.i128",
349 OverflowOp::Mul => match new_kind {
350 Int(I8) => "llvm.smul.with.overflow.i8",
351 Int(I16) => "llvm.smul.with.overflow.i16",
352 Int(I32) => "llvm.smul.with.overflow.i32",
353 Int(I64) => "llvm.smul.with.overflow.i64",
354 Int(I128) => "llvm.smul.with.overflow.i128",
356 Uint(U8) => "llvm.umul.with.overflow.i8",
357 Uint(U16) => "llvm.umul.with.overflow.i16",
358 Uint(U32) => "llvm.umul.with.overflow.i32",
359 Uint(U64) => "llvm.umul.with.overflow.i64",
360 Uint(U128) => "llvm.umul.with.overflow.i128",
366 let intrinsic = self.get_intrinsic(&name);
367 let res = self.call(intrinsic, &[lhs, rhs], None);
368 (self.extract_value(res, 0), self.extract_value(res, 1))
371 fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
372 if self.cx().val_ty(val) == self.cx().type_i1() {
373 self.zext(val, self.cx().type_i8())
378 fn to_immediate_scalar(&mut self, val: Self::Value, scalar: &abi::Scalar) -> Self::Value {
379 if scalar.is_bool() {
380 return self.trunc(val, self.cx().type_i1());
385 fn alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
386 let mut bx = Builder::with_cx(self.cx);
387 bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
388 bx.dynamic_alloca(ty, align)
391 fn dynamic_alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
393 let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
394 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
399 fn array_alloca(&mut self, ty: &'ll Type, len: &'ll Value, align: Align) -> &'ll Value {
401 let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, UNNAMED);
402 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
407 fn load(&mut self, ptr: &'ll Value, align: Align) -> &'ll Value {
409 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
410 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
415 fn volatile_load(&mut self, ptr: &'ll Value) -> &'ll Value {
417 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
418 llvm::LLVMSetVolatile(load, llvm::True);
426 order: rustc_codegen_ssa::common::AtomicOrdering,
430 let load = llvm::LLVMRustBuildAtomicLoad(
434 AtomicOrdering::from_generic(order),
436 // LLVM requires the alignment of atomic loads to be at least the size of the type.
437 llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
442 fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
443 debug!("PlaceRef::load: {:?}", place);
445 assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
447 if place.layout.is_zst() {
448 return OperandRef::new_zst(self, place.layout);
451 fn scalar_load_metadata<'a, 'll, 'tcx>(
452 bx: &mut Builder<'a, 'll, 'tcx>,
454 scalar: &abi::Scalar,
456 let vr = scalar.valid_range.clone();
459 let range = scalar.valid_range_exclusive(bx);
460 if range.start != range.end {
461 bx.range_metadata(load, range);
464 abi::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
465 bx.nonnull_metadata(load);
471 let val = if let Some(llextra) = place.llextra {
472 OperandValue::Ref(place.llval, Some(llextra), place.align)
473 } else if place.layout.is_llvm_immediate() {
474 let mut const_llval = None;
476 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
477 if llvm::LLVMIsGlobalConstant(global) == llvm::True {
478 const_llval = llvm::LLVMGetInitializer(global);
482 let llval = const_llval.unwrap_or_else(|| {
483 let load = self.load(place.llval, place.align);
484 if let abi::Abi::Scalar(ref scalar) = place.layout.abi {
485 scalar_load_metadata(self, load, scalar);
489 OperandValue::Immediate(self.to_immediate(llval, place.layout))
490 } else if let abi::Abi::ScalarPair(ref a, ref b) = place.layout.abi {
491 let b_offset = a.value.size(self).align_to(b.value.align(self).abi);
493 let mut load = |i, scalar: &abi::Scalar, align| {
494 let llptr = self.struct_gep(place.llval, i as u64);
495 let load = self.load(llptr, align);
496 scalar_load_metadata(self, load, scalar);
497 self.to_immediate_scalar(load, scalar)
501 load(0, a, place.align),
502 load(1, b, place.align.restrict_for_offset(b_offset)),
505 OperandValue::Ref(place.llval, None, place.align)
508 OperandRef { val, layout: place.layout }
511 fn write_operand_repeatedly(
513 cg_elem: OperandRef<'tcx, &'ll Value>,
515 dest: PlaceRef<'tcx, &'ll Value>,
517 let zero = self.const_usize(0);
518 let count = self.const_usize(count);
519 let start = dest.project_index(&mut self, zero).llval;
520 let end = dest.project_index(&mut self, count).llval;
522 let mut header_bx = self.build_sibling_block("repeat_loop_header");
523 let mut body_bx = self.build_sibling_block("repeat_loop_body");
524 let next_bx = self.build_sibling_block("repeat_loop_next");
526 self.br(header_bx.llbb());
527 let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
529 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
530 header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
532 let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
535 .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
537 let next = body_bx.inbounds_gep(current, &[self.const_usize(1)]);
538 body_bx.br(header_bx.llbb());
539 header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
544 fn range_metadata(&mut self, load: &'ll Value, range: Range<u128>) {
545 if self.sess().target.arch == "amdgpu" {
546 // amdgpu/LLVM does something weird and thinks a i64 value is
547 // split into a v2i32, halving the bitwidth LLVM expects,
548 // tripping an assertion. So, for now, just disable this
554 let llty = self.cx.val_ty(load);
556 self.cx.const_uint_big(llty, range.start),
557 self.cx.const_uint_big(llty, range.end),
560 llvm::LLVMSetMetadata(
562 llvm::MD_range as c_uint,
563 llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint),
568 fn nonnull_metadata(&mut self, load: &'ll Value) {
570 llvm::LLVMSetMetadata(
572 llvm::MD_nonnull as c_uint,
573 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
578 fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
579 self.store_with_flags(val, ptr, align, MemFlags::empty())
589 debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
590 let ptr = self.check_store(val, ptr);
592 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
594 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
595 llvm::LLVMSetAlignment(store, align);
596 if flags.contains(MemFlags::VOLATILE) {
597 llvm::LLVMSetVolatile(store, llvm::True);
599 if flags.contains(MemFlags::NONTEMPORAL) {
600 // According to LLVM [1] building a nontemporal store must
601 // *always* point to a metadata value of the integer 1.
603 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
604 let one = self.cx.const_i32(1);
605 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
606 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
616 order: rustc_codegen_ssa::common::AtomicOrdering,
619 debug!("Store {:?} -> {:?}", val, ptr);
620 let ptr = self.check_store(val, ptr);
622 let store = llvm::LLVMRustBuildAtomicStore(
626 AtomicOrdering::from_generic(order),
628 // LLVM requires the alignment of atomic stores to be at least the size of the type.
629 llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
633 fn gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
639 indices.len() as c_uint,
645 fn inbounds_gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
647 llvm::LLVMBuildInBoundsGEP(
651 indices.len() as c_uint,
657 fn struct_gep(&mut self, ptr: &'ll Value, idx: u64) -> &'ll Value {
658 assert_eq!(idx as c_uint as u64, idx);
659 unsafe { llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, UNNAMED) }
663 fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
664 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
667 fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
668 unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
671 fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
672 // WebAssembly has saturating floating point to integer casts if the
673 // `nontrapping-fptoint` target feature is activated. We'll use those if
674 // they are available.
675 if self.sess().target.arch == "wasm32"
676 && self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
678 let src_ty = self.cx.val_ty(val);
679 let float_width = self.cx.float_width(src_ty);
680 let int_width = self.cx.int_width(dest_ty);
681 let name = match (int_width, float_width) {
682 (32, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f32"),
683 (32, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f64"),
684 (64, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f32"),
685 (64, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f64"),
688 if let Some(name) = name {
689 let intrinsic = self.get_intrinsic(name);
690 return Some(self.call(intrinsic, &[val], None));
696 fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
697 // WebAssembly has saturating floating point to integer casts if the
698 // `nontrapping-fptoint` target feature is activated. We'll use those if
699 // they are available.
700 if self.sess().target.arch == "wasm32"
701 && self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
703 let src_ty = self.cx.val_ty(val);
704 let float_width = self.cx.float_width(src_ty);
705 let int_width = self.cx.int_width(dest_ty);
706 let name = match (int_width, float_width) {
707 (32, 32) => Some("llvm.wasm.trunc.saturate.signed.i32.f32"),
708 (32, 64) => Some("llvm.wasm.trunc.saturate.signed.i32.f64"),
709 (64, 32) => Some("llvm.wasm.trunc.saturate.signed.i64.f32"),
710 (64, 64) => Some("llvm.wasm.trunc.saturate.signed.i64.f64"),
713 if let Some(name) = name {
714 let intrinsic = self.get_intrinsic(name);
715 return Some(self.call(intrinsic, &[val], None));
721 fn fptosui_may_trap(&self, val: &'ll Value, dest_ty: &'ll Type) -> bool {
722 // Most of the time we'll be generating the `fptosi` or `fptoui`
723 // instruction for floating-point-to-integer conversions. These
724 // instructions by definition in LLVM do not trap. For the WebAssembly
725 // target, however, we'll lower in some cases to intrinsic calls instead
726 // which may trap. If we detect that this is a situation where we'll be
727 // using the intrinsics then we report that the call map trap, which
728 // callers might need to handle.
729 if !self.wasm_and_missing_nontrapping_fptoint() {
732 let src_ty = self.cx.val_ty(val);
733 let float_width = self.cx.float_width(src_ty);
734 let int_width = self.cx.int_width(dest_ty);
735 matches!((int_width, float_width), (32, 32) | (32, 64) | (64, 32) | (64, 64))
738 fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
739 // When we can, use the native wasm intrinsics which have tighter
740 // codegen. Note that this has a semantic difference in that the
741 // intrinsic can trap whereas `fptoui` never traps. That difference,
742 // however, is handled by `fptosui_may_trap` above.
744 // Note that we skip the wasm intrinsics for vector types where `fptoui`
745 // must be used instead.
746 if self.wasm_and_missing_nontrapping_fptoint() {
747 let src_ty = self.cx.val_ty(val);
748 if self.cx.type_kind(src_ty) != TypeKind::Vector {
749 let float_width = self.cx.float_width(src_ty);
750 let int_width = self.cx.int_width(dest_ty);
751 let name = match (int_width, float_width) {
752 (32, 32) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
753 (32, 64) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
754 (64, 32) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
755 (64, 64) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
758 if let Some(name) = name {
759 let intrinsic = self.get_intrinsic(name);
760 return self.call(intrinsic, &[val], None);
764 unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
767 fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
768 if self.wasm_and_missing_nontrapping_fptoint() {
769 let src_ty = self.cx.val_ty(val);
770 if self.cx.type_kind(src_ty) != TypeKind::Vector {
771 let float_width = self.cx.float_width(src_ty);
772 let int_width = self.cx.int_width(dest_ty);
773 let name = match (int_width, float_width) {
774 (32, 32) => Some("llvm.wasm.trunc.signed.i32.f32"),
775 (32, 64) => Some("llvm.wasm.trunc.signed.i32.f64"),
776 (64, 32) => Some("llvm.wasm.trunc.signed.i64.f32"),
777 (64, 64) => Some("llvm.wasm.trunc.signed.i64.f64"),
780 if let Some(name) = name {
781 let intrinsic = self.get_intrinsic(name);
782 return self.call(intrinsic, &[val], None);
786 unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
789 fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
790 unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
793 fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
794 unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
797 fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
798 unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
801 fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
802 unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
805 fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
806 unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
809 fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
810 unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
813 fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
814 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
817 fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
818 unsafe { llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed) }
821 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
822 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
826 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
827 let op = llvm::IntPredicate::from_generic(op);
828 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
831 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
832 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
835 /* Miscellaneous instructions */
845 if flags.contains(MemFlags::NONTEMPORAL) {
846 // HACK(nox): This is inefficient but there is no nontemporal memcpy.
847 let val = self.load(src, src_align);
848 let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
849 self.store_with_flags(val, ptr, dst_align, flags);
852 let size = self.intcast(size, self.type_isize(), false);
853 let is_volatile = flags.contains(MemFlags::VOLATILE);
854 let dst = self.pointercast(dst, self.type_i8p());
855 let src = self.pointercast(src, self.type_i8p());
857 llvm::LLVMRustBuildMemCpy(
860 dst_align.bytes() as c_uint,
862 src_align.bytes() as c_uint,
878 if flags.contains(MemFlags::NONTEMPORAL) {
879 // HACK(nox): This is inefficient but there is no nontemporal memmove.
880 let val = self.load(src, src_align);
881 let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
882 self.store_with_flags(val, ptr, dst_align, flags);
885 let size = self.intcast(size, self.type_isize(), false);
886 let is_volatile = flags.contains(MemFlags::VOLATILE);
887 let dst = self.pointercast(dst, self.type_i8p());
888 let src = self.pointercast(src, self.type_i8p());
890 llvm::LLVMRustBuildMemMove(
893 dst_align.bytes() as c_uint,
895 src_align.bytes() as c_uint,
905 fill_byte: &'ll Value,
910 let is_volatile = flags.contains(MemFlags::VOLATILE);
911 let ptr = self.pointercast(ptr, self.type_i8p());
913 llvm::LLVMRustBuildMemSet(
916 align.bytes() as c_uint,
927 then_val: &'ll Value,
928 else_val: &'ll Value,
930 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
933 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
934 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
937 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
938 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
941 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
943 let elt_ty = self.cx.val_ty(elt);
944 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
945 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
946 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
947 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
951 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
952 assert_eq!(idx as c_uint as u64, idx);
953 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
956 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
957 assert_eq!(idx as c_uint as u64, idx);
958 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
968 llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn, num_clauses as c_uint, UNNAMED)
972 fn set_cleanup(&mut self, landing_pad: &'ll Value) {
974 llvm::LLVMSetCleanup(landing_pad, llvm::True);
978 fn resume(&mut self, exn: &'ll Value) -> &'ll Value {
979 unsafe { llvm::LLVMBuildResume(self.llbuilder, exn) }
982 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
983 let name = cstr!("cleanuppad");
985 llvm::LLVMRustBuildCleanupPad(
988 args.len() as c_uint,
993 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
998 funclet: &Funclet<'ll>,
999 unwind: Option<&'ll BasicBlock>,
1002 unsafe { llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1003 ret.expect("LLVM does not have support for cleanupret")
1006 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1007 let name = cstr!("catchpad");
1009 llvm::LLVMRustBuildCatchPad(
1012 args.len() as c_uint,
1017 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1022 parent: Option<&'ll Value>,
1023 unwind: Option<&'ll BasicBlock>,
1024 num_handlers: usize,
1026 let name = cstr!("catchswitch");
1028 llvm::LLVMRustBuildCatchSwitch(
1032 num_handlers as c_uint,
1036 ret.expect("LLVM does not have support for catchswitch")
1039 fn add_handler(&mut self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1041 llvm::LLVMRustAddHandler(catch_switch, handler);
1045 fn set_personality_fn(&mut self, personality: &'ll Value) {
1047 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1051 // Atomic Operations
1057 order: rustc_codegen_ssa::common::AtomicOrdering,
1058 failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1061 let weak = if weak { llvm::True } else { llvm::False };
1063 llvm::LLVMRustBuildAtomicCmpXchg(
1068 AtomicOrdering::from_generic(order),
1069 AtomicOrdering::from_generic(failure_order),
1076 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1079 order: rustc_codegen_ssa::common::AtomicOrdering,
1082 llvm::LLVMBuildAtomicRMW(
1084 AtomicRmwBinOp::from_generic(op),
1087 AtomicOrdering::from_generic(order),
1095 order: rustc_codegen_ssa::common::AtomicOrdering,
1096 scope: rustc_codegen_ssa::common::SynchronizationScope,
1099 llvm::LLVMRustBuildAtomicFence(
1101 AtomicOrdering::from_generic(order),
1102 SynchronizationScope::from_generic(scope),
1107 fn set_invariant_load(&mut self, load: &'ll Value) {
1109 llvm::LLVMSetMetadata(
1111 llvm::MD_invariant_load as c_uint,
1112 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
1117 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1118 self.call_lifetime_intrinsic("llvm.lifetime.start.p0i8", ptr, size);
1121 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1122 self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size);
1125 fn instrprof_increment(
1127 fn_name: &'ll Value,
1129 num_counters: &'ll Value,
1133 "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})",
1134 fn_name, hash, num_counters, index
1137 let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) };
1138 let args = &[fn_name, hash, num_counters, index];
1139 let args = self.check_call("call", llfn, args);
1142 let _ = llvm::LLVMRustBuildCall(
1145 args.as_ptr() as *const &llvm::Value,
1146 args.len() as c_uint,
1155 args: &[&'ll Value],
1156 funclet: Option<&Funclet<'ll>>,
1158 debug!("call {:?} with args ({:?})", llfn, args);
1160 let args = self.check_call("call", llfn, args);
1161 let bundle = funclet.map(|funclet| funclet.bundle());
1162 let bundle = bundle.as_ref().map(|b| &*b.raw);
1165 llvm::LLVMRustBuildCall(
1168 args.as_ptr() as *const &llvm::Value,
1169 args.len() as c_uint,
1175 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1176 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1179 fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
1183 unsafe fn delete_basic_block(&mut self, bb: &'ll BasicBlock) {
1184 llvm::LLVMDeleteBasicBlock(bb);
1187 fn do_not_inline(&mut self, llret: &'ll Value) {
1188 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
1192 impl StaticBuilderMethods for Builder<'a, 'll, 'tcx> {
1193 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1194 // Forward to the `get_static` method of `CodegenCx`
1195 self.cx().get_static(def_id)
1199 impl Builder<'a, 'll, 'tcx> {
1200 pub fn llfn(&self) -> &'ll Value {
1201 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1204 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1206 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1210 pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1211 unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1214 pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1215 unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1218 pub fn insert_element(
1224 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1227 pub fn shuffle_vector(
1233 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1236 pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1237 unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1239 pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1240 unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1242 pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1244 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1245 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1249 pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1251 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1252 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1256 pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1257 unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1259 pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1260 unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1262 pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1263 unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1265 pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1266 unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1268 pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1269 unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1271 pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1273 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
1276 pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1278 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
1281 pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1284 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1285 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1289 pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1292 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1293 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1297 pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1298 unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1300 pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1301 unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1304 pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1306 llvm::LLVMAddClause(landing_pad, clause);
1310 pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1312 unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1313 ret.expect("LLVM does not have support for catchret")
1316 fn check_store(&mut self, val: &'ll Value, ptr: &'ll Value) -> &'ll Value {
1317 let dest_ptr_ty = self.cx.val_ty(ptr);
1318 let stored_ty = self.cx.val_ty(val);
1319 let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
1321 assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1323 if dest_ptr_ty == stored_ptr_ty {
1327 "type mismatch in store. \
1328 Expected {:?}, got {:?}; inserting bitcast",
1329 dest_ptr_ty, stored_ptr_ty
1331 self.bitcast(ptr, stored_ptr_ty)
1339 args: &'b [&'ll Value],
1340 ) -> Cow<'b, [&'ll Value]> {
1341 let mut fn_ty = self.cx.val_ty(llfn);
1342 // Strip off pointers
1343 while self.cx.type_kind(fn_ty) == TypeKind::Pointer {
1344 fn_ty = self.cx.element_type(fn_ty);
1348 self.cx.type_kind(fn_ty) == TypeKind::Function,
1349 "builder::{} not passed a function, but {:?}",
1354 let param_tys = self.cx.func_params_types(fn_ty);
1356 let all_args_match = iter::zip(¶m_tys, args.iter().map(|&v| self.val_ty(v)))
1357 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1360 return Cow::Borrowed(args);
1363 let casted_args: Vec<_> = iter::zip(param_tys, args)
1365 .map(|(i, (expected_ty, &actual_val))| {
1366 let actual_ty = self.val_ty(actual_val);
1367 if expected_ty != actual_ty {
1369 "type mismatch in function call of {:?}. \
1370 Expected {:?} for param {}, got {:?}; injecting bitcast",
1371 llfn, expected_ty, i, actual_ty
1373 self.bitcast(actual_val, expected_ty)
1380 Cow::Owned(casted_args)
1383 pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1384 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1387 fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1388 let size = size.bytes();
1393 if !self.cx().sess().emit_lifetime_markers() {
1397 let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1399 let ptr = self.pointercast(ptr, self.cx.type_i8p());
1400 self.call(lifetime_intrinsic, &[self.cx.const_u64(size), ptr], None);
1406 vals: &[&'ll Value],
1407 bbs: &[&'ll BasicBlock],
1409 assert_eq!(vals.len(), bbs.len());
1410 let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1412 llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1417 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1419 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1423 fn wasm_and_missing_nontrapping_fptoint(&self) -> bool {
1424 self.sess().target.arch == "wasm32"
1425 && !self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)