4 use crate::abi::{Abi, FnAbi, LlvmType, PassMode};
5 use crate::context::CodegenCx;
6 use crate::type_::Type;
7 use crate::type_of::LayoutLlvmExt;
8 use crate::builder::Builder;
9 use crate::value::Value;
10 use crate::va_arg::emit_va_arg;
11 use rustc_codegen_ssa::MemFlags;
12 use rustc_codegen_ssa::mir::place::PlaceRef;
13 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14 use rustc_codegen_ssa::glue;
15 use rustc_codegen_ssa::base::{to_immediate, wants_msvc_seh, compare_simd_types};
16 use rustc::ty::{self, Ty};
17 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, Primitive};
18 use rustc::mir::interpret::GlobalId;
19 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
21 use rustc_target::abi::HasDataLayout;
24 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
25 use rustc_codegen_ssa::traits::*;
29 use std::cmp::Ordering;
30 use std::{iter, i128, u128};
32 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
33 let llvm_name = match name {
34 "sqrtf32" => "llvm.sqrt.f32",
35 "sqrtf64" => "llvm.sqrt.f64",
36 "powif32" => "llvm.powi.f32",
37 "powif64" => "llvm.powi.f64",
38 "sinf32" => "llvm.sin.f32",
39 "sinf64" => "llvm.sin.f64",
40 "cosf32" => "llvm.cos.f32",
41 "cosf64" => "llvm.cos.f64",
42 "powf32" => "llvm.pow.f32",
43 "powf64" => "llvm.pow.f64",
44 "expf32" => "llvm.exp.f32",
45 "expf64" => "llvm.exp.f64",
46 "exp2f32" => "llvm.exp2.f32",
47 "exp2f64" => "llvm.exp2.f64",
48 "logf32" => "llvm.log.f32",
49 "logf64" => "llvm.log.f64",
50 "log10f32" => "llvm.log10.f32",
51 "log10f64" => "llvm.log10.f64",
52 "log2f32" => "llvm.log2.f32",
53 "log2f64" => "llvm.log2.f64",
54 "fmaf32" => "llvm.fma.f32",
55 "fmaf64" => "llvm.fma.f64",
56 "fabsf32" => "llvm.fabs.f32",
57 "fabsf64" => "llvm.fabs.f64",
58 "minnumf32" => "llvm.minnum.f32",
59 "minnumf64" => "llvm.minnum.f64",
60 "maxnumf32" => "llvm.maxnum.f32",
61 "maxnumf64" => "llvm.maxnum.f64",
62 "copysignf32" => "llvm.copysign.f32",
63 "copysignf64" => "llvm.copysign.f64",
64 "floorf32" => "llvm.floor.f32",
65 "floorf64" => "llvm.floor.f64",
66 "ceilf32" => "llvm.ceil.f32",
67 "ceilf64" => "llvm.ceil.f64",
68 "truncf32" => "llvm.trunc.f32",
69 "truncf64" => "llvm.trunc.f64",
70 "rintf32" => "llvm.rint.f32",
71 "rintf64" => "llvm.rint.f64",
72 "nearbyintf32" => "llvm.nearbyint.f32",
73 "nearbyintf64" => "llvm.nearbyint.f64",
74 "roundf32" => "llvm.round.f32",
75 "roundf64" => "llvm.round.f64",
76 "assume" => "llvm.assume",
77 "abort" => "llvm.trap",
80 Some(cx.get_intrinsic(&llvm_name))
83 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
84 fn codegen_intrinsic_call(
86 instance: ty::Instance<'tcx>,
87 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
88 args: &[OperandRef<'tcx, &'ll Value>],
93 let callee_ty = instance.ty(tcx);
95 let (def_id, substs) = match callee_ty.kind {
96 ty::FnDef(def_id, substs) => (def_id, substs),
97 _ => bug!("expected fn item type, found {}", callee_ty)
100 let sig = callee_ty.fn_sig(tcx);
101 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
102 let arg_tys = sig.inputs();
103 let ret_ty = sig.output();
104 let name = &*tcx.item_name(def_id).as_str();
106 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
107 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
109 let simple = get_simple_intrinsic(self, name);
110 let llval = match name {
111 _ if simple.is_some() => {
112 self.call(simple.unwrap(),
113 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
120 let expect = self.get_intrinsic(&("llvm.expect.i1"));
121 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
124 let expect = self.get_intrinsic(&("llvm.expect.i1"));
125 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
136 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
137 self.call(llfn, &[], None)
140 self.va_start(args[0].immediate())
143 self.va_end(args[0].immediate())
146 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
147 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
150 match fn_abi.ret.layout.abi {
151 layout::Abi::Scalar(ref scalar) => {
153 Primitive::Int(..) => {
154 if self.cx().size_of(ret_ty).bytes() < 4 {
155 // `va_arg` should not be called on a integer type
156 // less than 4 bytes in length. If it is, promote
157 // the integer to a `i32` and truncate the result
158 // back to the smaller type.
159 let promoted_result = emit_va_arg(self, args[0],
161 self.trunc(promoted_result, llret_ty)
163 emit_va_arg(self, args[0], ret_ty)
167 Primitive::Pointer => {
168 emit_va_arg(self, args[0], ret_ty)
170 // `va_arg` should never be used with the return type f32.
172 bug!("the va_arg intrinsic does not work with `f32`")
177 bug!("the va_arg intrinsic does not work with non-scalar types")
182 let tp_ty = substs.type_at(0);
183 if let OperandValue::Pair(_, meta) = args[0].val {
184 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
187 self.const_usize(self.size_of(tp_ty).bytes())
190 "min_align_of_val" => {
191 let tp_ty = substs.type_at(0);
192 if let OperandValue::Pair(_, meta) = args[0].val {
193 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
196 self.const_usize(self.align_of(tp_ty).bytes())
209 let ty_name = self.tcx.const_eval(ty::ParamEnv::reveal_all().and(gid)).unwrap();
210 OperandRef::from_const(self, ty_name).immediate_or_packed_pair(self)
213 let ty = substs.type_at(0);
214 if !self.layout_of(ty).is_zst() {
215 // Just zero out the stack slot.
216 // If we store a zero constant, LLVM will drown in vreg allocation for large
217 // data structures, and the generated code will be awful. (A telltale sign of
218 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
230 // Effectively no-ops
231 "uninit" | "forget" => {
235 let ptr = args[0].immediate();
236 let offset = args[1].immediate();
237 self.inbounds_gep(ptr, &[offset])
240 let ptr = args[0].immediate();
241 let offset = args[1].immediate();
242 self.gep(ptr, &[offset])
245 "copy_nonoverlapping" => {
246 copy_intrinsic(self, false, false, substs.type_at(0),
247 args[1].immediate(), args[0].immediate(), args[2].immediate());
251 copy_intrinsic(self, true, false, substs.type_at(0),
252 args[1].immediate(), args[0].immediate(), args[2].immediate());
256 memset_intrinsic(self, false, substs.type_at(0),
257 args[0].immediate(), args[1].immediate(), args[2].immediate());
261 "volatile_copy_nonoverlapping_memory" => {
262 copy_intrinsic(self, false, true, substs.type_at(0),
263 args[0].immediate(), args[1].immediate(), args[2].immediate());
266 "volatile_copy_memory" => {
267 copy_intrinsic(self, true, true, substs.type_at(0),
268 args[0].immediate(), args[1].immediate(), args[2].immediate());
271 "volatile_set_memory" => {
272 memset_intrinsic(self, true, substs.type_at(0),
273 args[0].immediate(), args[1].immediate(), args[2].immediate());
276 "volatile_load" | "unaligned_volatile_load" => {
277 let tp_ty = substs.type_at(0);
278 let mut ptr = args[0].immediate();
279 if let PassMode::Cast(ty) = fn_abi.ret.mode {
280 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
282 let load = self.volatile_load(ptr);
283 let align = if name == "unaligned_volatile_load" {
286 self.align_of(tp_ty).bytes() as u32
289 llvm::LLVMSetAlignment(load, align);
291 to_immediate(self, load, self.layout_of(tp_ty))
293 "volatile_store" => {
294 let dst = args[0].deref(self.cx());
295 args[1].val.volatile_store(self, dst);
298 "unaligned_volatile_store" => {
299 let dst = args[0].deref(self.cx());
300 args[1].val.unaligned_volatile_store(self, dst);
303 "prefetch_read_data" | "prefetch_write_data" |
304 "prefetch_read_instruction" | "prefetch_write_instruction" => {
305 let expect = self.get_intrinsic(&("llvm.prefetch"));
306 let (rw, cache_type) = match name {
307 "prefetch_read_data" => (0, 1),
308 "prefetch_write_data" => (1, 1),
309 "prefetch_read_instruction" => (0, 0),
310 "prefetch_write_instruction" => (1, 0),
317 self.const_i32(cache_type)
320 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
321 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
322 "mul_with_overflow" | "wrapping_add" | "wrapping_sub" | "wrapping_mul" |
323 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" |
324 "unchecked_add" | "unchecked_sub" | "unchecked_mul" | "exact_div" |
325 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
327 match int_type_width_signed(ty, self) {
328 Some((width, signed)) =>
331 let y = self.const_bool(false);
332 let llfn = self.get_intrinsic(
333 &format!("llvm.{}.i{}", name, width),
335 self.call(llfn, &[args[0].immediate(), y], None)
337 "ctlz_nonzero" | "cttz_nonzero" => {
338 let y = self.const_bool(true);
339 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
340 let llfn = self.get_intrinsic(llvm_name);
341 self.call(llfn, &[args[0].immediate(), y], None)
343 "ctpop" => self.call(
344 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
345 &[args[0].immediate()],
350 args[0].immediate() // byte swap a u8/i8 is just a no-op
354 &format!("llvm.bswap.i{}", width),
356 &[args[0].immediate()],
364 &format!("llvm.bitreverse.i{}", width),
366 &[args[0].immediate()],
370 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
371 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
372 if signed { 's' } else { 'u' },
374 let llfn = self.get_intrinsic(&intrinsic);
376 // Convert `i1` to a `bool`, and write it to the out parameter
377 let pair = self.call(llfn, &[
381 let val = self.extract_value(pair, 0);
382 let overflow = self.extract_value(pair, 1);
383 let overflow = self.zext(overflow, self.type_bool());
385 let dest = result.project_field(self, 0);
386 self.store(val, dest.llval, dest.align);
387 let dest = result.project_field(self, 1);
388 self.store(overflow, dest.llval, dest.align);
392 "wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
393 "wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
394 "wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
397 self.exactsdiv(args[0].immediate(), args[1].immediate())
399 self.exactudiv(args[0].immediate(), args[1].immediate())
403 self.sdiv(args[0].immediate(), args[1].immediate())
405 self.udiv(args[0].immediate(), args[1].immediate())
409 self.srem(args[0].immediate(), args[1].immediate())
411 self.urem(args[0].immediate(), args[1].immediate())
413 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
416 self.ashr(args[0].immediate(), args[1].immediate())
418 self.lshr(args[0].immediate(), args[1].immediate())
422 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
424 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
429 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
431 self.unchecked_usub(args[0].immediate(), args[1].immediate())
436 self.unchecked_smul(args[0].immediate(), args[1].immediate())
438 self.unchecked_umul(args[0].immediate(), args[1].immediate())
441 "rotate_left" | "rotate_right" => {
442 let is_left = name == "rotate_left";
443 let val = args[0].immediate();
444 let raw_shift = args[1].immediate();
445 if llvm_util::get_major_version() >= 7 {
446 // rotate = funnel shift with first two args the same
447 let llvm_name = &format!("llvm.fsh{}.i{}",
448 if is_left { 'l' } else { 'r' }, width);
449 let llfn = self.get_intrinsic(llvm_name);
450 self.call(llfn, &[val, val, raw_shift], None)
452 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
453 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
454 let width = self.const_uint(
458 let shift = self.urem(raw_shift, width);
459 let width_minus_raw_shift = self.sub(width, raw_shift);
460 let inv_shift = self.urem(width_minus_raw_shift, width);
461 let shift1 = self.shl(
463 if is_left { shift } else { inv_shift },
465 let shift2 = self.lshr(
467 if !is_left { shift } else { inv_shift },
469 self.or(shift1, shift2)
472 "saturating_add" | "saturating_sub" => {
473 let is_add = name == "saturating_add";
474 let lhs = args[0].immediate();
475 let rhs = args[1].immediate();
476 if llvm_util::get_major_version() >= 8 {
477 let llvm_name = &format!("llvm.{}{}.sat.i{}",
478 if signed { 's' } else { 'u' },
479 if is_add { "add" } else { "sub" },
481 let llfn = self.get_intrinsic(llvm_name);
482 self.call(llfn, &[lhs, rhs], None)
484 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
485 if signed { 's' } else { 'u' },
486 if is_add { "add" } else { "sub" },
488 let llfn = self.get_intrinsic(llvm_name);
489 let pair = self.call(llfn, &[lhs, rhs], None);
490 let val = self.extract_value(pair, 0);
491 let overflow = self.extract_value(pair, 1);
492 let llty = self.type_ix(width);
494 let limit = if signed {
495 let limit_lo = self.const_uint_big(
496 llty, (i128::MIN >> (128 - width)) as u128);
497 let limit_hi = self.const_uint_big(
498 llty, (i128::MAX >> (128 - width)) as u128);
500 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
501 self.select(neg, limit_hi, limit_lo)
503 self.const_uint_big(llty, u128::MAX >> (128 - width))
505 self.const_uint(llty, 0)
507 self.select(overflow, limit, val)
513 span_invalid_monomorphization_error(
515 &format!("invalid monomorphization of `{}` intrinsic: \
516 expected basic integer type, found `{}`", name, ty));
522 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
523 match float_type_width(arg_tys[0]) {
526 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
527 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
528 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
529 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
530 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
534 span_invalid_monomorphization_error(
536 &format!("invalid monomorphization of `{}` intrinsic: \
537 expected basic float type, found `{}`", name, arg_tys[0]));
544 "discriminant_value" => {
545 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
548 name if name.starts_with("simd_") => {
549 match generic_simd_intrinsic(self, name,
558 // This requires that atomic intrinsics follow a specific naming pattern:
559 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
560 name if name.starts_with("atomic_") => {
561 use rustc_codegen_ssa::common::AtomicOrdering::*;
562 use rustc_codegen_ssa::common::
563 {SynchronizationScope, AtomicRmwBinOp};
565 let split: Vec<&str> = name.split('_').collect();
567 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
568 let (order, failorder) = match split.len() {
569 2 => (SequentiallyConsistent, SequentiallyConsistent),
570 3 => match split[2] {
571 "unordered" => (Unordered, Unordered),
572 "relaxed" => (Monotonic, Monotonic),
573 "acq" => (Acquire, Acquire),
574 "rel" => (Release, Monotonic),
575 "acqrel" => (AcquireRelease, Acquire),
576 "failrelaxed" if is_cxchg =>
577 (SequentiallyConsistent, Monotonic),
578 "failacq" if is_cxchg =>
579 (SequentiallyConsistent, Acquire),
580 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
582 4 => match (split[2], split[3]) {
583 ("acq", "failrelaxed") if is_cxchg =>
584 (Acquire, Monotonic),
585 ("acqrel", "failrelaxed") if is_cxchg =>
586 (AcquireRelease, Monotonic),
587 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
589 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
592 let invalid_monomorphization = |ty| {
593 span_invalid_monomorphization_error(tcx.sess, span,
594 &format!("invalid monomorphization of `{}` intrinsic: \
595 expected basic integer type, found `{}`", name, ty));
599 "cxchg" | "cxchgweak" => {
600 let ty = substs.type_at(0);
601 if int_type_width_signed(ty, self).is_some() {
602 let weak = split[1] == "cxchgweak";
603 let pair = self.atomic_cmpxchg(
610 let val = self.extract_value(pair, 0);
611 let success = self.extract_value(pair, 1);
612 let success = self.zext(success, self.type_bool());
614 let dest = result.project_field(self, 0);
615 self.store(val, dest.llval, dest.align);
616 let dest = result.project_field(self, 1);
617 self.store(success, dest.llval, dest.align);
620 return invalid_monomorphization(ty);
625 let ty = substs.type_at(0);
626 if int_type_width_signed(ty, self).is_some() {
627 let size = self.size_of(ty);
628 self.atomic_load(args[0].immediate(), order, size)
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);
646 return invalid_monomorphization(ty);
651 self.atomic_fence(order, SynchronizationScope::CrossThread);
655 "singlethreadfence" => {
656 self.atomic_fence(order, SynchronizationScope::SingleThread);
660 // These are all AtomicRMW ops
662 let atom_op = match op {
663 "xchg" => AtomicRmwBinOp::AtomicXchg,
664 "xadd" => AtomicRmwBinOp::AtomicAdd,
665 "xsub" => AtomicRmwBinOp::AtomicSub,
666 "and" => AtomicRmwBinOp::AtomicAnd,
667 "nand" => AtomicRmwBinOp::AtomicNand,
668 "or" => AtomicRmwBinOp::AtomicOr,
669 "xor" => AtomicRmwBinOp::AtomicXor,
670 "max" => AtomicRmwBinOp::AtomicMax,
671 "min" => AtomicRmwBinOp::AtomicMin,
672 "umax" => AtomicRmwBinOp::AtomicUMax,
673 "umin" => AtomicRmwBinOp::AtomicUMin,
674 _ => self.sess().fatal("unknown atomic operation")
677 let ty = substs.type_at(0);
678 if int_type_width_signed(ty, self).is_some() {
686 return invalid_monomorphization(ty);
692 "nontemporal_store" => {
693 let dst = args[0].deref(self.cx());
694 args[1].val.nontemporal_store(self, dst);
698 "ptr_offset_from" => {
699 let ty = substs.type_at(0);
700 let pointee_size = self.size_of(ty);
702 // This is the same sequence that Clang emits for pointer subtraction.
703 // It can be neither `nsw` nor `nuw` because the input is treated as
704 // unsigned but then the output is treated as signed, so neither works.
705 let a = args[0].immediate();
706 let b = args[1].immediate();
707 let a = self.ptrtoint(a, self.type_isize());
708 let b = self.ptrtoint(b, self.type_isize());
709 let d = self.sub(a, b);
710 let pointee_size = self.const_usize(pointee_size.bytes());
711 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
712 self.exactsdiv(d, pointee_size)
715 _ => bug!("unknown intrinsic '{}'", name),
718 if !fn_abi.ret.is_ignore() {
719 if let PassMode::Cast(ty) = fn_abi.ret.mode {
720 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
721 let ptr = self.pointercast(result.llval, ptr_llty);
722 self.store(llval, ptr, result.align);
724 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
725 .val.store(self, result);
730 fn abort(&mut self) {
731 let fnname = self.get_intrinsic(&("llvm.trap"));
732 self.call(fnname, &[], None);
735 fn assume(&mut self, val: Self::Value) {
736 let assume_intrinsic = self.get_intrinsic("llvm.assume");
737 self.call(assume_intrinsic, &[val], None);
740 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
741 let expect = self.get_intrinsic(&"llvm.expect.i1");
742 self.call(expect, &[cond, self.const_bool(expected)], None)
745 fn sideeffect(&mut self) {
746 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
747 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
748 self.call(fnname, &[], None);
752 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
753 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
754 self.call(intrinsic, &[va_list], None)
757 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
758 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
759 self.call(intrinsic, &[va_list], None)
764 bx: &mut Builder<'a, 'll, 'tcx>,
772 let (size, align) = bx.size_and_align_of(ty);
773 let size = bx.mul(bx.const_usize(size.bytes()), count);
774 let flags = if volatile {
780 bx.memmove(dst, align, src, align, size, flags);
782 bx.memcpy(dst, align, src, align, size, flags);
787 bx: &mut Builder<'a, 'll, 'tcx>,
794 let (size, align) = bx.size_and_align_of(ty);
795 let size = bx.mul(bx.const_usize(size.bytes()), count);
796 let flags = if volatile {
801 bx.memset(dst, val, size, align, flags);
805 bx: &mut Builder<'a, 'll, 'tcx>,
808 local_ptr: &'ll Value,
811 if bx.sess().no_landing_pads() {
812 bx.call(func, &[data], None);
813 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
814 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
815 } else if wants_msvc_seh(bx.sess()) {
816 codegen_msvc_try(bx, func, data, local_ptr, dest);
818 codegen_gnu_try(bx, func, data, local_ptr, dest);
822 // MSVC's definition of the `rust_try` function.
824 // This implementation uses the new exception handling instructions in LLVM
825 // which have support in LLVM for SEH on MSVC targets. Although these
826 // instructions are meant to work for all targets, as of the time of this
827 // writing, however, LLVM does not recommend the usage of these new instructions
828 // as the old ones are still more optimized.
830 bx: &mut Builder<'a, 'll, 'tcx>,
833 local_ptr: &'ll Value,
836 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
837 bx.set_personality_fn(bx.eh_personality());
840 let mut normal = bx.build_sibling_block("normal");
841 let mut catchswitch = bx.build_sibling_block("catchswitch");
842 let mut catchpad = bx.build_sibling_block("catchpad");
843 let mut caught = bx.build_sibling_block("caught");
845 let func = llvm::get_param(bx.llfn(), 0);
846 let data = llvm::get_param(bx.llfn(), 1);
847 let local_ptr = llvm::get_param(bx.llfn(), 2);
849 // We're generating an IR snippet that looks like:
851 // declare i32 @rust_try(%func, %data, %ptr) {
852 // %slot = alloca [2 x i64]
853 // invoke %func(%data) to label %normal unwind label %catchswitch
859 // %cs = catchswitch within none [%catchpad] unwind to caller
862 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
863 // %ptr[0] = %slot[0]
864 // %ptr[1] = %slot[1]
865 // catchret from %tok to label %caught
871 // This structure follows the basic usage of throw/try/catch in LLVM.
872 // For example, compile this C++ snippet to see what LLVM generates:
874 // #include <stdint.h>
876 // struct rust_panic {
880 // int bar(void (*foo)(void), uint64_t *ret) {
884 // } catch(rust_panic a) {
891 // More information can be found in libstd's seh.rs implementation.
892 let i64_2 = bx.type_array(bx.type_i64(), 2);
893 let i64_align = bx.tcx().data_layout.i64_align.abi;
894 let slot = bx.alloca(i64_2, i64_align);
895 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
897 normal.ret(bx.const_i32(0));
899 let cs = catchswitch.catch_switch(None, None, 1);
900 catchswitch.add_handler(cs, catchpad.llbb());
902 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
903 Some(did) => bx.get_static(did),
904 None => bug!("eh_catch_typeinfo not defined, but needed for SEH unwinding"),
906 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
908 let payload = catchpad.load(slot, i64_align);
909 let local_ptr = catchpad.bitcast(local_ptr, bx.type_ptr_to(i64_2));
910 catchpad.store(payload, local_ptr, i64_align);
911 catchpad.catch_ret(&funclet, caught.llbb());
913 caught.ret(bx.const_i32(1));
916 // Note that no invoke is used here because by definition this function
917 // can't panic (that's what it's catching).
918 let ret = bx.call(llfn, &[func, data, local_ptr], None);
919 let i32_align = bx.tcx().data_layout.i32_align.abi;
920 bx.store(ret, dest, i32_align);
923 // Definition of the standard `try` function for Rust using the GNU-like model
924 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
927 // This codegen is a little surprising because we always call a shim
928 // function instead of inlining the call to `invoke` manually here. This is done
929 // because in LLVM we're only allowed to have one personality per function
930 // definition. The call to the `try` intrinsic is being inlined into the
931 // function calling it, and that function may already have other personality
932 // functions in play. By calling a shim we're guaranteed that our shim will have
933 // the right personality function.
935 bx: &mut Builder<'a, 'll, 'tcx>,
938 local_ptr: &'ll Value,
941 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
942 // Codegens the shims described above:
945 // invoke %func(%args...) normal %normal unwind %catch
951 // (ptr, _) = landingpad
952 // store ptr, %local_ptr
955 // Note that the `local_ptr` data passed into the `try` intrinsic is
956 // expected to be `*mut *mut u8` for this to actually work, but that's
957 // managed by the standard library.
961 let mut then = bx.build_sibling_block("then");
962 let mut catch = bx.build_sibling_block("catch");
964 let func = llvm::get_param(bx.llfn(), 0);
965 let data = llvm::get_param(bx.llfn(), 1);
966 let local_ptr = llvm::get_param(bx.llfn(), 2);
967 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
968 then.ret(bx.const_i32(0));
970 // Type indicator for the exception being thrown.
972 // The first value in this tuple is a pointer to the exception object
973 // being thrown. The second value is a "selector" indicating which of
974 // the landing pad clauses the exception's type had been matched to.
975 // rust_try ignores the selector.
976 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
977 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
978 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
980 let tydesc = bx.get_static(tydesc);
981 bx.bitcast(tydesc, bx.type_i8p())
983 None => bx.const_null(bx.type_i8p()),
985 catch.add_clause(vals, tydesc);
986 let ptr = catch.extract_value(vals, 0);
987 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
988 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
989 catch.store(ptr, bitcast, ptr_align);
990 catch.ret(bx.const_i32(1));
993 // Note that no invoke is used here because by definition this function
994 // can't panic (that's what it's catching).
995 let ret = bx.call(llfn, &[func, data, local_ptr], None);
996 let i32_align = bx.tcx().data_layout.i32_align.abi;
997 bx.store(ret, dest, i32_align);
1000 // Helper function to give a Block to a closure to codegen a shim function.
1001 // This is currently primarily used for the `try` intrinsic functions above.
1002 fn gen_fn<'ll, 'tcx>(
1003 cx: &CodegenCx<'ll, 'tcx>,
1005 inputs: Vec<Ty<'tcx>>,
1007 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1009 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1013 hir::Unsafety::Unsafe,
1016 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1017 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
1018 let bx = Builder::new_block(cx, llfn, "entry-block");
1023 // Helper function used to get a handle to the `__rust_try` function used to
1024 // catch exceptions.
1026 // This function is only generated once and is then cached.
1027 fn get_rust_try_fn<'ll, 'tcx>(
1028 cx: &CodegenCx<'ll, 'tcx>,
1029 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1031 if let Some(llfn) = cx.rust_try_fn.get() {
1035 // Define the type up front for the signature of the rust_try function.
1037 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1038 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1042 hir::Unsafety::Unsafe,
1045 let output = tcx.types.i32;
1046 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1047 cx.rust_try_fn.set(Some(rust_try));
1051 fn generic_simd_intrinsic(
1052 bx: &mut Builder<'a, 'll, 'tcx>,
1054 callee_ty: Ty<'tcx>,
1055 args: &[OperandRef<'tcx, &'ll Value>],
1057 llret_ty: &'ll Type,
1059 ) -> Result<&'ll Value, ()> {
1060 // macros for error handling:
1061 macro_rules! emit_error {
1065 ($msg: tt, $($fmt: tt)*) => {
1066 span_invalid_monomorphization_error(
1068 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1073 macro_rules! return_error {
1076 emit_error!($($fmt)*);
1082 macro_rules! require {
1083 ($cond: expr, $($fmt: tt)*) => {
1085 return_error!($($fmt)*);
1090 macro_rules! require_simd {
1091 ($ty: expr, $position: expr) => {
1092 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1097 let sig = tcx.normalize_erasing_late_bound_regions(
1098 ty::ParamEnv::reveal_all(),
1099 &callee_ty.fn_sig(tcx),
1101 let arg_tys = sig.inputs();
1103 if name == "simd_select_bitmask" {
1104 let in_ty = arg_tys[0];
1105 let m_len = match in_ty.kind {
1106 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1107 // of intentional as there's not currently a use case for that.
1108 ty::Int(i) => i.bit_width().unwrap() as u64,
1109 ty::Uint(i) => i.bit_width().unwrap() as u64,
1110 _ => return_error!("`{}` is not an integral type", in_ty),
1112 require_simd!(arg_tys[1], "argument");
1113 let v_len = arg_tys[1].simd_size(tcx);
1114 require!(m_len == v_len,
1115 "mismatched lengths: mask length `{}` != other vector length `{}`",
1118 let i1 = bx.type_i1();
1119 let i1xn = bx.type_vector(i1, m_len);
1120 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1121 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1124 // every intrinsic below takes a SIMD vector as its first argument
1125 require_simd!(arg_tys[0], "input");
1126 let in_ty = arg_tys[0];
1127 let in_elem = arg_tys[0].simd_type(tcx);
1128 let in_len = arg_tys[0].simd_size(tcx);
1130 let comparison = match name {
1131 "simd_eq" => Some(hir::BinOpKind::Eq),
1132 "simd_ne" => Some(hir::BinOpKind::Ne),
1133 "simd_lt" => Some(hir::BinOpKind::Lt),
1134 "simd_le" => Some(hir::BinOpKind::Le),
1135 "simd_gt" => Some(hir::BinOpKind::Gt),
1136 "simd_ge" => Some(hir::BinOpKind::Ge),
1140 if let Some(cmp_op) = comparison {
1141 require_simd!(ret_ty, "return");
1143 let out_len = ret_ty.simd_size(tcx);
1144 require!(in_len == out_len,
1145 "expected return type with length {} (same as input type `{}`), \
1146 found `{}` with length {}",
1149 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1150 "expected return type with integer elements, found `{}` with non-integer `{}`",
1152 ret_ty.simd_type(tcx));
1154 return Ok(compare_simd_types(bx,
1155 args[0].immediate(),
1156 args[1].immediate(),
1162 if name.starts_with("simd_shuffle") {
1163 let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1164 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1166 require_simd!(ret_ty, "return");
1168 let out_len = ret_ty.simd_size(tcx);
1169 require!(out_len == n,
1170 "expected return type of length {}, found `{}` with length {}",
1171 n, ret_ty, out_len);
1172 require!(in_elem == ret_ty.simd_type(tcx),
1173 "expected return element type `{}` (element of input `{}`), \
1174 found `{}` with element type `{}`",
1176 ret_ty, ret_ty.simd_type(tcx));
1178 let total_len = u128::from(in_len) * 2;
1180 let vector = args[2].immediate();
1182 let indices: Option<Vec<_>> = (0..n)
1185 let val = bx.const_get_elt(vector, i as u64);
1186 match bx.const_to_opt_u128(val, true) {
1188 emit_error!("shuffle index #{} is not a constant", arg_idx);
1191 Some(idx) if idx >= total_len => {
1192 emit_error!("shuffle index #{} is out of bounds (limit {})",
1193 arg_idx, total_len);
1196 Some(idx) => Some(bx.const_i32(idx as i32)),
1200 let indices = match indices {
1202 None => return Ok(bx.const_null(llret_ty))
1205 return Ok(bx.shuffle_vector(args[0].immediate(),
1206 args[1].immediate(),
1207 bx.const_vector(&indices)))
1210 if name == "simd_insert" {
1211 require!(in_elem == arg_tys[2],
1212 "expected inserted type `{}` (element of input `{}`), found `{}`",
1213 in_elem, in_ty, arg_tys[2]);
1214 return Ok(bx.insert_element(args[0].immediate(),
1215 args[2].immediate(),
1216 args[1].immediate()))
1218 if name == "simd_extract" {
1219 require!(ret_ty == in_elem,
1220 "expected return type `{}` (element of input `{}`), found `{}`",
1221 in_elem, in_ty, ret_ty);
1222 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1225 if name == "simd_select" {
1226 let m_elem_ty = in_elem;
1228 require_simd!(arg_tys[1], "argument");
1229 let v_len = arg_tys[1].simd_size(tcx);
1230 require!(m_len == v_len,
1231 "mismatched lengths: mask length `{}` != other vector length `{}`",
1234 match m_elem_ty.kind {
1236 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1238 // truncate the mask to a vector of i1s
1239 let i1 = bx.type_i1();
1240 let i1xn = bx.type_vector(i1, m_len as u64);
1241 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1242 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1245 if name == "simd_bitmask" {
1246 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1247 // vector mask and returns an unsigned integer containing the most
1248 // significant bit (MSB) of each lane.
1250 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1252 let expected_int_bits = in_len.max(8);
1254 ty::Uint(i) if i.bit_width() == Some(expected_int_bits as usize) => (),
1256 "bitmask `{}`, expected `u{}`",
1257 ret_ty, expected_int_bits
1261 // Integer vector <i{in_bitwidth} x in_len>:
1262 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1264 args[0].immediate(),
1265 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1268 args[0].immediate(),
1269 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1272 "vector argument `{}`'s element type `{}`, expected integer element type",
1277 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1278 let shift_indices = vec![
1279 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _);
1282 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1283 // Truncate vector to an <i1 x N>
1284 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1285 // Bitcast <i1 x N> to iN:
1286 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1287 // Zero-extend iN to the bitmask type:
1288 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1291 fn simd_simple_float_intrinsic(
1293 in_elem: &::rustc::ty::TyS<'_>,
1294 in_ty: &::rustc::ty::TyS<'_>,
1296 bx: &mut Builder<'a, 'll, 'tcx>,
1298 args: &[OperandRef<'tcx, &'ll Value>],
1299 ) -> Result<&'ll Value, ()> {
1300 macro_rules! emit_error {
1304 ($msg: tt, $($fmt: tt)*) => {
1305 span_invalid_monomorphization_error(
1307 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1311 macro_rules! return_error {
1314 emit_error!($($fmt)*);
1319 let ety = match in_elem.kind {
1320 ty::Float(f) if f.bit_width() == 32 => {
1321 if in_len < 2 || in_len > 16 {
1323 "unsupported floating-point vector `{}` with length `{}` \
1324 out-of-range [2, 16]",
1329 ty::Float(f) if f.bit_width() == 64 => {
1330 if in_len < 2 || in_len > 8 {
1331 return_error!("unsupported floating-point vector `{}` with length `{}` \
1332 out-of-range [2, 8]",
1338 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1339 f.name_str(), in_ty);
1342 return_error!("`{}` is not a floating-point type", in_ty);
1346 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1347 let intrinsic = bx.get_intrinsic(&llvm_name);
1348 let c = bx.call(intrinsic,
1349 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1351 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1357 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1360 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1363 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1366 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1369 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1372 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1375 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1378 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1381 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1384 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1387 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1390 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1393 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1396 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1398 _ => { /* fallthrough */ }
1402 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1403 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1404 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1405 let p0s: String = "p0".repeat(no_pointers);
1406 match elem_ty.kind {
1407 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1408 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1409 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1410 _ => unreachable!(),
1414 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64,
1415 mut no_pointers: usize) -> &'ll Type {
1416 // FIXME: use cx.layout_of(ty).llvm_type() ?
1417 let mut elem_ty = match elem_ty.kind {
1418 ty::Int(v) => cx.type_int_from_ty( v),
1419 ty::Uint(v) => cx.type_uint_from_ty( v),
1420 ty::Float(v) => cx.type_float_from_ty( v),
1421 _ => unreachable!(),
1423 while no_pointers > 0 {
1424 elem_ty = cx.type_ptr_to(elem_ty);
1427 cx.type_vector(elem_ty, vec_len)
1431 if name == "simd_gather" {
1432 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1433 // mask: <N x i{M}>) -> <N x T>
1434 // * N: number of elements in the input vectors
1435 // * T: type of the element to load
1436 // * M: any integer width is supported, will be truncated to i1
1438 // All types must be simd vector types
1439 require_simd!(in_ty, "first");
1440 require_simd!(arg_tys[1], "second");
1441 require_simd!(arg_tys[2], "third");
1442 require_simd!(ret_ty, "return");
1444 // Of the same length:
1445 require!(in_len == arg_tys[1].simd_size(tcx),
1446 "expected {} argument with length {} (same as input type `{}`), \
1447 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1448 arg_tys[1].simd_size(tcx));
1449 require!(in_len == arg_tys[2].simd_size(tcx),
1450 "expected {} argument with length {} (same as input type `{}`), \
1451 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1452 arg_tys[2].simd_size(tcx));
1454 // The return type must match the first argument type
1455 require!(ret_ty == in_ty,
1456 "expected return type `{}`, found `{}`",
1459 // This counts how many pointers
1460 fn ptr_count(t: Ty<'_>) -> usize {
1462 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1468 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1470 ty::RawPtr(p) => non_ptr(p.ty),
1475 // The second argument must be a simd vector with an element type that's a pointer
1476 // to the element type of the first argument
1477 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1478 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1479 non_ptr(arg_tys[1].simd_type(tcx))),
1481 require!(false, "expected element type `{}` of second argument `{}` \
1482 to be a pointer to the element type `{}` of the first \
1483 argument `{}`, found `{}` != `*_ {}`",
1484 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1485 arg_tys[1].simd_type(tcx), in_elem);
1489 assert!(pointer_count > 0);
1490 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1491 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1493 // The element type of the third argument must be a signed integer type of any width:
1494 match arg_tys[2].simd_type(tcx).kind {
1497 require!(false, "expected element type `{}` of third argument `{}` \
1498 to be a signed integer type",
1499 arg_tys[2].simd_type(tcx), arg_tys[2]);
1503 // Alignment of T, must be a constant integer value:
1504 let alignment_ty = bx.type_i32();
1505 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1507 // Truncate the mask vector to a vector of i1s:
1508 let (mask, mask_ty) = {
1509 let i1 = bx.type_i1();
1510 let i1xn = bx.type_vector(i1, in_len);
1511 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1514 // Type of the vector of pointers:
1515 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1516 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1518 // Type of the vector of elements:
1519 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1520 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1522 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1523 llvm_elem_vec_str, llvm_pointer_vec_str);
1524 let f = bx.declare_cfn(&llvm_intrinsic,
1526 llvm_pointer_vec_ty,
1529 llvm_elem_vec_ty], llvm_elem_vec_ty));
1530 llvm::SetUnnamedAddr(f, false);
1531 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1536 if name == "simd_scatter" {
1537 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1538 // mask: <N x i{M}>) -> ()
1539 // * N: number of elements in the input vectors
1540 // * T: type of the element to load
1541 // * M: any integer width is supported, will be truncated to i1
1543 // All types must be simd vector types
1544 require_simd!(in_ty, "first");
1545 require_simd!(arg_tys[1], "second");
1546 require_simd!(arg_tys[2], "third");
1548 // Of the same length:
1549 require!(in_len == arg_tys[1].simd_size(tcx),
1550 "expected {} argument with length {} (same as input type `{}`), \
1551 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1552 arg_tys[1].simd_size(tcx));
1553 require!(in_len == arg_tys[2].simd_size(tcx),
1554 "expected {} argument with length {} (same as input type `{}`), \
1555 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1556 arg_tys[2].simd_size(tcx));
1558 // This counts how many pointers
1559 fn ptr_count(t: Ty<'_>) -> usize {
1561 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1567 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1569 ty::RawPtr(p) => non_ptr(p.ty),
1574 // The second argument must be a simd vector with an element type that's a pointer
1575 // to the element type of the first argument
1576 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1577 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mutable
1578 => (ptr_count(arg_tys[1].simd_type(tcx)),
1579 non_ptr(arg_tys[1].simd_type(tcx))),
1581 require!(false, "expected element type `{}` of second argument `{}` \
1582 to be a pointer to the element type `{}` of the first \
1583 argument `{}`, found `{}` != `*mut {}`",
1584 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1585 arg_tys[1].simd_type(tcx), in_elem);
1589 assert!(pointer_count > 0);
1590 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1591 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1593 // The element type of the third argument must be a signed integer type of any width:
1594 match arg_tys[2].simd_type(tcx).kind {
1597 require!(false, "expected element type `{}` of third argument `{}` \
1598 to be a signed integer type",
1599 arg_tys[2].simd_type(tcx), arg_tys[2]);
1603 // Alignment of T, must be a constant integer value:
1604 let alignment_ty = bx.type_i32();
1605 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1607 // Truncate the mask vector to a vector of i1s:
1608 let (mask, mask_ty) = {
1609 let i1 = bx.type_i1();
1610 let i1xn = bx.type_vector(i1, in_len);
1611 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1614 let ret_t = bx.type_void();
1616 // Type of the vector of pointers:
1617 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1618 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1620 // Type of the vector of elements:
1621 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1622 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1624 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1625 llvm_elem_vec_str, llvm_pointer_vec_str);
1626 let f = bx.declare_cfn(&llvm_intrinsic,
1627 bx.type_func(&[llvm_elem_vec_ty,
1628 llvm_pointer_vec_ty,
1631 llvm::SetUnnamedAddr(f, false);
1632 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1637 macro_rules! arith_red {
1638 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1640 require!(ret_ty == in_elem,
1641 "expected return type `{}` (element of input `{}`), found `{}`",
1642 in_elem, in_ty, ret_ty);
1643 return match in_elem.kind {
1644 ty::Int(_) | ty::Uint(_) => {
1645 let r = bx.$integer_reduce(args[0].immediate());
1647 // if overflow occurs, the result is the
1648 // mathematical result modulo 2^n:
1649 if name.contains("mul") {
1650 Ok(bx.mul(args[1].immediate(), r))
1652 Ok(bx.add(args[1].immediate(), r))
1655 Ok(bx.$integer_reduce(args[0].immediate()))
1659 let acc = if $ordered {
1660 // ordered arithmetic reductions take an accumulator
1663 // unordered arithmetic reductions use the identity accumulator
1664 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1665 match f.bit_width() {
1666 32 => bx.const_real(bx.type_f32(), identity_acc),
1667 64 => bx.const_real(bx.type_f64(), identity_acc),
1670 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1671 $name, in_ty, in_elem, v, ret_ty
1676 Ok(bx.$float_reduce(acc, args[0].immediate()))
1680 "unsupported {} from `{}` with element `{}` to `{}`",
1681 $name, in_ty, in_elem, ret_ty
1689 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1690 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1691 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1692 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1694 macro_rules! minmax_red {
1695 ($name:tt: $int_red:ident, $float_red:ident) => {
1697 require!(ret_ty == in_elem,
1698 "expected return type `{}` (element of input `{}`), found `{}`",
1699 in_elem, in_ty, ret_ty);
1700 return match in_elem.kind {
1702 Ok(bx.$int_red(args[0].immediate(), true))
1705 Ok(bx.$int_red(args[0].immediate(), false))
1708 Ok(bx.$float_red(args[0].immediate()))
1711 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1712 $name, in_ty, in_elem, ret_ty)
1720 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1721 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1723 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1724 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1726 macro_rules! bitwise_red {
1727 ($name:tt : $red:ident, $boolean:expr) => {
1729 let input = if !$boolean {
1730 require!(ret_ty == in_elem,
1731 "expected return type `{}` (element of input `{}`), found `{}`",
1732 in_elem, in_ty, ret_ty);
1735 match in_elem.kind {
1736 ty::Int(_) | ty::Uint(_) => {},
1738 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1739 $name, in_ty, in_elem, ret_ty)
1743 // boolean reductions operate on vectors of i1s:
1744 let i1 = bx.type_i1();
1745 let i1xn = bx.type_vector(i1, in_len as u64);
1746 bx.trunc(args[0].immediate(), i1xn)
1748 return match in_elem.kind {
1749 ty::Int(_) | ty::Uint(_) => {
1750 let r = bx.$red(input);
1755 bx.zext(r, bx.type_bool())
1760 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1761 $name, in_ty, in_elem, ret_ty)
1768 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1769 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1770 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1771 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1772 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1774 if name == "simd_cast" {
1775 require_simd!(ret_ty, "return");
1776 let out_len = ret_ty.simd_size(tcx);
1777 require!(in_len == out_len,
1778 "expected return type with length {} (same as input type `{}`), \
1779 found `{}` with length {}",
1782 // casting cares about nominal type, not just structural type
1783 let out_elem = ret_ty.simd_type(tcx);
1785 if in_elem == out_elem { return Ok(args[0].immediate()); }
1787 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1789 let (in_style, in_width) = match in_elem.kind {
1790 // vectors of pointer-sized integers should've been
1791 // disallowed before here, so this unwrap is safe.
1792 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1793 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1794 ty::Float(f) => (Style::Float, f.bit_width()),
1795 _ => (Style::Unsupported, 0)
1797 let (out_style, out_width) = match out_elem.kind {
1798 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1799 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1800 ty::Float(f) => (Style::Float, f.bit_width()),
1801 _ => (Style::Unsupported, 0)
1804 match (in_style, out_style) {
1805 (Style::Int(in_is_signed), Style::Int(_)) => {
1806 return Ok(match in_width.cmp(&out_width) {
1807 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1808 Ordering::Equal => args[0].immediate(),
1809 Ordering::Less => if in_is_signed {
1810 bx.sext(args[0].immediate(), llret_ty)
1812 bx.zext(args[0].immediate(), llret_ty)
1816 (Style::Int(in_is_signed), Style::Float) => {
1817 return Ok(if in_is_signed {
1818 bx.sitofp(args[0].immediate(), llret_ty)
1820 bx.uitofp(args[0].immediate(), llret_ty)
1823 (Style::Float, Style::Int(out_is_signed)) => {
1824 return Ok(if out_is_signed {
1825 bx.fptosi(args[0].immediate(), llret_ty)
1827 bx.fptoui(args[0].immediate(), llret_ty)
1830 (Style::Float, Style::Float) => {
1831 return Ok(match in_width.cmp(&out_width) {
1832 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1833 Ordering::Equal => args[0].immediate(),
1834 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1837 _ => {/* Unsupported. Fallthrough. */}
1840 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1844 macro_rules! arith {
1845 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1846 $(if name == stringify!($name) {
1847 match in_elem.kind {
1848 $($(ty::$p(_))|* => {
1849 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1854 "unsupported operation on `{}` with element `{}`",
1861 simd_add: Uint, Int => add, Float => fadd;
1862 simd_sub: Uint, Int => sub, Float => fsub;
1863 simd_mul: Uint, Int => mul, Float => fmul;
1864 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1865 simd_rem: Uint => urem, Int => srem, Float => frem;
1866 simd_shl: Uint, Int => shl;
1867 simd_shr: Uint => lshr, Int => ashr;
1868 simd_and: Uint, Int => and;
1869 simd_or: Uint, Int => or;
1870 simd_xor: Uint, Int => xor;
1871 simd_fmax: Float => maxnum;
1872 simd_fmin: Float => minnum;
1876 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1877 let lhs = args[0].immediate();
1878 let rhs = args[1].immediate();
1879 let is_add = name == "simd_saturating_add";
1880 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1881 let (signed, elem_width, elem_ty) = match in_elem.kind {
1885 i.bit_width().unwrap_or(ptr_bits),
1886 bx.cx.type_int_from_ty(i)
1891 i.bit_width().unwrap_or(ptr_bits),
1892 bx.cx.type_uint_from_ty(i)
1896 "expected element type `{}` of vector type `{}` \
1897 to be a signed or unsigned integer type",
1898 arg_tys[0].simd_type(tcx), arg_tys[0]
1902 let llvm_intrinsic = &format!(
1903 "llvm.{}{}.sat.v{}i{}",
1904 if signed { 's' } else { 'u' },
1905 if is_add { "add" } else { "sub" },
1908 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1910 let f = bx.declare_cfn(
1912 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1914 llvm::SetUnnamedAddr(f, false);
1915 let v = bx.call(f, &[lhs, rhs], None);
1919 span_bug!(span, "unknown SIMD intrinsic");
1922 // Returns the width of an int Ty, and if it's signed or not
1923 // Returns None if the type is not an integer
1924 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1926 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1928 ty::Int(t) => Some((match t {
1929 ast::IntTy::Isize => cx.tcx.sess.target.ptr_width as u64,
1930 ast::IntTy::I8 => 8,
1931 ast::IntTy::I16 => 16,
1932 ast::IntTy::I32 => 32,
1933 ast::IntTy::I64 => 64,
1934 ast::IntTy::I128 => 128,
1936 ty::Uint(t) => Some((match t {
1937 ast::UintTy::Usize => cx.tcx.sess.target.ptr_width as u64,
1938 ast::UintTy::U8 => 8,
1939 ast::UintTy::U16 => 16,
1940 ast::UintTy::U32 => 32,
1941 ast::UintTy::U64 => 64,
1942 ast::UintTy::U128 => 128,
1948 // Returns the width of a float Ty
1949 // Returns None if the type is not a float
1950 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1952 ty::Float(t) => Some(t.bit_width() as u64),