1 use crate::abi::{Abi, FnAbi, LlvmType, PassMode};
2 use crate::builder::Builder;
3 use crate::context::CodegenCx;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::va_arg::emit_va_arg;
8 use crate::value::Value;
11 use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh};
12 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
13 use rustc_codegen_ssa::common::TypeKind;
14 use rustc_codegen_ssa::glue;
15 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
16 use rustc_codegen_ssa::mir::place::PlaceRef;
17 use rustc_codegen_ssa::traits::*;
18 use rustc_codegen_ssa::MemFlags;
20 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
21 use rustc_middle::ty::{self, Ty};
22 use rustc_middle::{bug, span_bug};
24 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
25 use rustc_target::spec::PanicStrategy;
27 use std::cmp::Ordering;
30 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
31 let llvm_name = match name {
32 "sqrtf32" => "llvm.sqrt.f32",
33 "sqrtf64" => "llvm.sqrt.f64",
34 "powif32" => "llvm.powi.f32",
35 "powif64" => "llvm.powi.f64",
36 "sinf32" => "llvm.sin.f32",
37 "sinf64" => "llvm.sin.f64",
38 "cosf32" => "llvm.cos.f32",
39 "cosf64" => "llvm.cos.f64",
40 "powf32" => "llvm.pow.f32",
41 "powf64" => "llvm.pow.f64",
42 "expf32" => "llvm.exp.f32",
43 "expf64" => "llvm.exp.f64",
44 "exp2f32" => "llvm.exp2.f32",
45 "exp2f64" => "llvm.exp2.f64",
46 "logf32" => "llvm.log.f32",
47 "logf64" => "llvm.log.f64",
48 "log10f32" => "llvm.log10.f32",
49 "log10f64" => "llvm.log10.f64",
50 "log2f32" => "llvm.log2.f32",
51 "log2f64" => "llvm.log2.f64",
52 "fmaf32" => "llvm.fma.f32",
53 "fmaf64" => "llvm.fma.f64",
54 "fabsf32" => "llvm.fabs.f32",
55 "fabsf64" => "llvm.fabs.f64",
56 "minnumf32" => "llvm.minnum.f32",
57 "minnumf64" => "llvm.minnum.f64",
58 "maxnumf32" => "llvm.maxnum.f32",
59 "maxnumf64" => "llvm.maxnum.f64",
60 "copysignf32" => "llvm.copysign.f32",
61 "copysignf64" => "llvm.copysign.f64",
62 "floorf32" => "llvm.floor.f32",
63 "floorf64" => "llvm.floor.f64",
64 "ceilf32" => "llvm.ceil.f32",
65 "ceilf64" => "llvm.ceil.f64",
66 "truncf32" => "llvm.trunc.f32",
67 "truncf64" => "llvm.trunc.f64",
68 "rintf32" => "llvm.rint.f32",
69 "rintf64" => "llvm.rint.f64",
70 "nearbyintf32" => "llvm.nearbyint.f32",
71 "nearbyintf64" => "llvm.nearbyint.f64",
72 "roundf32" => "llvm.round.f32",
73 "roundf64" => "llvm.round.f64",
74 "assume" => "llvm.assume",
75 "abort" => "llvm.trap",
78 Some(cx.get_intrinsic(&llvm_name))
81 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
82 fn codegen_intrinsic_call(
84 instance: ty::Instance<'tcx>,
85 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
86 args: &[OperandRef<'tcx, &'ll Value>],
91 let callee_ty = instance.monomorphic_ty(tcx);
93 let (def_id, substs) = match callee_ty.kind {
94 ty::FnDef(def_id, substs) => (def_id, substs),
95 _ => bug!("expected fn item type, found {}", callee_ty),
98 let sig = callee_ty.fn_sig(tcx);
99 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
100 let arg_tys = sig.inputs();
101 let ret_ty = sig.output();
102 let name = &*tcx.item_name(def_id).as_str();
104 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
105 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
107 let simple = get_simple_intrinsic(self, name);
108 let llval = match name {
109 _ if simple.is_some() => self.call(
111 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
118 let expect = self.get_intrinsic(&("llvm.expect.i1"));
119 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
122 let expect = self.get_intrinsic(&("llvm.expect.i1"));
123 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
136 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
137 self.call(llfn, &[], None)
139 "va_start" => self.va_start(args[0].immediate()),
140 "va_end" => self.va_end(args[0].immediate()),
142 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
143 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
146 match fn_abi.ret.layout.abi {
147 abi::Abi::Scalar(ref scalar) => {
149 Primitive::Int(..) => {
150 if self.cx().size_of(ret_ty).bytes() < 4 {
151 // `va_arg` should not be called on a integer type
152 // less than 4 bytes in length. If it is, promote
153 // the integer to a `i32` and truncate the result
154 // back to the smaller type.
155 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
156 self.trunc(promoted_result, llret_ty)
158 emit_va_arg(self, args[0], ret_ty)
161 Primitive::F64 | Primitive::Pointer => {
162 emit_va_arg(self, args[0], ret_ty)
164 // `va_arg` should never be used with the return type f32.
165 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
168 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
172 let tp_ty = substs.type_at(0);
173 if let OperandValue::Pair(_, meta) = args[0].val {
174 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
177 self.const_usize(self.size_of(tp_ty).bytes())
180 "min_align_of_val" => {
181 let tp_ty = substs.type_at(0);
182 if let OperandValue::Pair(_, meta) = args[0].val {
183 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
186 self.const_usize(self.align_of(tp_ty).bytes())
189 "size_of" | "pref_align_of" | "min_align_of" | "needs_drop" | "type_id"
193 .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
195 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
202 let ptr = args[0].immediate();
203 let offset = args[1].immediate();
204 self.inbounds_gep(ptr, &[offset])
207 let ptr = args[0].immediate();
208 let offset = args[1].immediate();
209 self.gep(ptr, &[offset])
212 "copy_nonoverlapping" => {
248 "volatile_copy_nonoverlapping_memory" => {
260 "volatile_copy_memory" => {
272 "volatile_set_memory" => {
283 "volatile_load" | "unaligned_volatile_load" => {
284 let tp_ty = substs.type_at(0);
285 let mut ptr = args[0].immediate();
286 if let PassMode::Cast(ty) = fn_abi.ret.mode {
287 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
289 let load = self.volatile_load(ptr);
290 let align = if name == "unaligned_volatile_load" {
293 self.align_of(tp_ty).bytes() as u32
296 llvm::LLVMSetAlignment(load, align);
298 to_immediate(self, load, self.layout_of(tp_ty))
300 "volatile_store" => {
301 let dst = args[0].deref(self.cx());
302 args[1].val.volatile_store(self, dst);
305 "unaligned_volatile_store" => {
306 let dst = args[0].deref(self.cx());
307 args[1].val.unaligned_volatile_store(self, dst);
311 | "prefetch_write_data"
312 | "prefetch_read_instruction"
313 | "prefetch_write_instruction" => {
314 let expect = self.get_intrinsic(&("llvm.prefetch"));
315 let (rw, cache_type) = match name {
316 "prefetch_read_data" => (0, 1),
317 "prefetch_write_data" => (1, 1),
318 "prefetch_read_instruction" => (0, 0),
319 "prefetch_write_instruction" => (1, 0),
328 self.const_i32(cache_type),
333 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap"
334 | "bitreverse" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow"
335 | "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "unchecked_div"
336 | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "unchecked_add"
337 | "unchecked_sub" | "unchecked_mul" | "exact_div" | "rotate_left" | "rotate_right"
338 | "saturating_add" | "saturating_sub" => {
340 match int_type_width_signed(ty, self) {
341 Some((width, signed)) => match name {
343 let y = self.const_bool(false);
344 let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
345 self.call(llfn, &[args[0].immediate(), y], None)
347 "ctlz_nonzero" | "cttz_nonzero" => {
348 let y = self.const_bool(true);
349 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
350 let llfn = self.get_intrinsic(llvm_name);
351 self.call(llfn, &[args[0].immediate(), y], None)
353 "ctpop" => self.call(
354 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
355 &[args[0].immediate()],
360 args[0].immediate() // byte swap a u8/i8 is just a no-op
363 self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
364 &[args[0].immediate()],
369 "bitreverse" => self.call(
370 self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
371 &[args[0].immediate()],
374 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
375 let intrinsic = format!(
376 "llvm.{}{}.with.overflow.i{}",
377 if signed { 's' } else { 'u' },
381 let llfn = self.get_intrinsic(&intrinsic);
383 // Convert `i1` to a `bool`, and write it to the out parameter
385 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
386 let val = self.extract_value(pair, 0);
387 let overflow = self.extract_value(pair, 1);
388 let overflow = self.zext(overflow, self.type_bool());
390 let dest = result.project_field(self, 0);
391 self.store(val, dest.llval, dest.align);
392 let dest = result.project_field(self, 1);
393 self.store(overflow, dest.llval, dest.align);
397 "wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
398 "wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
399 "wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
402 self.exactsdiv(args[0].immediate(), args[1].immediate())
404 self.exactudiv(args[0].immediate(), args[1].immediate())
409 self.sdiv(args[0].immediate(), args[1].immediate())
411 self.udiv(args[0].immediate(), args[1].immediate())
416 self.srem(args[0].immediate(), args[1].immediate())
418 self.urem(args[0].immediate(), args[1].immediate())
421 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
424 self.ashr(args[0].immediate(), args[1].immediate())
426 self.lshr(args[0].immediate(), args[1].immediate())
431 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
433 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
438 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
440 self.unchecked_usub(args[0].immediate(), args[1].immediate())
445 self.unchecked_smul(args[0].immediate(), args[1].immediate())
447 self.unchecked_umul(args[0].immediate(), args[1].immediate())
450 "rotate_left" | "rotate_right" => {
451 let is_left = name == "rotate_left";
452 let val = args[0].immediate();
453 let raw_shift = args[1].immediate();
454 // rotate = funnel shift with first two args the same
456 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
457 let llfn = self.get_intrinsic(llvm_name);
458 self.call(llfn, &[val, val, raw_shift], None)
460 "saturating_add" | "saturating_sub" => {
461 let is_add = name == "saturating_add";
462 let lhs = args[0].immediate();
463 let rhs = args[1].immediate();
464 let llvm_name = &format!(
466 if signed { 's' } else { 'u' },
467 if is_add { "add" } else { "sub" },
470 let llfn = self.get_intrinsic(llvm_name);
471 self.call(llfn, &[lhs, rhs], None)
476 span_invalid_monomorphization_error(
480 "invalid monomorphization of `{}` intrinsic: \
481 expected basic integer type, found `{}`",
489 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
490 match float_type_width(arg_tys[0]) {
491 Some(_width) => match name {
492 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
493 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
494 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
495 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
496 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
500 span_invalid_monomorphization_error(
504 "invalid monomorphization of `{}` intrinsic: \
505 expected basic float type, found `{}`",
514 "float_to_int_unchecked" => {
515 if float_type_width(arg_tys[0]).is_none() {
516 span_invalid_monomorphization_error(
520 "invalid monomorphization of `float_to_int_unchecked` \
521 intrinsic: expected basic float type, \
528 match int_type_width_signed(ret_ty, self.cx) {
529 Some((width, signed)) => {
531 self.fptosi(args[0].immediate(), self.cx.type_ix(width))
533 self.fptoui(args[0].immediate(), self.cx.type_ix(width))
537 span_invalid_monomorphization_error(
541 "invalid monomorphization of `float_to_int_unchecked` \
542 intrinsic: expected basic integer type, \
552 "discriminant_value" => {
553 if ret_ty.is_integral() {
554 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
556 span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
560 name if name.starts_with("simd_") => {
561 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
566 // This requires that atomic intrinsics follow a specific naming pattern:
567 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
568 name if name.starts_with("atomic_") => {
569 use rustc_codegen_ssa::common::AtomicOrdering::*;
570 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
572 let split: Vec<&str> = name.split('_').collect();
574 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
575 let (order, failorder) = match split.len() {
576 2 => (SequentiallyConsistent, SequentiallyConsistent),
577 3 => match split[2] {
578 "unordered" => (Unordered, Unordered),
579 "relaxed" => (Monotonic, Monotonic),
580 "acq" => (Acquire, Acquire),
581 "rel" => (Release, Monotonic),
582 "acqrel" => (AcquireRelease, Acquire),
583 "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
584 "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
585 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
587 4 => match (split[2], split[3]) {
588 ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
589 ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
590 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
592 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
595 let invalid_monomorphization = |ty| {
596 span_invalid_monomorphization_error(
600 "invalid monomorphization of `{}` intrinsic: \
601 expected basic integer type, found `{}`",
608 "cxchg" | "cxchgweak" => {
609 let ty = substs.type_at(0);
610 if int_type_width_signed(ty, self).is_some() {
611 let weak = split[1] == "cxchgweak";
612 let pair = self.atomic_cmpxchg(
620 let val = self.extract_value(pair, 0);
621 let success = self.extract_value(pair, 1);
622 let success = self.zext(success, self.type_bool());
624 let dest = result.project_field(self, 0);
625 self.store(val, dest.llval, dest.align);
626 let dest = result.project_field(self, 1);
627 self.store(success, dest.llval, dest.align);
630 return invalid_monomorphization(ty);
635 let ty = substs.type_at(0);
636 if int_type_width_signed(ty, self).is_some() {
637 let size = self.size_of(ty);
638 self.atomic_load(args[0].immediate(), order, size)
640 return invalid_monomorphization(ty);
645 let ty = substs.type_at(0);
646 if int_type_width_signed(ty, self).is_some() {
647 let size = self.size_of(ty);
656 return invalid_monomorphization(ty);
661 self.atomic_fence(order, SynchronizationScope::CrossThread);
665 "singlethreadfence" => {
666 self.atomic_fence(order, SynchronizationScope::SingleThread);
670 // These are all AtomicRMW ops
672 let atom_op = match op {
673 "xchg" => AtomicRmwBinOp::AtomicXchg,
674 "xadd" => AtomicRmwBinOp::AtomicAdd,
675 "xsub" => AtomicRmwBinOp::AtomicSub,
676 "and" => AtomicRmwBinOp::AtomicAnd,
677 "nand" => AtomicRmwBinOp::AtomicNand,
678 "or" => AtomicRmwBinOp::AtomicOr,
679 "xor" => AtomicRmwBinOp::AtomicXor,
680 "max" => AtomicRmwBinOp::AtomicMax,
681 "min" => AtomicRmwBinOp::AtomicMin,
682 "umax" => AtomicRmwBinOp::AtomicUMax,
683 "umin" => AtomicRmwBinOp::AtomicUMin,
684 _ => self.sess().fatal("unknown atomic operation"),
687 let ty = substs.type_at(0);
688 if int_type_width_signed(ty, self).is_some() {
696 return invalid_monomorphization(ty);
702 "nontemporal_store" => {
703 let dst = args[0].deref(self.cx());
704 args[1].val.nontemporal_store(self, dst);
708 "ptr_offset_from" => {
709 let ty = substs.type_at(0);
710 let pointee_size = self.size_of(ty);
712 // This is the same sequence that Clang emits for pointer subtraction.
713 // It can be neither `nsw` nor `nuw` because the input is treated as
714 // unsigned but then the output is treated as signed, so neither works.
715 let a = args[0].immediate();
716 let b = args[1].immediate();
717 let a = self.ptrtoint(a, self.type_isize());
718 let b = self.ptrtoint(b, self.type_isize());
719 let d = self.sub(a, b);
720 let pointee_size = self.const_usize(pointee_size.bytes());
721 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
722 self.exactsdiv(d, pointee_size)
725 _ => bug!("unknown intrinsic '{}'", name),
728 if !fn_abi.ret.is_ignore() {
729 if let PassMode::Cast(ty) = fn_abi.ret.mode {
730 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
731 let ptr = self.pointercast(result.llval, ptr_llty);
732 self.store(llval, ptr, result.align);
734 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
736 .store(self, result);
741 fn abort(&mut self) {
742 let fnname = self.get_intrinsic(&("llvm.trap"));
743 self.call(fnname, &[], None);
746 fn assume(&mut self, val: Self::Value) {
747 let assume_intrinsic = self.get_intrinsic("llvm.assume");
748 self.call(assume_intrinsic, &[val], None);
751 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
752 let expect = self.get_intrinsic(&"llvm.expect.i1");
753 self.call(expect, &[cond, self.const_bool(expected)], None)
756 fn sideeffect(&mut self) {
757 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
758 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
759 self.call(fnname, &[], None);
763 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
764 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
765 self.call(intrinsic, &[va_list], None)
768 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
769 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
770 self.call(intrinsic, &[va_list], None)
775 bx: &mut Builder<'a, 'll, 'tcx>,
783 let (size, align) = bx.size_and_align_of(ty);
784 let size = bx.mul(bx.const_usize(size.bytes()), count);
785 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
787 bx.memmove(dst, align, src, align, size, flags);
789 bx.memcpy(dst, align, src, align, size, flags);
794 bx: &mut Builder<'a, 'll, 'tcx>,
801 let (size, align) = bx.size_and_align_of(ty);
802 let size = bx.mul(bx.const_usize(size.bytes()), count);
803 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
804 bx.memset(dst, val, size, align, flags);
808 bx: &mut Builder<'a, 'll, 'tcx>,
809 try_func: &'ll Value,
811 catch_func: &'ll Value,
814 if bx.sess().panic_strategy() == PanicStrategy::Abort {
815 bx.call(try_func, &[data], None);
816 // Return 0 unconditionally from the intrinsic call;
817 // we can never unwind.
818 let ret_align = bx.tcx().data_layout.i32_align.abi;
819 bx.store(bx.const_i32(0), dest, ret_align);
820 } else if wants_msvc_seh(bx.sess()) {
821 codegen_msvc_try(bx, try_func, data, catch_func, dest);
823 codegen_gnu_try(bx, try_func, data, catch_func, dest);
827 // MSVC's definition of the `rust_try` function.
829 // This implementation uses the new exception handling instructions in LLVM
830 // which have support in LLVM for SEH on MSVC targets. Although these
831 // instructions are meant to work for all targets, as of the time of this
832 // writing, however, LLVM does not recommend the usage of these new instructions
833 // as the old ones are still more optimized.
835 bx: &mut Builder<'a, 'll, 'tcx>,
836 try_func: &'ll Value,
838 catch_func: &'ll Value,
841 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
842 bx.set_personality_fn(bx.eh_personality());
845 let mut normal = bx.build_sibling_block("normal");
846 let mut catchswitch = bx.build_sibling_block("catchswitch");
847 let mut catchpad = bx.build_sibling_block("catchpad");
848 let mut caught = bx.build_sibling_block("caught");
850 let try_func = llvm::get_param(bx.llfn(), 0);
851 let data = llvm::get_param(bx.llfn(), 1);
852 let catch_func = llvm::get_param(bx.llfn(), 2);
854 // We're generating an IR snippet that looks like:
856 // declare i32 @rust_try(%try_func, %data, %catch_func) {
857 // %slot = alloca u8*
858 // invoke %try_func(%data) to label %normal unwind label %catchswitch
864 // %cs = catchswitch within none [%catchpad] unwind to caller
867 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
869 // call %catch_func(%data, %ptr)
870 // catchret from %tok to label %caught
876 // This structure follows the basic usage of throw/try/catch in LLVM.
877 // For example, compile this C++ snippet to see what LLVM generates:
879 // #include <stdint.h>
881 // struct rust_panic {
882 // rust_panic(const rust_panic&);
889 // void (*try_func)(void*),
891 // void (*catch_func)(void*, void*) noexcept
896 // } catch(rust_panic& a) {
897 // catch_func(data, &a);
902 // More information can be found in libstd's seh.rs implementation.
903 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
904 let slot = bx.alloca(bx.type_i8p(), ptr_align);
905 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
907 normal.ret(bx.const_i32(0));
909 let cs = catchswitch.catch_switch(None, None, 1);
910 catchswitch.add_handler(cs, catchpad.llbb());
912 // We can't use the TypeDescriptor defined in libpanic_unwind because it
913 // might be in another DLL and the SEH encoding only supports specifying
914 // a TypeDescriptor from the current module.
916 // However this isn't an issue since the MSVC runtime uses string
917 // comparison on the type name to match TypeDescriptors rather than
920 // So instead we generate a new TypeDescriptor in each module that uses
921 // `try` and let the linker merge duplicate definitions in the same
924 // When modifying, make sure that the type_name string exactly matches
925 // the one used in src/libpanic_unwind/seh.rs.
926 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
927 let type_name = bx.const_bytes(b"rust_panic\0");
929 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
930 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
932 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
933 llvm::SetUniqueComdat(bx.llmod, tydesc);
934 llvm::LLVMSetInitializer(tydesc, type_info);
937 // The flag value of 8 indicates that we are catching the exception by
938 // reference instead of by value. We can't use catch by value because
939 // that requires copying the exception object, which we don't support
940 // since our exception object effectively contains a Box.
942 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
943 let flags = bx.const_i32(8);
944 let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
945 let ptr = catchpad.load(slot, ptr_align);
946 catchpad.call(catch_func, &[data, ptr], Some(&funclet));
948 catchpad.catch_ret(&funclet, caught.llbb());
950 caught.ret(bx.const_i32(1));
953 // Note that no invoke is used here because by definition this function
954 // can't panic (that's what it's catching).
955 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
956 let i32_align = bx.tcx().data_layout.i32_align.abi;
957 bx.store(ret, dest, i32_align);
960 // Definition of the standard `try` function for Rust using the GNU-like model
961 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
964 // This codegen is a little surprising because we always call a shim
965 // function instead of inlining the call to `invoke` manually here. This is done
966 // because in LLVM we're only allowed to have one personality per function
967 // definition. The call to the `try` intrinsic is being inlined into the
968 // function calling it, and that function may already have other personality
969 // functions in play. By calling a shim we're guaranteed that our shim will have
970 // the right personality function.
972 bx: &mut Builder<'a, 'll, 'tcx>,
973 try_func: &'ll Value,
975 catch_func: &'ll Value,
978 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
979 // Codegens the shims described above:
982 // invoke %try_func(%data) normal %normal unwind %catch
988 // (%ptr, _) = landingpad
989 // call %catch_func(%data, %ptr)
994 let mut then = bx.build_sibling_block("then");
995 let mut catch = bx.build_sibling_block("catch");
997 let try_func = llvm::get_param(bx.llfn(), 0);
998 let data = llvm::get_param(bx.llfn(), 1);
999 let catch_func = llvm::get_param(bx.llfn(), 2);
1000 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1001 then.ret(bx.const_i32(0));
1003 // Type indicator for the exception being thrown.
1005 // The first value in this tuple is a pointer to the exception object
1006 // being thrown. The second value is a "selector" indicating which of
1007 // the landing pad clauses the exception's type had been matched to.
1008 // rust_try ignores the selector.
1009 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1010 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1011 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1013 let tydesc = bx.get_static(tydesc);
1014 bx.bitcast(tydesc, bx.type_i8p())
1016 None => bx.const_null(bx.type_i8p()),
1018 catch.add_clause(vals, tydesc);
1019 let ptr = catch.extract_value(vals, 0);
1020 catch.call(catch_func, &[data, ptr], None);
1021 catch.ret(bx.const_i32(1));
1024 // Note that no invoke is used here because by definition this function
1025 // can't panic (that's what it's catching).
1026 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1027 let i32_align = bx.tcx().data_layout.i32_align.abi;
1028 bx.store(ret, dest, i32_align);
1031 // Helper function to give a Block to a closure to codegen a shim function.
1032 // This is currently primarily used for the `try` intrinsic functions above.
1033 fn gen_fn<'ll, 'tcx>(
1034 cx: &CodegenCx<'ll, 'tcx>,
1036 inputs: Vec<Ty<'tcx>>,
1038 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1040 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1044 hir::Unsafety::Unsafe,
1047 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1048 let llfn = cx.declare_fn(name, &fn_abi);
1049 cx.set_frame_pointer_elimination(llfn);
1050 cx.apply_target_cpu_attr(llfn);
1051 // FIXME(eddyb) find a nicer way to do this.
1052 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1053 let bx = Builder::new_block(cx, llfn, "entry-block");
1058 // Helper function used to get a handle to the `__rust_try` function used to
1059 // catch exceptions.
1061 // This function is only generated once and is then cached.
1062 fn get_rust_try_fn<'ll, 'tcx>(
1063 cx: &CodegenCx<'ll, 'tcx>,
1064 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1066 if let Some(llfn) = cx.rust_try_fn.get() {
1070 // Define the type up front for the signature of the rust_try function.
1072 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1073 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1077 hir::Unsafety::Unsafe,
1080 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1081 [i8p, i8p].iter().cloned(),
1084 hir::Unsafety::Unsafe,
1087 let output = tcx.types.i32;
1088 let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1089 cx.rust_try_fn.set(Some(rust_try));
1093 fn generic_simd_intrinsic(
1094 bx: &mut Builder<'a, 'll, 'tcx>,
1096 callee_ty: Ty<'tcx>,
1097 args: &[OperandRef<'tcx, &'ll Value>],
1099 llret_ty: &'ll Type,
1101 ) -> Result<&'ll Value, ()> {
1102 // macros for error handling:
1103 macro_rules! emit_error {
1107 ($msg: tt, $($fmt: tt)*) => {
1108 span_invalid_monomorphization_error(
1110 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1115 macro_rules! return_error {
1118 emit_error!($($fmt)*);
1124 macro_rules! require {
1125 ($cond: expr, $($fmt: tt)*) => {
1127 return_error!($($fmt)*);
1132 macro_rules! require_simd {
1133 ($ty: expr, $position: expr) => {
1134 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1140 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1141 let arg_tys = sig.inputs();
1143 if name == "simd_select_bitmask" {
1144 let in_ty = arg_tys[0];
1145 let m_len = match in_ty.kind {
1146 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1147 // of intentional as there's not currently a use case for that.
1148 ty::Int(i) => i.bit_width().unwrap(),
1149 ty::Uint(i) => i.bit_width().unwrap(),
1150 _ => return_error!("`{}` is not an integral type", in_ty),
1152 require_simd!(arg_tys[1], "argument");
1153 let v_len = arg_tys[1].simd_size(tcx);
1156 "mismatched lengths: mask length `{}` != other vector length `{}`",
1160 let i1 = bx.type_i1();
1161 let i1xn = bx.type_vector(i1, m_len);
1162 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1163 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1166 // every intrinsic below takes a SIMD vector as its first argument
1167 require_simd!(arg_tys[0], "input");
1168 let in_ty = arg_tys[0];
1169 let in_elem = arg_tys[0].simd_type(tcx);
1170 let in_len = arg_tys[0].simd_size(tcx);
1172 let comparison = match name {
1173 "simd_eq" => Some(hir::BinOpKind::Eq),
1174 "simd_ne" => Some(hir::BinOpKind::Ne),
1175 "simd_lt" => Some(hir::BinOpKind::Lt),
1176 "simd_le" => Some(hir::BinOpKind::Le),
1177 "simd_gt" => Some(hir::BinOpKind::Gt),
1178 "simd_ge" => Some(hir::BinOpKind::Ge),
1182 if let Some(cmp_op) = comparison {
1183 require_simd!(ret_ty, "return");
1185 let out_len = ret_ty.simd_size(tcx);
1188 "expected return type with length {} (same as input type `{}`), \
1189 found `{}` with length {}",
1196 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1197 "expected return type with integer elements, found `{}` with non-integer `{}`",
1199 ret_ty.simd_type(tcx)
1202 return Ok(compare_simd_types(
1204 args[0].immediate(),
1205 args[1].immediate(),
1212 if name.starts_with("simd_shuffle") {
1213 let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1214 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1217 require_simd!(ret_ty, "return");
1219 let out_len = ret_ty.simd_size(tcx);
1222 "expected return type of length {}, found `{}` with length {}",
1228 in_elem == ret_ty.simd_type(tcx),
1229 "expected return element type `{}` (element of input `{}`), \
1230 found `{}` with element type `{}`",
1234 ret_ty.simd_type(tcx)
1237 let total_len = u128::from(in_len) * 2;
1239 let vector = args[2].immediate();
1241 let indices: Option<Vec<_>> = (0..n)
1244 let val = bx.const_get_elt(vector, i as u64);
1245 match bx.const_to_opt_u128(val, true) {
1247 emit_error!("shuffle index #{} is not a constant", arg_idx);
1250 Some(idx) if idx >= total_len => {
1252 "shuffle index #{} is out of bounds (limit {})",
1258 Some(idx) => Some(bx.const_i32(idx as i32)),
1262 let indices = match indices {
1264 None => return Ok(bx.const_null(llret_ty)),
1267 return Ok(bx.shuffle_vector(
1268 args[0].immediate(),
1269 args[1].immediate(),
1270 bx.const_vector(&indices),
1274 if name == "simd_insert" {
1276 in_elem == arg_tys[2],
1277 "expected inserted type `{}` (element of input `{}`), found `{}`",
1282 return Ok(bx.insert_element(
1283 args[0].immediate(),
1284 args[2].immediate(),
1285 args[1].immediate(),
1288 if name == "simd_extract" {
1291 "expected return type `{}` (element of input `{}`), found `{}`",
1296 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1299 if name == "simd_select" {
1300 let m_elem_ty = in_elem;
1302 require_simd!(arg_tys[1], "argument");
1303 let v_len = arg_tys[1].simd_size(tcx);
1306 "mismatched lengths: mask length `{}` != other vector length `{}`",
1310 match m_elem_ty.kind {
1312 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1314 // truncate the mask to a vector of i1s
1315 let i1 = bx.type_i1();
1316 let i1xn = bx.type_vector(i1, m_len as u64);
1317 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1318 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1321 if name == "simd_bitmask" {
1322 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1323 // vector mask and returns an unsigned integer containing the most
1324 // significant bit (MSB) of each lane.
1326 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1328 let expected_int_bits = in_len.max(8);
1330 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1331 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1334 // Integer vector <i{in_bitwidth} x in_len>:
1335 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1337 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1340 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1343 "vector argument `{}`'s element type `{}`, expected integer element type",
1349 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1352 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1355 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1356 // Truncate vector to an <i1 x N>
1357 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1358 // Bitcast <i1 x N> to iN:
1359 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1360 // Zero-extend iN to the bitmask type:
1361 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1364 fn simd_simple_float_intrinsic(
1366 in_elem: &::rustc_middle::ty::TyS<'_>,
1367 in_ty: &::rustc_middle::ty::TyS<'_>,
1369 bx: &mut Builder<'a, 'll, 'tcx>,
1371 args: &[OperandRef<'tcx, &'ll Value>],
1372 ) -> Result<&'ll Value, ()> {
1373 macro_rules! emit_error {
1377 ($msg: tt, $($fmt: tt)*) => {
1378 span_invalid_monomorphization_error(
1380 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1384 macro_rules! return_error {
1387 emit_error!($($fmt)*);
1392 let ety = match in_elem.kind {
1393 ty::Float(f) if f.bit_width() == 32 => {
1394 if in_len < 2 || in_len > 16 {
1396 "unsupported floating-point vector `{}` with length `{}` \
1397 out-of-range [2, 16]",
1404 ty::Float(f) if f.bit_width() == 64 => {
1405 if in_len < 2 || in_len > 8 {
1407 "unsupported floating-point vector `{}` with length `{}` \
1408 out-of-range [2, 8]",
1417 "unsupported element type `{}` of floating-point vector `{}`",
1423 return_error!("`{}` is not a floating-point type", in_ty);
1427 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1428 let intrinsic = bx.get_intrinsic(&llvm_name);
1430 bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1431 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1437 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1440 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1443 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1446 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1449 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1452 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1455 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1458 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1461 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1464 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1467 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1470 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1473 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1476 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1478 _ => { /* fallthrough */ }
1482 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1483 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1484 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1485 let p0s: String = "p0".repeat(no_pointers);
1486 match elem_ty.kind {
1487 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1488 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1489 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1490 _ => unreachable!(),
1495 cx: &CodegenCx<'ll, '_>,
1498 mut no_pointers: usize,
1500 // FIXME: use cx.layout_of(ty).llvm_type() ?
1501 let mut elem_ty = match elem_ty.kind {
1502 ty::Int(v) => cx.type_int_from_ty(v),
1503 ty::Uint(v) => cx.type_uint_from_ty(v),
1504 ty::Float(v) => cx.type_float_from_ty(v),
1505 _ => unreachable!(),
1507 while no_pointers > 0 {
1508 elem_ty = cx.type_ptr_to(elem_ty);
1511 cx.type_vector(elem_ty, vec_len)
1514 if name == "simd_gather" {
1515 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1516 // mask: <N x i{M}>) -> <N x T>
1517 // * N: number of elements in the input vectors
1518 // * T: type of the element to load
1519 // * M: any integer width is supported, will be truncated to i1
1521 // All types must be simd vector types
1522 require_simd!(in_ty, "first");
1523 require_simd!(arg_tys[1], "second");
1524 require_simd!(arg_tys[2], "third");
1525 require_simd!(ret_ty, "return");
1527 // Of the same length:
1529 in_len == arg_tys[1].simd_size(tcx),
1530 "expected {} argument with length {} (same as input type `{}`), \
1531 found `{}` with length {}",
1536 arg_tys[1].simd_size(tcx)
1539 in_len == arg_tys[2].simd_size(tcx),
1540 "expected {} argument with length {} (same as input type `{}`), \
1541 found `{}` with length {}",
1546 arg_tys[2].simd_size(tcx)
1549 // The return type must match the first argument type
1550 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1552 // This counts how many pointers
1553 fn ptr_count(t: Ty<'_>) -> usize {
1555 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1561 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1563 ty::RawPtr(p) => non_ptr(p.ty),
1568 // The second argument must be a simd vector with an element type that's a pointer
1569 // to the element type of the first argument
1570 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1571 ty::RawPtr(p) if p.ty == in_elem => {
1572 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1577 "expected element type `{}` of second argument `{}` \
1578 to be a pointer to the element type `{}` of the first \
1579 argument `{}`, found `{}` != `*_ {}`",
1580 arg_tys[1].simd_type(tcx),
1584 arg_tys[1].simd_type(tcx),
1590 assert!(pointer_count > 0);
1591 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1592 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1594 // The element type of the third argument must be a signed integer type of any width:
1595 match arg_tys[2].simd_type(tcx).kind {
1600 "expected element type `{}` of third argument `{}` \
1601 to be a signed integer type",
1602 arg_tys[2].simd_type(tcx),
1608 // Alignment of T, must be a constant integer value:
1609 let alignment_ty = bx.type_i32();
1610 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1612 // Truncate the mask vector to a vector of i1s:
1613 let (mask, mask_ty) = {
1614 let i1 = bx.type_i1();
1615 let i1xn = bx.type_vector(i1, in_len);
1616 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1619 // Type of the vector of pointers:
1620 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1621 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1623 // Type of the vector of elements:
1624 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1625 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1627 let llvm_intrinsic =
1628 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1629 let f = bx.declare_cfn(
1632 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1636 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1637 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1641 if name == "simd_scatter" {
1642 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1643 // mask: <N x i{M}>) -> ()
1644 // * N: number of elements in the input vectors
1645 // * T: type of the element to load
1646 // * M: any integer width is supported, will be truncated to i1
1648 // All types must be simd vector types
1649 require_simd!(in_ty, "first");
1650 require_simd!(arg_tys[1], "second");
1651 require_simd!(arg_tys[2], "third");
1653 // Of the same length:
1655 in_len == arg_tys[1].simd_size(tcx),
1656 "expected {} argument with length {} (same as input type `{}`), \
1657 found `{}` with length {}",
1662 arg_tys[1].simd_size(tcx)
1665 in_len == arg_tys[2].simd_size(tcx),
1666 "expected {} argument with length {} (same as input type `{}`), \
1667 found `{}` with length {}",
1672 arg_tys[2].simd_size(tcx)
1675 // This counts how many pointers
1676 fn ptr_count(t: Ty<'_>) -> usize {
1678 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1684 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1686 ty::RawPtr(p) => non_ptr(p.ty),
1691 // The second argument must be a simd vector with an element type that's a pointer
1692 // to the element type of the first argument
1693 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1694 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1695 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1700 "expected element type `{}` of second argument `{}` \
1701 to be a pointer to the element type `{}` of the first \
1702 argument `{}`, found `{}` != `*mut {}`",
1703 arg_tys[1].simd_type(tcx),
1707 arg_tys[1].simd_type(tcx),
1713 assert!(pointer_count > 0);
1714 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1715 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1717 // The element type of the third argument must be a signed integer type of any width:
1718 match arg_tys[2].simd_type(tcx).kind {
1723 "expected element type `{}` of third argument `{}` \
1724 to be a signed integer type",
1725 arg_tys[2].simd_type(tcx),
1731 // Alignment of T, must be a constant integer value:
1732 let alignment_ty = bx.type_i32();
1733 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1735 // Truncate the mask vector to a vector of i1s:
1736 let (mask, mask_ty) = {
1737 let i1 = bx.type_i1();
1738 let i1xn = bx.type_vector(i1, in_len);
1739 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1742 let ret_t = bx.type_void();
1744 // Type of the vector of pointers:
1745 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1746 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1748 // Type of the vector of elements:
1749 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1750 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1752 let llvm_intrinsic =
1753 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1754 let f = bx.declare_cfn(
1756 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1758 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1759 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1763 macro_rules! arith_red {
1764 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1768 "expected return type `{}` (element of input `{}`), found `{}`",
1773 return match in_elem.kind {
1774 ty::Int(_) | ty::Uint(_) => {
1775 let r = bx.$integer_reduce(args[0].immediate());
1777 // if overflow occurs, the result is the
1778 // mathematical result modulo 2^n:
1779 if name.contains("mul") {
1780 Ok(bx.mul(args[1].immediate(), r))
1782 Ok(bx.add(args[1].immediate(), r))
1785 Ok(bx.$integer_reduce(args[0].immediate()))
1789 let acc = if $ordered {
1790 // ordered arithmetic reductions take an accumulator
1793 // unordered arithmetic reductions use the identity accumulator
1794 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1795 match f.bit_width() {
1796 32 => bx.const_real(bx.type_f32(), identity_acc),
1797 64 => bx.const_real(bx.type_f64(), identity_acc),
1800 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1809 Ok(bx.$float_reduce(acc, args[0].immediate()))
1812 "unsupported {} from `{}` with element `{}` to `{}`",
1823 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1824 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1825 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1826 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1828 macro_rules! minmax_red {
1829 ($name:tt: $int_red:ident, $float_red:ident) => {
1833 "expected return type `{}` (element of input `{}`), found `{}`",
1838 return match in_elem.kind {
1839 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1840 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1841 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1843 "unsupported {} from `{}` with element `{}` to `{}`",
1854 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1855 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1857 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1858 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1860 macro_rules! bitwise_red {
1861 ($name:tt : $red:ident, $boolean:expr) => {
1863 let input = if !$boolean {
1866 "expected return type `{}` (element of input `{}`), found `{}`",
1873 match in_elem.kind {
1874 ty::Int(_) | ty::Uint(_) => {}
1876 "unsupported {} from `{}` with element `{}` to `{}`",
1884 // boolean reductions operate on vectors of i1s:
1885 let i1 = bx.type_i1();
1886 let i1xn = bx.type_vector(i1, in_len as u64);
1887 bx.trunc(args[0].immediate(), i1xn)
1889 return match in_elem.kind {
1890 ty::Int(_) | ty::Uint(_) => {
1891 let r = bx.$red(input);
1892 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1895 "unsupported {} from `{}` with element `{}` to `{}`",
1906 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1907 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1908 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1909 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1910 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1912 if name == "simd_cast" {
1913 require_simd!(ret_ty, "return");
1914 let out_len = ret_ty.simd_size(tcx);
1917 "expected return type with length {} (same as input type `{}`), \
1918 found `{}` with length {}",
1924 // casting cares about nominal type, not just structural type
1925 let out_elem = ret_ty.simd_type(tcx);
1927 if in_elem == out_elem {
1928 return Ok(args[0].immediate());
1933 Int(/* is signed? */ bool),
1937 let (in_style, in_width) = match in_elem.kind {
1938 // vectors of pointer-sized integers should've been
1939 // disallowed before here, so this unwrap is safe.
1940 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1941 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1942 ty::Float(f) => (Style::Float, f.bit_width()),
1943 _ => (Style::Unsupported, 0),
1945 let (out_style, out_width) = match out_elem.kind {
1946 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1947 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1948 ty::Float(f) => (Style::Float, f.bit_width()),
1949 _ => (Style::Unsupported, 0),
1952 match (in_style, out_style) {
1953 (Style::Int(in_is_signed), Style::Int(_)) => {
1954 return Ok(match in_width.cmp(&out_width) {
1955 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1956 Ordering::Equal => args[0].immediate(),
1959 bx.sext(args[0].immediate(), llret_ty)
1961 bx.zext(args[0].immediate(), llret_ty)
1966 (Style::Int(in_is_signed), Style::Float) => {
1967 return Ok(if in_is_signed {
1968 bx.sitofp(args[0].immediate(), llret_ty)
1970 bx.uitofp(args[0].immediate(), llret_ty)
1973 (Style::Float, Style::Int(out_is_signed)) => {
1974 return Ok(if out_is_signed {
1975 bx.fptosi(args[0].immediate(), llret_ty)
1977 bx.fptoui(args[0].immediate(), llret_ty)
1980 (Style::Float, Style::Float) => {
1981 return Ok(match in_width.cmp(&out_width) {
1982 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1983 Ordering::Equal => args[0].immediate(),
1984 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1987 _ => { /* Unsupported. Fallthrough. */ }
1991 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1998 macro_rules! arith {
1999 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2000 $(if name == stringify!($name) {
2001 match in_elem.kind {
2002 $($(ty::$p(_))|* => {
2003 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2008 "unsupported operation on `{}` with element `{}`",
2015 simd_add: Uint, Int => add, Float => fadd;
2016 simd_sub: Uint, Int => sub, Float => fsub;
2017 simd_mul: Uint, Int => mul, Float => fmul;
2018 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2019 simd_rem: Uint => urem, Int => srem, Float => frem;
2020 simd_shl: Uint, Int => shl;
2021 simd_shr: Uint => lshr, Int => ashr;
2022 simd_and: Uint, Int => and;
2023 simd_or: Uint, Int => or;
2024 simd_xor: Uint, Int => xor;
2025 simd_fmax: Float => maxnum;
2026 simd_fmin: Float => minnum;
2030 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
2031 let lhs = args[0].immediate();
2032 let rhs = args[1].immediate();
2033 let is_add = name == "simd_saturating_add";
2034 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2035 let (signed, elem_width, elem_ty) = match in_elem.kind {
2036 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2037 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2040 "expected element type `{}` of vector type `{}` \
2041 to be a signed or unsigned integer type",
2042 arg_tys[0].simd_type(tcx),
2047 let llvm_intrinsic = &format!(
2048 "llvm.{}{}.sat.v{}i{}",
2049 if signed { 's' } else { 'u' },
2050 if is_add { "add" } else { "sub" },
2054 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2056 let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2057 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2058 let v = bx.call(f, &[lhs, rhs], None);
2062 span_bug!(span, "unknown SIMD intrinsic");
2065 // Returns the width of an int Ty, and if it's signed or not
2066 // Returns None if the type is not an integer
2067 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2069 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2071 ty::Int(t) => Some((
2073 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2074 ast::IntTy::I8 => 8,
2075 ast::IntTy::I16 => 16,
2076 ast::IntTy::I32 => 32,
2077 ast::IntTy::I64 => 64,
2078 ast::IntTy::I128 => 128,
2082 ty::Uint(t) => Some((
2084 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2085 ast::UintTy::U8 => 8,
2086 ast::UintTy::U16 => 16,
2087 ast::UintTy::U32 => 32,
2088 ast::UintTy::U64 => 64,
2089 ast::UintTy::U128 => 128,
2097 // Returns the width of a float Ty
2098 // Returns None if the type is not a float
2099 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2101 ty::Float(t) => Some(t.bit_width()),