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::{FloatTy, 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)
166 Primitive::Float(FloatTy::F64) |
167 Primitive::Pointer => {
168 emit_va_arg(self, args[0], ret_ty)
170 // `va_arg` should never be used with the return type f32.
171 Primitive::Float(FloatTy::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(),
1109 ty::Uint(i) => i.bit_width().unwrap(),
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 as u64);
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: usize = 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 = in_len as u128 * 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) => (),
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 _); in_len
1281 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1282 // Truncate vector to an <i1 x N>
1283 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1284 // Bitcast <i1 x N> to iN:
1285 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1286 // Zero-extend iN to the bitmask type:
1287 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1290 fn simd_simple_float_intrinsic(
1292 in_elem: &::rustc::ty::TyS<'_>,
1293 in_ty: &::rustc::ty::TyS<'_>,
1295 bx: &mut Builder<'a, 'll, 'tcx>,
1297 args: &[OperandRef<'tcx, &'ll Value>],
1298 ) -> Result<&'ll Value, ()> {
1299 macro_rules! emit_error {
1303 ($msg: tt, $($fmt: tt)*) => {
1304 span_invalid_monomorphization_error(
1306 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1310 macro_rules! return_error {
1313 emit_error!($($fmt)*);
1318 let ety = match in_elem.kind {
1319 ty::Float(f) if f.bit_width() == 32 => {
1320 if in_len < 2 || in_len > 16 {
1322 "unsupported floating-point vector `{}` with length `{}` \
1323 out-of-range [2, 16]",
1328 ty::Float(f) if f.bit_width() == 64 => {
1329 if in_len < 2 || in_len > 8 {
1330 return_error!("unsupported floating-point vector `{}` with length `{}` \
1331 out-of-range [2, 8]",
1337 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1338 f.name_str(), in_ty);
1341 return_error!("`{}` is not a floating-point type", in_ty);
1345 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1346 let intrinsic = bx.get_intrinsic(&llvm_name);
1347 let c = bx.call(intrinsic,
1348 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1350 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1356 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1359 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1362 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1365 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1368 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1371 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1374 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1377 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1380 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1383 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1386 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1389 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1392 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1395 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1397 _ => { /* fallthrough */ }
1401 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1402 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1403 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: usize, no_pointers: usize) -> String {
1404 let p0s: String = "p0".repeat(no_pointers);
1405 match elem_ty.kind {
1406 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1407 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1408 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1409 _ => unreachable!(),
1413 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: usize,
1414 mut no_pointers: usize) -> &'ll Type {
1415 // FIXME: use cx.layout_of(ty).llvm_type() ?
1416 let mut elem_ty = match elem_ty.kind {
1417 ty::Int(v) => cx.type_int_from_ty( v),
1418 ty::Uint(v) => cx.type_uint_from_ty( v),
1419 ty::Float(v) => cx.type_float_from_ty( v),
1420 _ => unreachable!(),
1422 while no_pointers > 0 {
1423 elem_ty = cx.type_ptr_to(elem_ty);
1426 cx.type_vector(elem_ty, vec_len as u64)
1430 if name == "simd_gather" {
1431 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1432 // mask: <N x i{M}>) -> <N x T>
1433 // * N: number of elements in the input vectors
1434 // * T: type of the element to load
1435 // * M: any integer width is supported, will be truncated to i1
1437 // All types must be simd vector types
1438 require_simd!(in_ty, "first");
1439 require_simd!(arg_tys[1], "second");
1440 require_simd!(arg_tys[2], "third");
1441 require_simd!(ret_ty, "return");
1443 // Of the same length:
1444 require!(in_len == arg_tys[1].simd_size(tcx),
1445 "expected {} argument with length {} (same as input type `{}`), \
1446 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1447 arg_tys[1].simd_size(tcx));
1448 require!(in_len == arg_tys[2].simd_size(tcx),
1449 "expected {} argument with length {} (same as input type `{}`), \
1450 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1451 arg_tys[2].simd_size(tcx));
1453 // The return type must match the first argument type
1454 require!(ret_ty == in_ty,
1455 "expected return type `{}`, found `{}`",
1458 // This counts how many pointers
1459 fn ptr_count(t: Ty<'_>) -> usize {
1461 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1467 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1469 ty::RawPtr(p) => non_ptr(p.ty),
1474 // The second argument must be a simd vector with an element type that's a pointer
1475 // to the element type of the first argument
1476 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1477 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1478 non_ptr(arg_tys[1].simd_type(tcx))),
1480 require!(false, "expected element type `{}` of second argument `{}` \
1481 to be a pointer to the element type `{}` of the first \
1482 argument `{}`, found `{}` != `*_ {}`",
1483 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1484 arg_tys[1].simd_type(tcx), in_elem);
1488 assert!(pointer_count > 0);
1489 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1490 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1492 // The element type of the third argument must be a signed integer type of any width:
1493 match arg_tys[2].simd_type(tcx).kind {
1496 require!(false, "expected element type `{}` of third argument `{}` \
1497 to be a signed integer type",
1498 arg_tys[2].simd_type(tcx), arg_tys[2]);
1502 // Alignment of T, must be a constant integer value:
1503 let alignment_ty = bx.type_i32();
1504 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1506 // Truncate the mask vector to a vector of i1s:
1507 let (mask, mask_ty) = {
1508 let i1 = bx.type_i1();
1509 let i1xn = bx.type_vector(i1, in_len as u64);
1510 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1513 // Type of the vector of pointers:
1514 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1515 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1517 // Type of the vector of elements:
1518 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1519 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1521 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1522 llvm_elem_vec_str, llvm_pointer_vec_str);
1523 let f = bx.declare_cfn(&llvm_intrinsic,
1525 llvm_pointer_vec_ty,
1528 llvm_elem_vec_ty], llvm_elem_vec_ty));
1529 llvm::SetUnnamedAddr(f, false);
1530 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1535 if name == "simd_scatter" {
1536 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1537 // mask: <N x i{M}>) -> ()
1538 // * N: number of elements in the input vectors
1539 // * T: type of the element to load
1540 // * M: any integer width is supported, will be truncated to i1
1542 // All types must be simd vector types
1543 require_simd!(in_ty, "first");
1544 require_simd!(arg_tys[1], "second");
1545 require_simd!(arg_tys[2], "third");
1547 // Of the same length:
1548 require!(in_len == arg_tys[1].simd_size(tcx),
1549 "expected {} argument with length {} (same as input type `{}`), \
1550 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1551 arg_tys[1].simd_size(tcx));
1552 require!(in_len == arg_tys[2].simd_size(tcx),
1553 "expected {} argument with length {} (same as input type `{}`), \
1554 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1555 arg_tys[2].simd_size(tcx));
1557 // This counts how many pointers
1558 fn ptr_count(t: Ty<'_>) -> usize {
1560 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1566 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1568 ty::RawPtr(p) => non_ptr(p.ty),
1573 // The second argument must be a simd vector with an element type that's a pointer
1574 // to the element type of the first argument
1575 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1576 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1577 => (ptr_count(arg_tys[1].simd_type(tcx)),
1578 non_ptr(arg_tys[1].simd_type(tcx))),
1580 require!(false, "expected element type `{}` of second argument `{}` \
1581 to be a pointer to the element type `{}` of the first \
1582 argument `{}`, found `{}` != `*mut {}`",
1583 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1584 arg_tys[1].simd_type(tcx), in_elem);
1588 assert!(pointer_count > 0);
1589 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1590 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1592 // The element type of the third argument must be a signed integer type of any width:
1593 match arg_tys[2].simd_type(tcx).kind {
1596 require!(false, "expected element type `{}` of third argument `{}` \
1597 to be a signed integer type",
1598 arg_tys[2].simd_type(tcx), arg_tys[2]);
1602 // Alignment of T, must be a constant integer value:
1603 let alignment_ty = bx.type_i32();
1604 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1606 // Truncate the mask vector to a vector of i1s:
1607 let (mask, mask_ty) = {
1608 let i1 = bx.type_i1();
1609 let i1xn = bx.type_vector(i1, in_len as u64);
1610 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1613 let ret_t = bx.type_void();
1615 // Type of the vector of pointers:
1616 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1617 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1619 // Type of the vector of elements:
1620 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1621 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1623 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1624 llvm_elem_vec_str, llvm_pointer_vec_str);
1625 let f = bx.declare_cfn(&llvm_intrinsic,
1626 bx.type_func(&[llvm_elem_vec_ty,
1627 llvm_pointer_vec_ty,
1630 llvm::SetUnnamedAddr(f, false);
1631 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1636 macro_rules! arith_red {
1637 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1639 require!(ret_ty == in_elem,
1640 "expected return type `{}` (element of input `{}`), found `{}`",
1641 in_elem, in_ty, ret_ty);
1642 return match in_elem.kind {
1643 ty::Int(_) | ty::Uint(_) => {
1644 let r = bx.$integer_reduce(args[0].immediate());
1646 // if overflow occurs, the result is the
1647 // mathematical result modulo 2^n:
1648 if name.contains("mul") {
1649 Ok(bx.mul(args[1].immediate(), r))
1651 Ok(bx.add(args[1].immediate(), r))
1654 Ok(bx.$integer_reduce(args[0].immediate()))
1658 let acc = if $ordered {
1659 // ordered arithmetic reductions take an accumulator
1662 // unordered arithmetic reductions use the identity accumulator
1663 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1664 match f.bit_width() {
1665 32 => bx.const_real(bx.type_f32(), identity_acc),
1666 64 => bx.const_real(bx.type_f64(), identity_acc),
1669 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1670 $name, in_ty, in_elem, v, ret_ty
1675 Ok(bx.$float_reduce(acc, args[0].immediate()))
1679 "unsupported {} from `{}` with element `{}` to `{}`",
1680 $name, in_ty, in_elem, ret_ty
1688 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1689 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1690 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1691 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1693 macro_rules! minmax_red {
1694 ($name:tt: $int_red:ident, $float_red:ident) => {
1696 require!(ret_ty == in_elem,
1697 "expected return type `{}` (element of input `{}`), found `{}`",
1698 in_elem, in_ty, ret_ty);
1699 return match in_elem.kind {
1701 Ok(bx.$int_red(args[0].immediate(), true))
1704 Ok(bx.$int_red(args[0].immediate(), false))
1707 Ok(bx.$float_red(args[0].immediate()))
1710 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1711 $name, in_ty, in_elem, ret_ty)
1719 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1720 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1722 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1723 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1725 macro_rules! bitwise_red {
1726 ($name:tt : $red:ident, $boolean:expr) => {
1728 let input = if !$boolean {
1729 require!(ret_ty == in_elem,
1730 "expected return type `{}` (element of input `{}`), found `{}`",
1731 in_elem, in_ty, ret_ty);
1734 match in_elem.kind {
1735 ty::Int(_) | ty::Uint(_) => {},
1737 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1738 $name, in_ty, in_elem, ret_ty)
1742 // boolean reductions operate on vectors of i1s:
1743 let i1 = bx.type_i1();
1744 let i1xn = bx.type_vector(i1, in_len as u64);
1745 bx.trunc(args[0].immediate(), i1xn)
1747 return match in_elem.kind {
1748 ty::Int(_) | ty::Uint(_) => {
1749 let r = bx.$red(input);
1754 bx.zext(r, bx.type_bool())
1759 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1760 $name, in_ty, in_elem, ret_ty)
1767 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1768 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1769 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1770 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1771 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1773 if name == "simd_cast" {
1774 require_simd!(ret_ty, "return");
1775 let out_len = ret_ty.simd_size(tcx);
1776 require!(in_len == out_len,
1777 "expected return type with length {} (same as input type `{}`), \
1778 found `{}` with length {}",
1781 // casting cares about nominal type, not just structural type
1782 let out_elem = ret_ty.simd_type(tcx);
1784 if in_elem == out_elem { return Ok(args[0].immediate()); }
1786 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1788 let (in_style, in_width) = match in_elem.kind {
1789 // vectors of pointer-sized integers should've been
1790 // disallowed before here, so this unwrap is safe.
1791 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1792 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1793 ty::Float(f) => (Style::Float, f.bit_width()),
1794 _ => (Style::Unsupported, 0)
1796 let (out_style, out_width) = match out_elem.kind {
1797 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1798 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1799 ty::Float(f) => (Style::Float, f.bit_width()),
1800 _ => (Style::Unsupported, 0)
1803 match (in_style, out_style) {
1804 (Style::Int(in_is_signed), Style::Int(_)) => {
1805 return Ok(match in_width.cmp(&out_width) {
1806 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1807 Ordering::Equal => args[0].immediate(),
1808 Ordering::Less => if in_is_signed {
1809 bx.sext(args[0].immediate(), llret_ty)
1811 bx.zext(args[0].immediate(), llret_ty)
1815 (Style::Int(in_is_signed), Style::Float) => {
1816 return Ok(if in_is_signed {
1817 bx.sitofp(args[0].immediate(), llret_ty)
1819 bx.uitofp(args[0].immediate(), llret_ty)
1822 (Style::Float, Style::Int(out_is_signed)) => {
1823 return Ok(if out_is_signed {
1824 bx.fptosi(args[0].immediate(), llret_ty)
1826 bx.fptoui(args[0].immediate(), llret_ty)
1829 (Style::Float, Style::Float) => {
1830 return Ok(match in_width.cmp(&out_width) {
1831 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1832 Ordering::Equal => args[0].immediate(),
1833 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1836 _ => {/* Unsupported. Fallthrough. */}
1839 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1843 macro_rules! arith {
1844 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1845 $(if name == stringify!($name) {
1846 match in_elem.kind {
1847 $($(ty::$p(_))|* => {
1848 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1853 "unsupported operation on `{}` with element `{}`",
1860 simd_add: Uint, Int => add, Float => fadd;
1861 simd_sub: Uint, Int => sub, Float => fsub;
1862 simd_mul: Uint, Int => mul, Float => fmul;
1863 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1864 simd_rem: Uint => urem, Int => srem, Float => frem;
1865 simd_shl: Uint, Int => shl;
1866 simd_shr: Uint => lshr, Int => ashr;
1867 simd_and: Uint, Int => and;
1868 simd_or: Uint, Int => or;
1869 simd_xor: Uint, Int => xor;
1870 simd_fmax: Float => maxnum;
1871 simd_fmin: Float => minnum;
1875 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1876 let lhs = args[0].immediate();
1877 let rhs = args[1].immediate();
1878 let is_add = name == "simd_saturating_add";
1879 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1880 let (signed, elem_width, elem_ty) = match in_elem.kind {
1884 i.bit_width().unwrap_or(ptr_bits),
1885 bx.cx.type_int_from_ty(i)
1890 i.bit_width().unwrap_or(ptr_bits),
1891 bx.cx.type_uint_from_ty(i)
1895 "expected element type `{}` of vector type `{}` \
1896 to be a signed or unsigned integer type",
1897 arg_tys[0].simd_type(tcx), arg_tys[0]
1901 let llvm_intrinsic = &format!(
1902 "llvm.{}{}.sat.v{}i{}",
1903 if signed { 's' } else { 'u' },
1904 if is_add { "add" } else { "sub" },
1907 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1909 let f = bx.declare_cfn(
1911 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1913 llvm::SetUnnamedAddr(f, false);
1914 let v = bx.call(f, &[lhs, rhs], None);
1918 span_bug!(span, "unknown SIMD intrinsic");
1921 // Returns the width of an int Ty, and if it's signed or not
1922 // Returns None if the type is not an integer
1923 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1925 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1927 ty::Int(t) => Some((match t {
1928 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1929 ast::IntTy::I8 => 8,
1930 ast::IntTy::I16 => 16,
1931 ast::IntTy::I32 => 32,
1932 ast::IntTy::I64 => 64,
1933 ast::IntTy::I128 => 128,
1935 ty::Uint(t) => Some((match t {
1936 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1937 ast::UintTy::U8 => 8,
1938 ast::UintTy::U16 => 16,
1939 ast::UintTy::U32 => 32,
1940 ast::UintTy::U64 => 64,
1941 ast::UintTy::U128 => 128,
1947 // Returns the width of a float Ty
1948 // Returns None if the type is not a float
1949 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1951 ty::Float(t) => Some(t.bit_width() as u64),