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;
13 use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh};
14 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
15 use rustc_codegen_ssa::common::TypeKind;
16 use rustc_codegen_ssa::glue;
17 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
18 use rustc_codegen_ssa::mir::place::PlaceRef;
19 use rustc_codegen_ssa::mir::FunctionCx;
20 use rustc_codegen_ssa::traits::*;
21 use rustc_codegen_ssa::MemFlags;
23 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
24 use rustc_middle::ty::{self, Ty};
25 use rustc_middle::{bug, span_bug};
27 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
28 use rustc_target::spec::PanicStrategy;
30 use std::cmp::Ordering;
33 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
34 let llvm_name = match name {
35 "sqrtf32" => "llvm.sqrt.f32",
36 "sqrtf64" => "llvm.sqrt.f64",
37 "powif32" => "llvm.powi.f32",
38 "powif64" => "llvm.powi.f64",
39 "sinf32" => "llvm.sin.f32",
40 "sinf64" => "llvm.sin.f64",
41 "cosf32" => "llvm.cos.f32",
42 "cosf64" => "llvm.cos.f64",
43 "powf32" => "llvm.pow.f32",
44 "powf64" => "llvm.pow.f64",
45 "expf32" => "llvm.exp.f32",
46 "expf64" => "llvm.exp.f64",
47 "exp2f32" => "llvm.exp2.f32",
48 "exp2f64" => "llvm.exp2.f64",
49 "logf32" => "llvm.log.f32",
50 "logf64" => "llvm.log.f64",
51 "log10f32" => "llvm.log10.f32",
52 "log10f64" => "llvm.log10.f64",
53 "log2f32" => "llvm.log2.f32",
54 "log2f64" => "llvm.log2.f64",
55 "fmaf32" => "llvm.fma.f32",
56 "fmaf64" => "llvm.fma.f64",
57 "fabsf32" => "llvm.fabs.f32",
58 "fabsf64" => "llvm.fabs.f64",
59 "minnumf32" => "llvm.minnum.f32",
60 "minnumf64" => "llvm.minnum.f64",
61 "maxnumf32" => "llvm.maxnum.f32",
62 "maxnumf64" => "llvm.maxnum.f64",
63 "copysignf32" => "llvm.copysign.f32",
64 "copysignf64" => "llvm.copysign.f64",
65 "floorf32" => "llvm.floor.f32",
66 "floorf64" => "llvm.floor.f64",
67 "ceilf32" => "llvm.ceil.f32",
68 "ceilf64" => "llvm.ceil.f64",
69 "truncf32" => "llvm.trunc.f32",
70 "truncf64" => "llvm.trunc.f64",
71 "rintf32" => "llvm.rint.f32",
72 "rintf64" => "llvm.rint.f64",
73 "nearbyintf32" => "llvm.nearbyint.f32",
74 "nearbyintf64" => "llvm.nearbyint.f64",
75 "roundf32" => "llvm.round.f32",
76 "roundf64" => "llvm.round.f64",
77 "assume" => "llvm.assume",
78 "abort" => "llvm.trap",
81 Some(cx.get_intrinsic(&llvm_name))
84 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
85 fn codegen_intrinsic_call<'b, Bx: BuilderMethods<'b, 'tcx>>(
87 fx: &FunctionCx<'b, 'tcx, Bx>,
88 instance: ty::Instance<'tcx>,
89 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
90 args: &[OperandRef<'tcx, &'ll Value>],
95 let callee_ty = instance.monomorphic_ty(tcx);
97 let (def_id, substs) = match callee_ty.kind {
98 ty::FnDef(def_id, substs) => (def_id, substs),
99 _ => bug!("expected fn item type, found {}", callee_ty),
102 let sig = callee_ty.fn_sig(tcx);
103 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
104 let arg_tys = sig.inputs();
105 let ret_ty = sig.output();
106 let name = &*tcx.item_name(def_id).as_str();
108 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
109 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
111 let simple = get_simple_intrinsic(self, name);
112 let llval = match name {
113 _ if simple.is_some() => self.call(
115 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
122 let expect = self.get_intrinsic(&("llvm.expect.i1"));
123 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
126 let expect = self.get_intrinsic(&("llvm.expect.i1"));
127 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
140 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
141 self.call(llfn, &[], None)
143 "count_code_region" => {
144 let coverage_data = fx.mir.coverage_data.as_ref().unwrap();
145 let mangled_fn = tcx.symbol_name(fx.instance);
146 let (mangled_fn_name, _len_val) = self.const_str(mangled_fn.name);
147 let hash = self.const_u64(coverage_data.hash);
148 let index = args[0].immediate();
149 let num_counters = self.const_u32(coverage_data.num_counters as u32);
151 "count_code_region to LLVM intrinsic instrprof.increment(fn_name={}, hash={:?}, num_counters={:?}, index={:?})",
152 mangled_fn.name, hash, index, num_counters
154 self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
156 "va_start" => self.va_start(args[0].immediate()),
157 "va_end" => self.va_end(args[0].immediate()),
159 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
160 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
163 match fn_abi.ret.layout.abi {
164 abi::Abi::Scalar(ref scalar) => {
166 Primitive::Int(..) => {
167 if self.cx().size_of(ret_ty).bytes() < 4 {
168 // `va_arg` should not be called on a integer type
169 // less than 4 bytes in length. If it is, promote
170 // the integer to a `i32` and truncate the result
171 // back to the smaller type.
172 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
173 self.trunc(promoted_result, llret_ty)
175 emit_va_arg(self, args[0], ret_ty)
178 Primitive::F64 | Primitive::Pointer => {
179 emit_va_arg(self, args[0], ret_ty)
181 // `va_arg` should never be used with the return type f32.
182 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
185 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
189 let tp_ty = substs.type_at(0);
190 if let OperandValue::Pair(_, meta) = args[0].val {
191 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
194 self.const_usize(self.size_of(tp_ty).bytes())
197 "min_align_of_val" => {
198 let tp_ty = substs.type_at(0);
199 if let OperandValue::Pair(_, meta) = args[0].val {
200 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
203 self.const_usize(self.align_of(tp_ty).bytes())
206 "size_of" | "pref_align_of" | "min_align_of" | "needs_drop" | "type_id"
210 .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
212 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
219 let ptr = args[0].immediate();
220 let offset = args[1].immediate();
221 self.inbounds_gep(ptr, &[offset])
224 let ptr = args[0].immediate();
225 let offset = args[1].immediate();
226 self.gep(ptr, &[offset])
229 "copy_nonoverlapping" => {
265 "volatile_copy_nonoverlapping_memory" => {
277 "volatile_copy_memory" => {
289 "volatile_set_memory" => {
300 "volatile_load" | "unaligned_volatile_load" => {
301 let tp_ty = substs.type_at(0);
302 let mut ptr = args[0].immediate();
303 if let PassMode::Cast(ty) = fn_abi.ret.mode {
304 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
306 let load = self.volatile_load(ptr);
307 let align = if name == "unaligned_volatile_load" {
310 self.align_of(tp_ty).bytes() as u32
313 llvm::LLVMSetAlignment(load, align);
315 to_immediate(self, load, self.layout_of(tp_ty))
317 "volatile_store" => {
318 let dst = args[0].deref(self.cx());
319 args[1].val.volatile_store(self, dst);
322 "unaligned_volatile_store" => {
323 let dst = args[0].deref(self.cx());
324 args[1].val.unaligned_volatile_store(self, dst);
328 | "prefetch_write_data"
329 | "prefetch_read_instruction"
330 | "prefetch_write_instruction" => {
331 let expect = self.get_intrinsic(&("llvm.prefetch"));
332 let (rw, cache_type) = match name {
333 "prefetch_read_data" => (0, 1),
334 "prefetch_write_data" => (1, 1),
335 "prefetch_read_instruction" => (0, 0),
336 "prefetch_write_instruction" => (1, 0),
345 self.const_i32(cache_type),
350 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap"
351 | "bitreverse" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow"
352 | "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "unchecked_div"
353 | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "unchecked_add"
354 | "unchecked_sub" | "unchecked_mul" | "exact_div" | "rotate_left" | "rotate_right"
355 | "saturating_add" | "saturating_sub" => {
357 match int_type_width_signed(ty, self) {
358 Some((width, signed)) => match name {
360 let y = self.const_bool(false);
361 let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
362 self.call(llfn, &[args[0].immediate(), y], None)
364 "ctlz_nonzero" | "cttz_nonzero" => {
365 let y = self.const_bool(true);
366 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
367 let llfn = self.get_intrinsic(llvm_name);
368 self.call(llfn, &[args[0].immediate(), y], None)
370 "ctpop" => self.call(
371 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
372 &[args[0].immediate()],
377 args[0].immediate() // byte swap a u8/i8 is just a no-op
380 self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
381 &[args[0].immediate()],
386 "bitreverse" => self.call(
387 self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
388 &[args[0].immediate()],
391 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
392 let intrinsic = format!(
393 "llvm.{}{}.with.overflow.i{}",
394 if signed { 's' } else { 'u' },
398 let llfn = self.get_intrinsic(&intrinsic);
400 // Convert `i1` to a `bool`, and write it to the out parameter
402 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
403 let val = self.extract_value(pair, 0);
404 let overflow = self.extract_value(pair, 1);
405 let overflow = self.zext(overflow, self.type_bool());
407 let dest = result.project_field(self, 0);
408 self.store(val, dest.llval, dest.align);
409 let dest = result.project_field(self, 1);
410 self.store(overflow, dest.llval, dest.align);
414 "wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
415 "wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
416 "wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
419 self.exactsdiv(args[0].immediate(), args[1].immediate())
421 self.exactudiv(args[0].immediate(), args[1].immediate())
426 self.sdiv(args[0].immediate(), args[1].immediate())
428 self.udiv(args[0].immediate(), args[1].immediate())
433 self.srem(args[0].immediate(), args[1].immediate())
435 self.urem(args[0].immediate(), args[1].immediate())
438 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
441 self.ashr(args[0].immediate(), args[1].immediate())
443 self.lshr(args[0].immediate(), args[1].immediate())
448 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
450 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
455 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
457 self.unchecked_usub(args[0].immediate(), args[1].immediate())
462 self.unchecked_smul(args[0].immediate(), args[1].immediate())
464 self.unchecked_umul(args[0].immediate(), args[1].immediate())
467 "rotate_left" | "rotate_right" => {
468 let is_left = name == "rotate_left";
469 let val = args[0].immediate();
470 let raw_shift = args[1].immediate();
471 // rotate = funnel shift with first two args the same
473 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
474 let llfn = self.get_intrinsic(llvm_name);
475 self.call(llfn, &[val, val, raw_shift], None)
477 "saturating_add" | "saturating_sub" => {
478 let is_add = name == "saturating_add";
479 let lhs = args[0].immediate();
480 let rhs = args[1].immediate();
481 let llvm_name = &format!(
483 if signed { 's' } else { 'u' },
484 if is_add { "add" } else { "sub" },
487 let llfn = self.get_intrinsic(llvm_name);
488 self.call(llfn, &[lhs, rhs], None)
493 span_invalid_monomorphization_error(
497 "invalid monomorphization of `{}` intrinsic: \
498 expected basic integer type, found `{}`",
506 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
507 match float_type_width(arg_tys[0]) {
508 Some(_width) => match name {
509 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
510 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
511 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
512 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
513 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
517 span_invalid_monomorphization_error(
521 "invalid monomorphization of `{}` intrinsic: \
522 expected basic float type, found `{}`",
531 "float_to_int_unchecked" => {
532 if float_type_width(arg_tys[0]).is_none() {
533 span_invalid_monomorphization_error(
537 "invalid monomorphization of `float_to_int_unchecked` \
538 intrinsic: expected basic float type, \
545 match int_type_width_signed(ret_ty, self.cx) {
546 Some((width, signed)) => {
548 self.fptosi(args[0].immediate(), self.cx.type_ix(width))
550 self.fptoui(args[0].immediate(), self.cx.type_ix(width))
554 span_invalid_monomorphization_error(
558 "invalid monomorphization of `float_to_int_unchecked` \
559 intrinsic: expected basic integer type, \
569 "discriminant_value" => {
570 if ret_ty.is_integral() {
571 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
573 span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
577 name if name.starts_with("simd_") => {
578 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
583 // This requires that atomic intrinsics follow a specific naming pattern:
584 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
585 name if name.starts_with("atomic_") => {
586 use rustc_codegen_ssa::common::AtomicOrdering::*;
587 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
589 let split: Vec<&str> = name.split('_').collect();
591 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
592 let (order, failorder) = match split.len() {
593 2 => (SequentiallyConsistent, SequentiallyConsistent),
594 3 => match split[2] {
595 "unordered" => (Unordered, Unordered),
596 "relaxed" => (Monotonic, Monotonic),
597 "acq" => (Acquire, Acquire),
598 "rel" => (Release, Monotonic),
599 "acqrel" => (AcquireRelease, Acquire),
600 "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
601 "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
602 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
604 4 => match (split[2], split[3]) {
605 ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
606 ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
607 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
609 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
612 let invalid_monomorphization = |ty| {
613 span_invalid_monomorphization_error(
617 "invalid monomorphization of `{}` intrinsic: \
618 expected basic integer type, found `{}`",
625 "cxchg" | "cxchgweak" => {
626 let ty = substs.type_at(0);
627 if int_type_width_signed(ty, self).is_some() {
628 let weak = split[1] == "cxchgweak";
629 let pair = self.atomic_cmpxchg(
637 let val = self.extract_value(pair, 0);
638 let success = self.extract_value(pair, 1);
639 let success = self.zext(success, self.type_bool());
641 let dest = result.project_field(self, 0);
642 self.store(val, dest.llval, dest.align);
643 let dest = result.project_field(self, 1);
644 self.store(success, dest.llval, dest.align);
647 return invalid_monomorphization(ty);
652 let ty = substs.type_at(0);
653 if int_type_width_signed(ty, self).is_some() {
654 let size = self.size_of(ty);
655 self.atomic_load(args[0].immediate(), order, size)
657 return invalid_monomorphization(ty);
662 let ty = substs.type_at(0);
663 if int_type_width_signed(ty, self).is_some() {
664 let size = self.size_of(ty);
673 return invalid_monomorphization(ty);
678 self.atomic_fence(order, SynchronizationScope::CrossThread);
682 "singlethreadfence" => {
683 self.atomic_fence(order, SynchronizationScope::SingleThread);
687 // These are all AtomicRMW ops
689 let atom_op = match op {
690 "xchg" => AtomicRmwBinOp::AtomicXchg,
691 "xadd" => AtomicRmwBinOp::AtomicAdd,
692 "xsub" => AtomicRmwBinOp::AtomicSub,
693 "and" => AtomicRmwBinOp::AtomicAnd,
694 "nand" => AtomicRmwBinOp::AtomicNand,
695 "or" => AtomicRmwBinOp::AtomicOr,
696 "xor" => AtomicRmwBinOp::AtomicXor,
697 "max" => AtomicRmwBinOp::AtomicMax,
698 "min" => AtomicRmwBinOp::AtomicMin,
699 "umax" => AtomicRmwBinOp::AtomicUMax,
700 "umin" => AtomicRmwBinOp::AtomicUMin,
701 _ => self.sess().fatal("unknown atomic operation"),
704 let ty = substs.type_at(0);
705 if int_type_width_signed(ty, self).is_some() {
713 return invalid_monomorphization(ty);
719 "nontemporal_store" => {
720 let dst = args[0].deref(self.cx());
721 args[1].val.nontemporal_store(self, dst);
725 "ptr_offset_from" => {
726 let ty = substs.type_at(0);
727 let pointee_size = self.size_of(ty);
729 // This is the same sequence that Clang emits for pointer subtraction.
730 // It can be neither `nsw` nor `nuw` because the input is treated as
731 // unsigned but then the output is treated as signed, so neither works.
732 let a = args[0].immediate();
733 let b = args[1].immediate();
734 let a = self.ptrtoint(a, self.type_isize());
735 let b = self.ptrtoint(b, self.type_isize());
736 let d = self.sub(a, b);
737 let pointee_size = self.const_usize(pointee_size.bytes());
738 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
739 self.exactsdiv(d, pointee_size)
742 _ => bug!("unknown intrinsic '{}'", name),
745 if !fn_abi.ret.is_ignore() {
746 if let PassMode::Cast(ty) = fn_abi.ret.mode {
747 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
748 let ptr = self.pointercast(result.llval, ptr_llty);
749 self.store(llval, ptr, result.align);
751 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
753 .store(self, result);
758 fn abort(&mut self) {
759 let fnname = self.get_intrinsic(&("llvm.trap"));
760 self.call(fnname, &[], None);
763 fn assume(&mut self, val: Self::Value) {
764 let assume_intrinsic = self.get_intrinsic("llvm.assume");
765 self.call(assume_intrinsic, &[val], None);
768 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
769 let expect = self.get_intrinsic(&"llvm.expect.i1");
770 self.call(expect, &[cond, self.const_bool(expected)], None)
773 fn sideeffect(&mut self) {
774 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
775 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
776 self.call(fnname, &[], None);
780 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
781 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
782 self.call(intrinsic, &[va_list], None)
785 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
786 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
787 self.call(intrinsic, &[va_list], None)
792 bx: &mut Builder<'a, 'll, 'tcx>,
800 let (size, align) = bx.size_and_align_of(ty);
801 let size = bx.mul(bx.const_usize(size.bytes()), count);
802 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
804 bx.memmove(dst, align, src, align, size, flags);
806 bx.memcpy(dst, align, src, align, size, flags);
811 bx: &mut Builder<'a, 'll, 'tcx>,
818 let (size, align) = bx.size_and_align_of(ty);
819 let size = bx.mul(bx.const_usize(size.bytes()), count);
820 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
821 bx.memset(dst, val, size, align, flags);
825 bx: &mut Builder<'a, 'll, 'tcx>,
826 try_func: &'ll Value,
828 catch_func: &'ll Value,
831 if bx.sess().panic_strategy() == PanicStrategy::Abort {
832 bx.call(try_func, &[data], None);
833 // Return 0 unconditionally from the intrinsic call;
834 // we can never unwind.
835 let ret_align = bx.tcx().data_layout.i32_align.abi;
836 bx.store(bx.const_i32(0), dest, ret_align);
837 } else if wants_msvc_seh(bx.sess()) {
838 codegen_msvc_try(bx, try_func, data, catch_func, dest);
840 codegen_gnu_try(bx, try_func, data, catch_func, dest);
844 // MSVC's definition of the `rust_try` function.
846 // This implementation uses the new exception handling instructions in LLVM
847 // which have support in LLVM for SEH on MSVC targets. Although these
848 // instructions are meant to work for all targets, as of the time of this
849 // writing, however, LLVM does not recommend the usage of these new instructions
850 // as the old ones are still more optimized.
852 bx: &mut Builder<'a, 'll, 'tcx>,
853 try_func: &'ll Value,
855 catch_func: &'ll Value,
858 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
859 bx.set_personality_fn(bx.eh_personality());
862 let mut normal = bx.build_sibling_block("normal");
863 let mut catchswitch = bx.build_sibling_block("catchswitch");
864 let mut catchpad = bx.build_sibling_block("catchpad");
865 let mut caught = bx.build_sibling_block("caught");
867 let try_func = llvm::get_param(bx.llfn(), 0);
868 let data = llvm::get_param(bx.llfn(), 1);
869 let catch_func = llvm::get_param(bx.llfn(), 2);
871 // We're generating an IR snippet that looks like:
873 // declare i32 @rust_try(%try_func, %data, %catch_func) {
874 // %slot = alloca u8*
875 // invoke %try_func(%data) to label %normal unwind label %catchswitch
881 // %cs = catchswitch within none [%catchpad] unwind to caller
884 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
886 // call %catch_func(%data, %ptr)
887 // catchret from %tok to label %caught
893 // This structure follows the basic usage of throw/try/catch in LLVM.
894 // For example, compile this C++ snippet to see what LLVM generates:
896 // #include <stdint.h>
898 // struct rust_panic {
899 // rust_panic(const rust_panic&);
906 // void (*try_func)(void*),
908 // void (*catch_func)(void*, void*) noexcept
913 // } catch(rust_panic& a) {
914 // catch_func(data, &a);
919 // More information can be found in libstd's seh.rs implementation.
920 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
921 let slot = bx.alloca(bx.type_i8p(), ptr_align);
922 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
924 normal.ret(bx.const_i32(0));
926 let cs = catchswitch.catch_switch(None, None, 1);
927 catchswitch.add_handler(cs, catchpad.llbb());
929 // We can't use the TypeDescriptor defined in libpanic_unwind because it
930 // might be in another DLL and the SEH encoding only supports specifying
931 // a TypeDescriptor from the current module.
933 // However this isn't an issue since the MSVC runtime uses string
934 // comparison on the type name to match TypeDescriptors rather than
937 // So instead we generate a new TypeDescriptor in each module that uses
938 // `try` and let the linker merge duplicate definitions in the same
941 // When modifying, make sure that the type_name string exactly matches
942 // the one used in src/libpanic_unwind/seh.rs.
943 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
944 let type_name = bx.const_bytes(b"rust_panic\0");
946 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
947 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
949 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
950 llvm::SetUniqueComdat(bx.llmod, tydesc);
951 llvm::LLVMSetInitializer(tydesc, type_info);
954 // The flag value of 8 indicates that we are catching the exception by
955 // reference instead of by value. We can't use catch by value because
956 // that requires copying the exception object, which we don't support
957 // since our exception object effectively contains a Box.
959 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
960 let flags = bx.const_i32(8);
961 let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
962 let ptr = catchpad.load(slot, ptr_align);
963 catchpad.call(catch_func, &[data, ptr], Some(&funclet));
965 catchpad.catch_ret(&funclet, caught.llbb());
967 caught.ret(bx.const_i32(1));
970 // Note that no invoke is used here because by definition this function
971 // can't panic (that's what it's catching).
972 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
973 let i32_align = bx.tcx().data_layout.i32_align.abi;
974 bx.store(ret, dest, i32_align);
977 // Definition of the standard `try` function for Rust using the GNU-like model
978 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
981 // This codegen is a little surprising because we always call a shim
982 // function instead of inlining the call to `invoke` manually here. This is done
983 // because in LLVM we're only allowed to have one personality per function
984 // definition. The call to the `try` intrinsic is being inlined into the
985 // function calling it, and that function may already have other personality
986 // functions in play. By calling a shim we're guaranteed that our shim will have
987 // the right personality function.
989 bx: &mut Builder<'a, 'll, 'tcx>,
990 try_func: &'ll Value,
992 catch_func: &'ll Value,
995 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
996 // Codegens the shims described above:
999 // invoke %try_func(%data) normal %normal unwind %catch
1005 // (%ptr, _) = landingpad
1006 // call %catch_func(%data, %ptr)
1011 let mut then = bx.build_sibling_block("then");
1012 let mut catch = bx.build_sibling_block("catch");
1014 let try_func = llvm::get_param(bx.llfn(), 0);
1015 let data = llvm::get_param(bx.llfn(), 1);
1016 let catch_func = llvm::get_param(bx.llfn(), 2);
1017 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1018 then.ret(bx.const_i32(0));
1020 // Type indicator for the exception being thrown.
1022 // The first value in this tuple is a pointer to the exception object
1023 // being thrown. The second value is a "selector" indicating which of
1024 // the landing pad clauses the exception's type had been matched to.
1025 // rust_try ignores the selector.
1026 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1027 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1028 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1030 let tydesc = bx.get_static(tydesc);
1031 bx.bitcast(tydesc, bx.type_i8p())
1033 None => bx.const_null(bx.type_i8p()),
1035 catch.add_clause(vals, tydesc);
1036 let ptr = catch.extract_value(vals, 0);
1037 catch.call(catch_func, &[data, ptr], None);
1038 catch.ret(bx.const_i32(1));
1041 // Note that no invoke is used here because by definition this function
1042 // can't panic (that's what it's catching).
1043 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1044 let i32_align = bx.tcx().data_layout.i32_align.abi;
1045 bx.store(ret, dest, i32_align);
1048 // Helper function to give a Block to a closure to codegen a shim function.
1049 // This is currently primarily used for the `try` intrinsic functions above.
1050 fn gen_fn<'ll, 'tcx>(
1051 cx: &CodegenCx<'ll, 'tcx>,
1053 inputs: Vec<Ty<'tcx>>,
1055 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1057 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1061 hir::Unsafety::Unsafe,
1064 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1065 let llfn = cx.declare_fn(name, &fn_abi);
1066 cx.set_frame_pointer_elimination(llfn);
1067 cx.apply_target_cpu_attr(llfn);
1068 // FIXME(eddyb) find a nicer way to do this.
1069 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1070 let bx = Builder::new_block(cx, llfn, "entry-block");
1075 // Helper function used to get a handle to the `__rust_try` function used to
1076 // catch exceptions.
1078 // This function is only generated once and is then cached.
1079 fn get_rust_try_fn<'ll, 'tcx>(
1080 cx: &CodegenCx<'ll, 'tcx>,
1081 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1083 if let Some(llfn) = cx.rust_try_fn.get() {
1087 // Define the type up front for the signature of the rust_try function.
1089 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1090 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1094 hir::Unsafety::Unsafe,
1097 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1098 [i8p, i8p].iter().cloned(),
1101 hir::Unsafety::Unsafe,
1104 let output = tcx.types.i32;
1105 let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1106 cx.rust_try_fn.set(Some(rust_try));
1110 fn generic_simd_intrinsic(
1111 bx: &mut Builder<'a, 'll, 'tcx>,
1113 callee_ty: Ty<'tcx>,
1114 args: &[OperandRef<'tcx, &'ll Value>],
1116 llret_ty: &'ll Type,
1118 ) -> Result<&'ll Value, ()> {
1119 // macros for error handling:
1120 macro_rules! emit_error {
1124 ($msg: tt, $($fmt: tt)*) => {
1125 span_invalid_monomorphization_error(
1127 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1132 macro_rules! return_error {
1135 emit_error!($($fmt)*);
1141 macro_rules! require {
1142 ($cond: expr, $($fmt: tt)*) => {
1144 return_error!($($fmt)*);
1149 macro_rules! require_simd {
1150 ($ty: expr, $position: expr) => {
1151 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1157 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1158 let arg_tys = sig.inputs();
1160 if name == "simd_select_bitmask" {
1161 let in_ty = arg_tys[0];
1162 let m_len = match in_ty.kind {
1163 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1164 // of intentional as there's not currently a use case for that.
1165 ty::Int(i) => i.bit_width().unwrap(),
1166 ty::Uint(i) => i.bit_width().unwrap(),
1167 _ => return_error!("`{}` is not an integral type", in_ty),
1169 require_simd!(arg_tys[1], "argument");
1170 let v_len = arg_tys[1].simd_size(tcx);
1173 "mismatched lengths: mask length `{}` != other vector length `{}`",
1177 let i1 = bx.type_i1();
1178 let i1xn = bx.type_vector(i1, m_len);
1179 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1180 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1183 // every intrinsic below takes a SIMD vector as its first argument
1184 require_simd!(arg_tys[0], "input");
1185 let in_ty = arg_tys[0];
1186 let in_elem = arg_tys[0].simd_type(tcx);
1187 let in_len = arg_tys[0].simd_size(tcx);
1189 let comparison = match name {
1190 "simd_eq" => Some(hir::BinOpKind::Eq),
1191 "simd_ne" => Some(hir::BinOpKind::Ne),
1192 "simd_lt" => Some(hir::BinOpKind::Lt),
1193 "simd_le" => Some(hir::BinOpKind::Le),
1194 "simd_gt" => Some(hir::BinOpKind::Gt),
1195 "simd_ge" => Some(hir::BinOpKind::Ge),
1199 if let Some(cmp_op) = comparison {
1200 require_simd!(ret_ty, "return");
1202 let out_len = ret_ty.simd_size(tcx);
1205 "expected return type with length {} (same as input type `{}`), \
1206 found `{}` with length {}",
1213 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1214 "expected return type with integer elements, found `{}` with non-integer `{}`",
1216 ret_ty.simd_type(tcx)
1219 return Ok(compare_simd_types(
1221 args[0].immediate(),
1222 args[1].immediate(),
1229 if name.starts_with("simd_shuffle") {
1230 let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1231 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1234 require_simd!(ret_ty, "return");
1236 let out_len = ret_ty.simd_size(tcx);
1239 "expected return type of length {}, found `{}` with length {}",
1245 in_elem == ret_ty.simd_type(tcx),
1246 "expected return element type `{}` (element of input `{}`), \
1247 found `{}` with element type `{}`",
1251 ret_ty.simd_type(tcx)
1254 let total_len = u128::from(in_len) * 2;
1256 let vector = args[2].immediate();
1258 let indices: Option<Vec<_>> = (0..n)
1261 let val = bx.const_get_elt(vector, i as u64);
1262 match bx.const_to_opt_u128(val, true) {
1264 emit_error!("shuffle index #{} is not a constant", arg_idx);
1267 Some(idx) if idx >= total_len => {
1269 "shuffle index #{} is out of bounds (limit {})",
1275 Some(idx) => Some(bx.const_i32(idx as i32)),
1279 let indices = match indices {
1281 None => return Ok(bx.const_null(llret_ty)),
1284 return Ok(bx.shuffle_vector(
1285 args[0].immediate(),
1286 args[1].immediate(),
1287 bx.const_vector(&indices),
1291 if name == "simd_insert" {
1293 in_elem == arg_tys[2],
1294 "expected inserted type `{}` (element of input `{}`), found `{}`",
1299 return Ok(bx.insert_element(
1300 args[0].immediate(),
1301 args[2].immediate(),
1302 args[1].immediate(),
1305 if name == "simd_extract" {
1308 "expected return type `{}` (element of input `{}`), found `{}`",
1313 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1316 if name == "simd_select" {
1317 let m_elem_ty = in_elem;
1319 require_simd!(arg_tys[1], "argument");
1320 let v_len = arg_tys[1].simd_size(tcx);
1323 "mismatched lengths: mask length `{}` != other vector length `{}`",
1327 match m_elem_ty.kind {
1329 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1331 // truncate the mask to a vector of i1s
1332 let i1 = bx.type_i1();
1333 let i1xn = bx.type_vector(i1, m_len as u64);
1334 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1335 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1338 if name == "simd_bitmask" {
1339 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1340 // vector mask and returns an unsigned integer containing the most
1341 // significant bit (MSB) of each lane.
1343 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1345 let expected_int_bits = in_len.max(8);
1347 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1348 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1351 // Integer vector <i{in_bitwidth} x in_len>:
1352 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1354 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1357 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1360 "vector argument `{}`'s element type `{}`, expected integer element type",
1366 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1369 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1372 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1373 // Truncate vector to an <i1 x N>
1374 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1375 // Bitcast <i1 x N> to iN:
1376 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1377 // Zero-extend iN to the bitmask type:
1378 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1381 fn simd_simple_float_intrinsic(
1383 in_elem: &::rustc_middle::ty::TyS<'_>,
1384 in_ty: &::rustc_middle::ty::TyS<'_>,
1386 bx: &mut Builder<'a, 'll, 'tcx>,
1388 args: &[OperandRef<'tcx, &'ll Value>],
1389 ) -> Result<&'ll Value, ()> {
1390 macro_rules! emit_error {
1394 ($msg: tt, $($fmt: tt)*) => {
1395 span_invalid_monomorphization_error(
1397 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1401 macro_rules! return_error {
1404 emit_error!($($fmt)*);
1409 let ety = match in_elem.kind {
1410 ty::Float(f) if f.bit_width() == 32 => {
1411 if in_len < 2 || in_len > 16 {
1413 "unsupported floating-point vector `{}` with length `{}` \
1414 out-of-range [2, 16]",
1421 ty::Float(f) if f.bit_width() == 64 => {
1422 if in_len < 2 || in_len > 8 {
1424 "unsupported floating-point vector `{}` with length `{}` \
1425 out-of-range [2, 8]",
1434 "unsupported element type `{}` of floating-point vector `{}`",
1440 return_error!("`{}` is not a floating-point type", in_ty);
1444 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1445 let intrinsic = bx.get_intrinsic(&llvm_name);
1447 bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1448 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1454 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1457 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1460 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1463 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1466 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1469 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1472 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1475 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1478 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1481 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1484 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1487 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1490 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1493 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1495 _ => { /* fallthrough */ }
1499 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1500 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1501 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1502 let p0s: String = "p0".repeat(no_pointers);
1503 match elem_ty.kind {
1504 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1505 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1506 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1507 _ => unreachable!(),
1512 cx: &CodegenCx<'ll, '_>,
1515 mut no_pointers: usize,
1517 // FIXME: use cx.layout_of(ty).llvm_type() ?
1518 let mut elem_ty = match elem_ty.kind {
1519 ty::Int(v) => cx.type_int_from_ty(v),
1520 ty::Uint(v) => cx.type_uint_from_ty(v),
1521 ty::Float(v) => cx.type_float_from_ty(v),
1522 _ => unreachable!(),
1524 while no_pointers > 0 {
1525 elem_ty = cx.type_ptr_to(elem_ty);
1528 cx.type_vector(elem_ty, vec_len)
1531 if name == "simd_gather" {
1532 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1533 // mask: <N x i{M}>) -> <N x T>
1534 // * N: number of elements in the input vectors
1535 // * T: type of the element to load
1536 // * M: any integer width is supported, will be truncated to i1
1538 // All types must be simd vector types
1539 require_simd!(in_ty, "first");
1540 require_simd!(arg_tys[1], "second");
1541 require_simd!(arg_tys[2], "third");
1542 require_simd!(ret_ty, "return");
1544 // Of the same length:
1546 in_len == arg_tys[1].simd_size(tcx),
1547 "expected {} argument with length {} (same as input type `{}`), \
1548 found `{}` with length {}",
1553 arg_tys[1].simd_size(tcx)
1556 in_len == arg_tys[2].simd_size(tcx),
1557 "expected {} argument with length {} (same as input type `{}`), \
1558 found `{}` with length {}",
1563 arg_tys[2].simd_size(tcx)
1566 // The return type must match the first argument type
1567 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1569 // This counts how many pointers
1570 fn ptr_count(t: Ty<'_>) -> usize {
1572 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1578 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1580 ty::RawPtr(p) => non_ptr(p.ty),
1585 // The second argument must be a simd vector with an element type that's a pointer
1586 // to the element type of the first argument
1587 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1588 ty::RawPtr(p) if p.ty == in_elem => {
1589 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1594 "expected element type `{}` of second argument `{}` \
1595 to be a pointer to the element type `{}` of the first \
1596 argument `{}`, found `{}` != `*_ {}`",
1597 arg_tys[1].simd_type(tcx),
1601 arg_tys[1].simd_type(tcx),
1607 assert!(pointer_count > 0);
1608 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1609 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1611 // The element type of the third argument must be a signed integer type of any width:
1612 match arg_tys[2].simd_type(tcx).kind {
1617 "expected element type `{}` of third argument `{}` \
1618 to be a signed integer type",
1619 arg_tys[2].simd_type(tcx),
1625 // Alignment of T, must be a constant integer value:
1626 let alignment_ty = bx.type_i32();
1627 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1629 // Truncate the mask vector to a vector of i1s:
1630 let (mask, mask_ty) = {
1631 let i1 = bx.type_i1();
1632 let i1xn = bx.type_vector(i1, in_len);
1633 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1636 // Type of the vector of pointers:
1637 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1638 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1640 // Type of the vector of elements:
1641 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1642 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1644 let llvm_intrinsic =
1645 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1646 let f = bx.declare_cfn(
1649 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1653 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1654 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1658 if name == "simd_scatter" {
1659 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1660 // mask: <N x i{M}>) -> ()
1661 // * N: number of elements in the input vectors
1662 // * T: type of the element to load
1663 // * M: any integer width is supported, will be truncated to i1
1665 // All types must be simd vector types
1666 require_simd!(in_ty, "first");
1667 require_simd!(arg_tys[1], "second");
1668 require_simd!(arg_tys[2], "third");
1670 // Of the same length:
1672 in_len == arg_tys[1].simd_size(tcx),
1673 "expected {} argument with length {} (same as input type `{}`), \
1674 found `{}` with length {}",
1679 arg_tys[1].simd_size(tcx)
1682 in_len == arg_tys[2].simd_size(tcx),
1683 "expected {} argument with length {} (same as input type `{}`), \
1684 found `{}` with length {}",
1689 arg_tys[2].simd_size(tcx)
1692 // This counts how many pointers
1693 fn ptr_count(t: Ty<'_>) -> usize {
1695 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1701 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1703 ty::RawPtr(p) => non_ptr(p.ty),
1708 // The second argument must be a simd vector with an element type that's a pointer
1709 // to the element type of the first argument
1710 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1711 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1712 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1717 "expected element type `{}` of second argument `{}` \
1718 to be a pointer to the element type `{}` of the first \
1719 argument `{}`, found `{}` != `*mut {}`",
1720 arg_tys[1].simd_type(tcx),
1724 arg_tys[1].simd_type(tcx),
1730 assert!(pointer_count > 0);
1731 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1732 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1734 // The element type of the third argument must be a signed integer type of any width:
1735 match arg_tys[2].simd_type(tcx).kind {
1740 "expected element type `{}` of third argument `{}` \
1741 to be a signed integer type",
1742 arg_tys[2].simd_type(tcx),
1748 // Alignment of T, must be a constant integer value:
1749 let alignment_ty = bx.type_i32();
1750 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1752 // Truncate the mask vector to a vector of i1s:
1753 let (mask, mask_ty) = {
1754 let i1 = bx.type_i1();
1755 let i1xn = bx.type_vector(i1, in_len);
1756 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1759 let ret_t = bx.type_void();
1761 // Type of the vector of pointers:
1762 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1763 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1765 // Type of the vector of elements:
1766 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1767 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1769 let llvm_intrinsic =
1770 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1771 let f = bx.declare_cfn(
1773 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1775 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1776 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1780 macro_rules! arith_red {
1781 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1785 "expected return type `{}` (element of input `{}`), found `{}`",
1790 return match in_elem.kind {
1791 ty::Int(_) | ty::Uint(_) => {
1792 let r = bx.$integer_reduce(args[0].immediate());
1794 // if overflow occurs, the result is the
1795 // mathematical result modulo 2^n:
1796 if name.contains("mul") {
1797 Ok(bx.mul(args[1].immediate(), r))
1799 Ok(bx.add(args[1].immediate(), r))
1802 Ok(bx.$integer_reduce(args[0].immediate()))
1806 let acc = if $ordered {
1807 // ordered arithmetic reductions take an accumulator
1810 // unordered arithmetic reductions use the identity accumulator
1811 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1812 match f.bit_width() {
1813 32 => bx.const_real(bx.type_f32(), identity_acc),
1814 64 => bx.const_real(bx.type_f64(), identity_acc),
1817 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1826 Ok(bx.$float_reduce(acc, args[0].immediate()))
1829 "unsupported {} from `{}` with element `{}` to `{}`",
1840 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1841 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1842 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1843 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1845 macro_rules! minmax_red {
1846 ($name:tt: $int_red:ident, $float_red:ident) => {
1850 "expected return type `{}` (element of input `{}`), found `{}`",
1855 return match in_elem.kind {
1856 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1857 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1858 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1860 "unsupported {} from `{}` with element `{}` to `{}`",
1871 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1872 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1874 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1875 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1877 macro_rules! bitwise_red {
1878 ($name:tt : $red:ident, $boolean:expr) => {
1880 let input = if !$boolean {
1883 "expected return type `{}` (element of input `{}`), found `{}`",
1890 match in_elem.kind {
1891 ty::Int(_) | ty::Uint(_) => {}
1893 "unsupported {} from `{}` with element `{}` to `{}`",
1901 // boolean reductions operate on vectors of i1s:
1902 let i1 = bx.type_i1();
1903 let i1xn = bx.type_vector(i1, in_len as u64);
1904 bx.trunc(args[0].immediate(), i1xn)
1906 return match in_elem.kind {
1907 ty::Int(_) | ty::Uint(_) => {
1908 let r = bx.$red(input);
1909 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1912 "unsupported {} from `{}` with element `{}` to `{}`",
1923 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1924 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1925 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1926 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1927 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1929 if name == "simd_cast" {
1930 require_simd!(ret_ty, "return");
1931 let out_len = ret_ty.simd_size(tcx);
1934 "expected return type with length {} (same as input type `{}`), \
1935 found `{}` with length {}",
1941 // casting cares about nominal type, not just structural type
1942 let out_elem = ret_ty.simd_type(tcx);
1944 if in_elem == out_elem {
1945 return Ok(args[0].immediate());
1950 Int(/* is signed? */ bool),
1954 let (in_style, in_width) = match in_elem.kind {
1955 // vectors of pointer-sized integers should've been
1956 // disallowed before here, so this unwrap is safe.
1957 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1958 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1959 ty::Float(f) => (Style::Float, f.bit_width()),
1960 _ => (Style::Unsupported, 0),
1962 let (out_style, out_width) = match out_elem.kind {
1963 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1964 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1965 ty::Float(f) => (Style::Float, f.bit_width()),
1966 _ => (Style::Unsupported, 0),
1969 match (in_style, out_style) {
1970 (Style::Int(in_is_signed), Style::Int(_)) => {
1971 return Ok(match in_width.cmp(&out_width) {
1972 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1973 Ordering::Equal => args[0].immediate(),
1976 bx.sext(args[0].immediate(), llret_ty)
1978 bx.zext(args[0].immediate(), llret_ty)
1983 (Style::Int(in_is_signed), Style::Float) => {
1984 return Ok(if in_is_signed {
1985 bx.sitofp(args[0].immediate(), llret_ty)
1987 bx.uitofp(args[0].immediate(), llret_ty)
1990 (Style::Float, Style::Int(out_is_signed)) => {
1991 return Ok(if out_is_signed {
1992 bx.fptosi(args[0].immediate(), llret_ty)
1994 bx.fptoui(args[0].immediate(), llret_ty)
1997 (Style::Float, Style::Float) => {
1998 return Ok(match in_width.cmp(&out_width) {
1999 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2000 Ordering::Equal => args[0].immediate(),
2001 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2004 _ => { /* Unsupported. Fallthrough. */ }
2008 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2015 macro_rules! arith {
2016 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2017 $(if name == stringify!($name) {
2018 match in_elem.kind {
2019 $($(ty::$p(_))|* => {
2020 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2025 "unsupported operation on `{}` with element `{}`",
2032 simd_add: Uint, Int => add, Float => fadd;
2033 simd_sub: Uint, Int => sub, Float => fsub;
2034 simd_mul: Uint, Int => mul, Float => fmul;
2035 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2036 simd_rem: Uint => urem, Int => srem, Float => frem;
2037 simd_shl: Uint, Int => shl;
2038 simd_shr: Uint => lshr, Int => ashr;
2039 simd_and: Uint, Int => and;
2040 simd_or: Uint, Int => or;
2041 simd_xor: Uint, Int => xor;
2042 simd_fmax: Float => maxnum;
2043 simd_fmin: Float => minnum;
2047 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
2048 let lhs = args[0].immediate();
2049 let rhs = args[1].immediate();
2050 let is_add = name == "simd_saturating_add";
2051 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2052 let (signed, elem_width, elem_ty) = match in_elem.kind {
2053 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2054 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2057 "expected element type `{}` of vector type `{}` \
2058 to be a signed or unsigned integer type",
2059 arg_tys[0].simd_type(tcx),
2064 let llvm_intrinsic = &format!(
2065 "llvm.{}{}.sat.v{}i{}",
2066 if signed { 's' } else { 'u' },
2067 if is_add { "add" } else { "sub" },
2071 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2073 let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2074 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2075 let v = bx.call(f, &[lhs, rhs], None);
2079 span_bug!(span, "unknown SIMD intrinsic");
2082 // Returns the width of an int Ty, and if it's signed or not
2083 // Returns None if the type is not an integer
2084 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2086 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2088 ty::Int(t) => Some((
2090 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2091 ast::IntTy::I8 => 8,
2092 ast::IntTy::I16 => 16,
2093 ast::IntTy::I32 => 32,
2094 ast::IntTy::I64 => 64,
2095 ast::IntTy::I128 => 128,
2099 ty::Uint(t) => Some((
2101 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2102 ast::UintTy::U8 => 8,
2103 ast::UintTy::U16 => 16,
2104 ast::UintTy::U32 => 32,
2105 ast::UintTy::U64 => 64,
2106 ast::UintTy::U128 => 128,
2114 // Returns the width of a float Ty
2115 // Returns None if the type is not a float
2116 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2118 ty::Float(t) => Some(t.bit_width()),