4 use crate::abi::{Abi, FnType, 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 syntax::ast::{self, FloatTy};
23 use rustc_codegen_ssa::traits::*;
25 use rustc::session::Session;
28 use std::cmp::Ordering;
29 use std::{iter, i128, u128};
31 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
32 let llvm_name = match name {
33 "sqrtf32" => "llvm.sqrt.f32",
34 "sqrtf64" => "llvm.sqrt.f64",
35 "powif32" => "llvm.powi.f32",
36 "powif64" => "llvm.powi.f64",
37 "sinf32" => "llvm.sin.f32",
38 "sinf64" => "llvm.sin.f64",
39 "cosf32" => "llvm.cos.f32",
40 "cosf64" => "llvm.cos.f64",
41 "powf32" => "llvm.pow.f32",
42 "powf64" => "llvm.pow.f64",
43 "expf32" => "llvm.exp.f32",
44 "expf64" => "llvm.exp.f64",
45 "exp2f32" => "llvm.exp2.f32",
46 "exp2f64" => "llvm.exp2.f64",
47 "logf32" => "llvm.log.f32",
48 "logf64" => "llvm.log.f64",
49 "log10f32" => "llvm.log10.f32",
50 "log10f64" => "llvm.log10.f64",
51 "log2f32" => "llvm.log2.f32",
52 "log2f64" => "llvm.log2.f64",
53 "fmaf32" => "llvm.fma.f32",
54 "fmaf64" => "llvm.fma.f64",
55 "fabsf32" => "llvm.fabs.f32",
56 "fabsf64" => "llvm.fabs.f64",
57 "minnumf32" => "llvm.minnum.f32",
58 "minnumf64" => "llvm.minnum.f64",
59 "maxnumf32" => "llvm.maxnum.f32",
60 "maxnumf64" => "llvm.maxnum.f64",
61 "copysignf32" => "llvm.copysign.f32",
62 "copysignf64" => "llvm.copysign.f64",
63 "floorf32" => "llvm.floor.f32",
64 "floorf64" => "llvm.floor.f64",
65 "ceilf32" => "llvm.ceil.f32",
66 "ceilf64" => "llvm.ceil.f64",
67 "truncf32" => "llvm.trunc.f32",
68 "truncf64" => "llvm.trunc.f64",
69 "rintf32" => "llvm.rint.f32",
70 "rintf64" => "llvm.rint.f64",
71 "nearbyintf32" => "llvm.nearbyint.f32",
72 "nearbyintf64" => "llvm.nearbyint.f64",
73 "roundf32" => "llvm.round.f32",
74 "roundf64" => "llvm.round.f64",
75 "assume" => "llvm.assume",
76 "abort" => "llvm.trap",
79 Some(cx.get_intrinsic(&llvm_name))
82 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
83 fn codegen_intrinsic_call(
85 instance: ty::Instance<'tcx>,
86 fn_ty: &FnType<'tcx, Ty<'tcx>>,
87 args: &[OperandRef<'tcx, &'ll Value>],
92 let callee_ty = instance.ty(tcx);
94 let (def_id, substs) = match callee_ty.sty {
95 ty::FnDef(def_id, substs) => (def_id, substs),
96 _ => bug!("expected fn item type, found {}", callee_ty)
99 let sig = callee_ty.fn_sig(tcx);
100 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
101 let arg_tys = sig.inputs();
102 let ret_ty = sig.output();
103 let name = &*tcx.item_name(def_id).as_str();
105 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
106 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout);
108 let simple = get_simple_intrinsic(self, name);
109 let llval = match name {
110 _ if simple.is_some() => {
111 self.call(simple.unwrap(),
112 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
119 let expect = self.get_intrinsic(&("llvm.expect.i1"));
120 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
123 let expect = self.get_intrinsic(&("llvm.expect.i1"));
124 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
135 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
136 self.call(llfn, &[], None)
139 self.va_start(args[0].immediate())
142 self.va_end(args[0].immediate())
145 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
146 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
149 match fn_ty.ret.layout.abi {
150 layout::Abi::Scalar(ref scalar) => {
152 Primitive::Int(..) => {
153 if self.cx().size_of(ret_ty).bytes() < 4 {
154 // va_arg should not be called on a integer type
155 // less than 4 bytes in length. If it is, promote
156 // the integer to a `i32` and truncate the result
157 // back to the smaller type.
158 let promoted_result = emit_va_arg(self, args[0],
160 self.trunc(promoted_result, llret_ty)
162 emit_va_arg(self, args[0], ret_ty)
165 Primitive::Float(FloatTy::F64) |
166 Primitive::Pointer => {
167 emit_va_arg(self, args[0], ret_ty)
169 // `va_arg` should never be used with the return type f32.
170 Primitive::Float(FloatTy::F32) => {
171 bug!("the va_arg intrinsic does not work with `f32`")
176 bug!("the va_arg intrinsic does not work with non-scalar types")
181 let tp_ty = substs.type_at(0);
182 if let OperandValue::Pair(_, meta) = args[0].val {
183 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
186 self.const_usize(self.size_of(tp_ty).bytes())
189 "min_align_of_val" => {
190 let tp_ty = substs.type_at(0);
191 if let OperandValue::Pair(_, meta) = args[0].val {
192 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
195 self.const_usize(self.align_of(tp_ty).bytes())
208 let ty_name = self.tcx.const_eval(ty::ParamEnv::reveal_all().and(gid)).unwrap();
209 OperandRef::from_const(self, ty_name).immediate_or_packed_pair(self)
212 let ty = substs.type_at(0);
213 if !self.layout_of(ty).is_zst() {
214 // Just zero out the stack slot.
215 // If we store a zero constant, LLVM will drown in vreg allocation for large
216 // data structures, and the generated code will be awful. (A telltale sign of
217 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
229 // Effectively no-ops
230 "uninit" | "forget" => {
234 let ptr = args[0].immediate();
235 let offset = args[1].immediate();
236 self.inbounds_gep(ptr, &[offset])
239 let ptr = args[0].immediate();
240 let offset = args[1].immediate();
241 self.gep(ptr, &[offset])
244 "copy_nonoverlapping" => {
245 copy_intrinsic(self, false, false, substs.type_at(0),
246 args[1].immediate(), args[0].immediate(), args[2].immediate());
250 copy_intrinsic(self, true, false, substs.type_at(0),
251 args[1].immediate(), args[0].immediate(), args[2].immediate());
255 memset_intrinsic(self, false, substs.type_at(0),
256 args[0].immediate(), args[1].immediate(), args[2].immediate());
260 "volatile_copy_nonoverlapping_memory" => {
261 copy_intrinsic(self, false, true, substs.type_at(0),
262 args[0].immediate(), args[1].immediate(), args[2].immediate());
265 "volatile_copy_memory" => {
266 copy_intrinsic(self, true, true, substs.type_at(0),
267 args[0].immediate(), args[1].immediate(), args[2].immediate());
270 "volatile_set_memory" => {
271 memset_intrinsic(self, true, substs.type_at(0),
272 args[0].immediate(), args[1].immediate(), args[2].immediate());
275 "volatile_load" | "unaligned_volatile_load" => {
276 let tp_ty = substs.type_at(0);
277 let mut ptr = args[0].immediate();
278 if let PassMode::Cast(ty) = fn_ty.ret.mode {
279 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
281 let load = self.volatile_load(ptr);
282 let align = if name == "unaligned_volatile_load" {
285 self.align_of(tp_ty).bytes() as u32
288 llvm::LLVMSetAlignment(load, align);
290 to_immediate(self, load, self.layout_of(tp_ty))
292 "volatile_store" => {
293 let dst = args[0].deref(self.cx());
294 args[1].val.volatile_store(self, dst);
297 "unaligned_volatile_store" => {
298 let dst = args[0].deref(self.cx());
299 args[1].val.unaligned_volatile_store(self, dst);
302 "prefetch_read_data" | "prefetch_write_data" |
303 "prefetch_read_instruction" | "prefetch_write_instruction" => {
304 let expect = self.get_intrinsic(&("llvm.prefetch"));
305 let (rw, cache_type) = match name {
306 "prefetch_read_data" => (0, 1),
307 "prefetch_write_data" => (1, 1),
308 "prefetch_read_instruction" => (0, 0),
309 "prefetch_write_instruction" => (1, 0),
316 self.const_i32(cache_type)
319 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
320 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
321 "mul_with_overflow" | "wrapping_add" | "wrapping_sub" | "wrapping_mul" |
322 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" |
323 "unchecked_add" | "unchecked_sub" | "unchecked_mul" | "exact_div" |
324 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
326 match int_type_width_signed(ty, self) {
327 Some((width, signed)) =>
330 let y = self.const_bool(false);
331 let llfn = self.get_intrinsic(
332 &format!("llvm.{}.i{}", name, width),
334 self.call(llfn, &[args[0].immediate(), y], None)
336 "ctlz_nonzero" | "cttz_nonzero" => {
337 let y = self.const_bool(true);
338 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
339 let llfn = self.get_intrinsic(llvm_name);
340 self.call(llfn, &[args[0].immediate(), y], None)
342 "ctpop" => self.call(
343 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
344 &[args[0].immediate()],
349 args[0].immediate() // byte swap a u8/i8 is just a no-op
353 &format!("llvm.bswap.i{}", width),
355 &[args[0].immediate()],
363 &format!("llvm.bitreverse.i{}", width),
365 &[args[0].immediate()],
369 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
370 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
371 if signed { 's' } else { 'u' },
373 let llfn = self.get_intrinsic(&intrinsic);
375 // Convert `i1` to a `bool`, and write it to the out parameter
376 let pair = self.call(llfn, &[
380 let val = self.extract_value(pair, 0);
381 let overflow = self.extract_value(pair, 1);
382 let overflow = self.zext(overflow, self.type_bool());
384 let dest = result.project_field(self, 0);
385 self.store(val, dest.llval, dest.align);
386 let dest = result.project_field(self, 1);
387 self.store(overflow, dest.llval, dest.align);
391 "wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
392 "wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
393 "wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
396 self.exactsdiv(args[0].immediate(), args[1].immediate())
398 self.exactudiv(args[0].immediate(), args[1].immediate())
402 self.sdiv(args[0].immediate(), args[1].immediate())
404 self.udiv(args[0].immediate(), args[1].immediate())
408 self.srem(args[0].immediate(), args[1].immediate())
410 self.urem(args[0].immediate(), args[1].immediate())
412 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
415 self.ashr(args[0].immediate(), args[1].immediate())
417 self.lshr(args[0].immediate(), args[1].immediate())
421 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
423 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
428 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
430 self.unchecked_usub(args[0].immediate(), args[1].immediate())
435 self.unchecked_smul(args[0].immediate(), args[1].immediate())
437 self.unchecked_umul(args[0].immediate(), args[1].immediate())
440 "rotate_left" | "rotate_right" => {
441 let is_left = name == "rotate_left";
442 let val = args[0].immediate();
443 let raw_shift = args[1].immediate();
444 if llvm_util::get_major_version() >= 7 {
445 // rotate = funnel shift with first two args the same
446 let llvm_name = &format!("llvm.fsh{}.i{}",
447 if is_left { 'l' } else { 'r' }, width);
448 let llfn = self.get_intrinsic(llvm_name);
449 self.call(llfn, &[val, val, raw_shift], None)
451 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
452 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
453 let width = self.const_uint(
457 let shift = self.urem(raw_shift, width);
458 let width_minus_raw_shift = self.sub(width, raw_shift);
459 let inv_shift = self.urem(width_minus_raw_shift, width);
460 let shift1 = self.shl(
462 if is_left { shift } else { inv_shift },
464 let shift2 = self.lshr(
466 if !is_left { shift } else { inv_shift },
468 self.or(shift1, shift2)
471 "saturating_add" | "saturating_sub" => {
472 let is_add = name == "saturating_add";
473 let lhs = args[0].immediate();
474 let rhs = args[1].immediate();
475 if llvm_util::get_major_version() >= 8 {
476 let llvm_name = &format!("llvm.{}{}.sat.i{}",
477 if signed { 's' } else { 'u' },
478 if is_add { "add" } else { "sub" },
480 let llfn = self.get_intrinsic(llvm_name);
481 self.call(llfn, &[lhs, rhs], None)
483 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
484 if signed { 's' } else { 'u' },
485 if is_add { "add" } else { "sub" },
487 let llfn = self.get_intrinsic(llvm_name);
488 let pair = self.call(llfn, &[lhs, rhs], None);
489 let val = self.extract_value(pair, 0);
490 let overflow = self.extract_value(pair, 1);
491 let llty = self.type_ix(width);
493 let limit = if signed {
494 let limit_lo = self.const_uint_big(
495 llty, (i128::MIN >> (128 - width)) as u128);
496 let limit_hi = self.const_uint_big(
497 llty, (i128::MAX >> (128 - width)) as u128);
499 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
500 self.select(neg, limit_hi, limit_lo)
502 self.const_uint_big(llty, u128::MAX >> (128 - width))
504 self.const_uint(llty, 0)
506 self.select(overflow, limit, val)
512 span_invalid_monomorphization_error(
514 &format!("invalid monomorphization of `{}` intrinsic: \
515 expected basic integer type, found `{}`", name, ty));
521 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
522 match float_type_width(arg_tys[0]) {
525 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
526 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
527 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
528 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
529 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
533 span_invalid_monomorphization_error(
535 &format!("invalid monomorphization of `{}` intrinsic: \
536 expected basic float type, found `{}`", name, arg_tys[0]));
543 "discriminant_value" => {
544 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
547 name if name.starts_with("simd_") => {
548 match generic_simd_intrinsic(self, name,
557 // This requires that atomic intrinsics follow a specific naming pattern:
558 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
559 name if name.starts_with("atomic_") => {
560 use rustc_codegen_ssa::common::AtomicOrdering::*;
561 use rustc_codegen_ssa::common::
562 {SynchronizationScope, AtomicRmwBinOp};
564 let split: Vec<&str> = name.split('_').collect();
566 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
567 let (order, failorder) = match split.len() {
568 2 => (SequentiallyConsistent, SequentiallyConsistent),
569 3 => match split[2] {
570 "unordered" => (Unordered, Unordered),
571 "relaxed" => (Monotonic, Monotonic),
572 "acq" => (Acquire, Acquire),
573 "rel" => (Release, Monotonic),
574 "acqrel" => (AcquireRelease, Acquire),
575 "failrelaxed" if is_cxchg =>
576 (SequentiallyConsistent, Monotonic),
577 "failacq" if is_cxchg =>
578 (SequentiallyConsistent, Acquire),
579 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
581 4 => match (split[2], split[3]) {
582 ("acq", "failrelaxed") if is_cxchg =>
583 (Acquire, Monotonic),
584 ("acqrel", "failrelaxed") if is_cxchg =>
585 (AcquireRelease, Monotonic),
586 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
588 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
591 let invalid_monomorphization = |ty| {
592 span_invalid_monomorphization_error(tcx.sess, span,
593 &format!("invalid monomorphization of `{}` intrinsic: \
594 expected basic integer type, found `{}`", name, ty));
598 "cxchg" | "cxchgweak" => {
599 let ty = substs.type_at(0);
600 if int_type_width_signed(ty, self).is_some() {
601 let weak = split[1] == "cxchgweak";
602 let pair = self.atomic_cmpxchg(
609 let val = self.extract_value(pair, 0);
610 let success = self.extract_value(pair, 1);
611 let success = self.zext(success, self.type_bool());
613 let dest = result.project_field(self, 0);
614 self.store(val, dest.llval, dest.align);
615 let dest = result.project_field(self, 1);
616 self.store(success, dest.llval, dest.align);
619 return invalid_monomorphization(ty);
624 let ty = substs.type_at(0);
625 if int_type_width_signed(ty, self).is_some() {
626 let size = self.size_of(ty);
627 self.atomic_load(args[0].immediate(), order, size)
629 return invalid_monomorphization(ty);
634 let ty = substs.type_at(0);
635 if int_type_width_signed(ty, self).is_some() {
636 let size = self.size_of(ty);
645 return invalid_monomorphization(ty);
650 self.atomic_fence(order, SynchronizationScope::CrossThread);
654 "singlethreadfence" => {
655 self.atomic_fence(order, SynchronizationScope::SingleThread);
659 // These are all AtomicRMW ops
661 let atom_op = match op {
662 "xchg" => AtomicRmwBinOp::AtomicXchg,
663 "xadd" => AtomicRmwBinOp::AtomicAdd,
664 "xsub" => AtomicRmwBinOp::AtomicSub,
665 "and" => AtomicRmwBinOp::AtomicAnd,
666 "nand" => AtomicRmwBinOp::AtomicNand,
667 "or" => AtomicRmwBinOp::AtomicOr,
668 "xor" => AtomicRmwBinOp::AtomicXor,
669 "max" => AtomicRmwBinOp::AtomicMax,
670 "min" => AtomicRmwBinOp::AtomicMin,
671 "umax" => AtomicRmwBinOp::AtomicUMax,
672 "umin" => AtomicRmwBinOp::AtomicUMin,
673 _ => self.sess().fatal("unknown atomic operation")
676 let ty = substs.type_at(0);
677 if int_type_width_signed(ty, self).is_some() {
685 return invalid_monomorphization(ty);
691 "nontemporal_store" => {
692 let dst = args[0].deref(self.cx());
693 args[1].val.nontemporal_store(self, dst);
697 _ => bug!("unknown intrinsic '{}'", name),
700 if !fn_ty.ret.is_ignore() {
701 if let PassMode::Cast(ty) = fn_ty.ret.mode {
702 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
703 let ptr = self.pointercast(result.llval, ptr_llty);
704 self.store(llval, ptr, result.align);
706 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
707 .val.store(self, result);
712 fn abort(&mut self) {
713 let fnname = self.get_intrinsic(&("llvm.trap"));
714 self.call(fnname, &[], None);
717 fn assume(&mut self, val: Self::Value) {
718 let assume_intrinsic = self.get_intrinsic("llvm.assume");
719 self.call(assume_intrinsic, &[val], None);
722 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
723 let expect = self.get_intrinsic(&"llvm.expect.i1");
724 self.call(expect, &[cond, self.const_bool(expected)], None)
727 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
728 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
729 self.call(intrinsic, &[va_list], None)
732 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
733 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
734 self.call(intrinsic, &[va_list], None)
739 bx: &mut Builder<'a, 'll, 'tcx>,
747 let (size, align) = bx.size_and_align_of(ty);
748 let size = bx.mul(bx.const_usize(size.bytes()), count);
749 let flags = if volatile {
755 bx.memmove(dst, align, src, align, size, flags);
757 bx.memcpy(dst, align, src, align, size, flags);
762 bx: &mut Builder<'a, 'll, 'tcx>,
769 let (size, align) = bx.size_and_align_of(ty);
770 let size = bx.mul(bx.const_usize(size.bytes()), count);
771 let flags = if volatile {
776 bx.memset(dst, val, size, align, flags);
780 bx: &mut Builder<'a, 'll, 'tcx>,
783 local_ptr: &'ll Value,
786 if bx.sess().no_landing_pads() {
787 bx.call(func, &[data], None);
788 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
789 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
790 } else if wants_msvc_seh(bx.sess()) {
791 codegen_msvc_try(bx, func, data, local_ptr, dest);
793 codegen_gnu_try(bx, func, data, local_ptr, dest);
797 // MSVC's definition of the `rust_try` function.
799 // This implementation uses the new exception handling instructions in LLVM
800 // which have support in LLVM for SEH on MSVC targets. Although these
801 // instructions are meant to work for all targets, as of the time of this
802 // writing, however, LLVM does not recommend the usage of these new instructions
803 // as the old ones are still more optimized.
805 bx: &mut Builder<'a, 'll, 'tcx>,
808 local_ptr: &'ll Value,
811 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
812 bx.set_personality_fn(bx.eh_personality());
814 let mut normal = bx.build_sibling_block("normal");
815 let mut catchswitch = bx.build_sibling_block("catchswitch");
816 let mut catchpad = bx.build_sibling_block("catchpad");
817 let mut caught = bx.build_sibling_block("caught");
819 let func = llvm::get_param(bx.llfn(), 0);
820 let data = llvm::get_param(bx.llfn(), 1);
821 let local_ptr = llvm::get_param(bx.llfn(), 2);
823 // We're generating an IR snippet that looks like:
825 // declare i32 @rust_try(%func, %data, %ptr) {
826 // %slot = alloca i64*
827 // invoke %func(%data) to label %normal unwind label %catchswitch
833 // %cs = catchswitch within none [%catchpad] unwind to caller
836 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
837 // %ptr[0] = %slot[0]
838 // %ptr[1] = %slot[1]
839 // catchret from %tok to label %caught
845 // This structure follows the basic usage of throw/try/catch in LLVM.
846 // For example, compile this C++ snippet to see what LLVM generates:
848 // #include <stdint.h>
850 // int bar(void (*foo)(void), uint64_t *ret) {
854 // } catch(uint64_t a[2]) {
861 // More information can be found in libstd's seh.rs implementation.
862 let i64p = bx.type_ptr_to(bx.type_i64());
863 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
864 let slot = bx.alloca(i64p, ptr_align);
865 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
867 normal.ret(bx.const_i32(0));
869 let cs = catchswitch.catch_switch(None, None, 1);
870 catchswitch.add_handler(cs, catchpad.llbb());
872 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
873 Some(did) => bx.get_static(did),
874 None => bug!("msvc_try_filter not defined"),
876 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
877 let addr = catchpad.load(slot, ptr_align);
879 let i64_align = bx.tcx().data_layout.i64_align.abi;
880 let arg1 = catchpad.load(addr, i64_align);
881 let val1 = bx.const_i32(1);
882 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
883 let arg2 = catchpad.load(gep1, i64_align);
884 let local_ptr = catchpad.bitcast(local_ptr, i64p);
885 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
886 catchpad.store(arg1, local_ptr, i64_align);
887 catchpad.store(arg2, gep2, i64_align);
888 catchpad.catch_ret(&funclet, caught.llbb());
890 caught.ret(bx.const_i32(1));
893 // Note that no invoke is used here because by definition this function
894 // can't panic (that's what it's catching).
895 let ret = bx.call(llfn, &[func, data, local_ptr], None);
896 let i32_align = bx.tcx().data_layout.i32_align.abi;
897 bx.store(ret, dest, i32_align);
900 // Definition of the standard `try` function for Rust using the GNU-like model
901 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
904 // This codegen is a little surprising because we always call a shim
905 // function instead of inlining the call to `invoke` manually here. This is done
906 // because in LLVM we're only allowed to have one personality per function
907 // definition. The call to the `try` intrinsic is being inlined into the
908 // function calling it, and that function may already have other personality
909 // functions in play. By calling a shim we're guaranteed that our shim will have
910 // the right personality function.
912 bx: &mut Builder<'a, 'll, 'tcx>,
915 local_ptr: &'ll Value,
918 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
919 // Codegens the shims described above:
922 // invoke %func(%args...) normal %normal unwind %catch
928 // (ptr, _) = landingpad
929 // store ptr, %local_ptr
932 // Note that the `local_ptr` data passed into the `try` intrinsic is
933 // expected to be `*mut *mut u8` for this to actually work, but that's
934 // managed by the standard library.
936 let mut then = bx.build_sibling_block("then");
937 let mut catch = bx.build_sibling_block("catch");
939 let func = llvm::get_param(bx.llfn(), 0);
940 let data = llvm::get_param(bx.llfn(), 1);
941 let local_ptr = llvm::get_param(bx.llfn(), 2);
942 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
943 then.ret(bx.const_i32(0));
945 // Type indicator for the exception being thrown.
947 // The first value in this tuple is a pointer to the exception object
948 // being thrown. The second value is a "selector" indicating which of
949 // the landing pad clauses the exception's type had been matched to.
950 // rust_try ignores the selector.
951 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
952 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
953 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
954 let ptr = catch.extract_value(vals, 0);
955 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
956 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
957 catch.store(ptr, bitcast, ptr_align);
958 catch.ret(bx.const_i32(1));
961 // Note that no invoke is used here because by definition this function
962 // can't panic (that's what it's catching).
963 let ret = bx.call(llfn, &[func, data, local_ptr], None);
964 let i32_align = bx.tcx().data_layout.i32_align.abi;
965 bx.store(ret, dest, i32_align);
968 // Helper function to give a Block to a closure to codegen a shim function.
969 // This is currently primarily used for the `try` intrinsic functions above.
970 fn gen_fn<'ll, 'tcx>(
971 cx: &CodegenCx<'ll, 'tcx>,
973 inputs: Vec<Ty<'tcx>>,
975 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
977 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
981 hir::Unsafety::Unsafe,
984 let llfn = cx.define_internal_fn(name, rust_fn_sig);
985 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
986 let bx = Builder::new_block(cx, llfn, "entry-block");
991 // Helper function used to get a handle to the `__rust_try` function used to
994 // This function is only generated once and is then cached.
995 fn get_rust_try_fn<'ll, 'tcx>(
996 cx: &CodegenCx<'ll, 'tcx>,
997 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
999 if let Some(llfn) = cx.rust_try_fn.get() {
1003 // Define the type up front for the signature of the rust_try function.
1005 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1006 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1010 hir::Unsafety::Unsafe,
1013 let output = tcx.types.i32;
1014 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1015 cx.rust_try_fn.set(Some(rust_try));
1019 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1020 span_err!(a, b, E0511, "{}", c);
1023 fn generic_simd_intrinsic(
1024 bx: &mut Builder<'a, 'll, 'tcx>,
1026 callee_ty: Ty<'tcx>,
1027 args: &[OperandRef<'tcx, &'ll Value>],
1029 llret_ty: &'ll Type,
1031 ) -> Result<&'ll Value, ()> {
1032 // macros for error handling:
1033 macro_rules! emit_error {
1037 ($msg: tt, $($fmt: tt)*) => {
1038 span_invalid_monomorphization_error(
1040 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1045 macro_rules! return_error {
1048 emit_error!($($fmt)*);
1054 macro_rules! require {
1055 ($cond: expr, $($fmt: tt)*) => {
1057 return_error!($($fmt)*);
1062 macro_rules! require_simd {
1063 ($ty: expr, $position: expr) => {
1064 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1069 let sig = tcx.normalize_erasing_late_bound_regions(
1070 ty::ParamEnv::reveal_all(),
1071 &callee_ty.fn_sig(tcx),
1073 let arg_tys = sig.inputs();
1075 if name == "simd_select_bitmask" {
1076 let in_ty = arg_tys[0];
1077 let m_len = match in_ty.sty {
1078 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1079 // of intentional as there's not currently a use case for that.
1080 ty::Int(i) => i.bit_width().unwrap(),
1081 ty::Uint(i) => i.bit_width().unwrap(),
1082 _ => return_error!("`{}` is not an integral type", in_ty),
1084 require_simd!(arg_tys[1], "argument");
1085 let v_len = arg_tys[1].simd_size(tcx);
1086 require!(m_len == v_len,
1087 "mismatched lengths: mask length `{}` != other vector length `{}`",
1090 let i1 = bx.type_i1();
1091 let i1xn = bx.type_vector(i1, m_len as u64);
1092 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1093 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1096 // every intrinsic below takes a SIMD vector as its first argument
1097 require_simd!(arg_tys[0], "input");
1098 let in_ty = arg_tys[0];
1099 let in_elem = arg_tys[0].simd_type(tcx);
1100 let in_len = arg_tys[0].simd_size(tcx);
1102 let comparison = match name {
1103 "simd_eq" => Some(hir::BinOpKind::Eq),
1104 "simd_ne" => Some(hir::BinOpKind::Ne),
1105 "simd_lt" => Some(hir::BinOpKind::Lt),
1106 "simd_le" => Some(hir::BinOpKind::Le),
1107 "simd_gt" => Some(hir::BinOpKind::Gt),
1108 "simd_ge" => Some(hir::BinOpKind::Ge),
1112 if let Some(cmp_op) = comparison {
1113 require_simd!(ret_ty, "return");
1115 let out_len = ret_ty.simd_size(tcx);
1116 require!(in_len == out_len,
1117 "expected return type with length {} (same as input type `{}`), \
1118 found `{}` with length {}",
1121 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1122 "expected return type with integer elements, found `{}` with non-integer `{}`",
1124 ret_ty.simd_type(tcx));
1126 return Ok(compare_simd_types(bx,
1127 args[0].immediate(),
1128 args[1].immediate(),
1134 if name.starts_with("simd_shuffle") {
1135 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1136 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1138 require_simd!(ret_ty, "return");
1140 let out_len = ret_ty.simd_size(tcx);
1141 require!(out_len == n,
1142 "expected return type of length {}, found `{}` with length {}",
1143 n, ret_ty, out_len);
1144 require!(in_elem == ret_ty.simd_type(tcx),
1145 "expected return element type `{}` (element of input `{}`), \
1146 found `{}` with element type `{}`",
1148 ret_ty, ret_ty.simd_type(tcx));
1150 let total_len = in_len as u128 * 2;
1152 let vector = args[2].immediate();
1154 let indices: Option<Vec<_>> = (0..n)
1157 let val = bx.const_get_elt(vector, i as u64);
1158 match bx.const_to_opt_u128(val, true) {
1160 emit_error!("shuffle index #{} is not a constant", arg_idx);
1163 Some(idx) if idx >= total_len => {
1164 emit_error!("shuffle index #{} is out of bounds (limit {})",
1165 arg_idx, total_len);
1168 Some(idx) => Some(bx.const_i32(idx as i32)),
1172 let indices = match indices {
1174 None => return Ok(bx.const_null(llret_ty))
1177 return Ok(bx.shuffle_vector(args[0].immediate(),
1178 args[1].immediate(),
1179 bx.const_vector(&indices)))
1182 if name == "simd_insert" {
1183 require!(in_elem == arg_tys[2],
1184 "expected inserted type `{}` (element of input `{}`), found `{}`",
1185 in_elem, in_ty, arg_tys[2]);
1186 return Ok(bx.insert_element(args[0].immediate(),
1187 args[2].immediate(),
1188 args[1].immediate()))
1190 if name == "simd_extract" {
1191 require!(ret_ty == in_elem,
1192 "expected return type `{}` (element of input `{}`), found `{}`",
1193 in_elem, in_ty, ret_ty);
1194 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1197 if name == "simd_select" {
1198 let m_elem_ty = in_elem;
1200 require_simd!(arg_tys[1], "argument");
1201 let v_len = arg_tys[1].simd_size(tcx);
1202 require!(m_len == v_len,
1203 "mismatched lengths: mask length `{}` != other vector length `{}`",
1206 match m_elem_ty.sty {
1208 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1210 // truncate the mask to a vector of i1s
1211 let i1 = bx.type_i1();
1212 let i1xn = bx.type_vector(i1, m_len as u64);
1213 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1214 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1217 if name == "simd_bitmask" {
1218 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1219 // vector mask and returns an unsigned integer containing the most
1220 // significant bit (MSB) of each lane.
1221 use rustc_target::abi::HasDataLayout;
1223 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1225 let expected_int_bits = in_len.max(8);
1227 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1229 "bitmask `{}`, expected `u{}`",
1230 ret_ty, expected_int_bits
1234 // Integer vector <i{in_bitwidth} x in_len>:
1235 let (i_xn, in_elem_bitwidth) = match in_elem.sty {
1237 args[0].immediate(),
1238 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1241 args[0].immediate(),
1242 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1245 "vector argument `{}`'s element type `{}`, expected integer element type",
1250 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1251 let shift_indices = vec![
1252 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _); in_len
1254 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1255 // Truncate vector to an <i1 x N>
1256 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1257 // Bitcast <i1 x N> to iN:
1258 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1259 // Zero-extend iN to the bitmask type:
1260 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1263 fn simd_simple_float_intrinsic(
1265 in_elem: &::rustc::ty::TyS<'_>,
1266 in_ty: &::rustc::ty::TyS<'_>,
1268 bx: &mut Builder<'a, 'll, 'tcx>,
1270 args: &[OperandRef<'tcx, &'ll Value>],
1271 ) -> Result<&'ll Value, ()> {
1272 macro_rules! emit_error {
1276 ($msg: tt, $($fmt: tt)*) => {
1277 span_invalid_monomorphization_error(
1279 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1283 macro_rules! return_error {
1286 emit_error!($($fmt)*);
1291 let ety = match in_elem.sty {
1292 ty::Float(f) if f.bit_width() == 32 => {
1293 if in_len < 2 || in_len > 16 {
1295 "unsupported floating-point vector `{}` with length `{}` \
1296 out-of-range [2, 16]",
1301 ty::Float(f) if f.bit_width() == 64 => {
1302 if in_len < 2 || in_len > 8 {
1303 return_error!("unsupported floating-point vector `{}` with length `{}` \
1304 out-of-range [2, 8]",
1310 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1314 return_error!("`{}` is not a floating-point type", in_ty);
1318 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1319 let intrinsic = bx.get_intrinsic(&llvm_name);
1320 let c = bx.call(intrinsic,
1321 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1323 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1329 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1332 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1335 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1338 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1341 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1344 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1347 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1350 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1353 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1356 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1359 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1362 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1365 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1368 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1370 _ => { /* fallthrough */ }
1374 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1375 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1376 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: usize, no_pointers: usize) -> String {
1377 let p0s: String = "p0".repeat(no_pointers);
1379 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1380 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1381 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1382 _ => unreachable!(),
1386 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: usize,
1387 mut no_pointers: usize) -> &'ll Type {
1388 // FIXME: use cx.layout_of(ty).llvm_type() ?
1389 let mut elem_ty = match elem_ty.sty {
1390 ty::Int(v) => cx.type_int_from_ty( v),
1391 ty::Uint(v) => cx.type_uint_from_ty( v),
1392 ty::Float(v) => cx.type_float_from_ty( v),
1393 _ => unreachable!(),
1395 while no_pointers > 0 {
1396 elem_ty = cx.type_ptr_to(elem_ty);
1399 cx.type_vector(elem_ty, vec_len as u64)
1403 if name == "simd_gather" {
1404 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1405 // mask: <N x i{M}>) -> <N x T>
1406 // * N: number of elements in the input vectors
1407 // * T: type of the element to load
1408 // * M: any integer width is supported, will be truncated to i1
1410 // All types must be simd vector types
1411 require_simd!(in_ty, "first");
1412 require_simd!(arg_tys[1], "second");
1413 require_simd!(arg_tys[2], "third");
1414 require_simd!(ret_ty, "return");
1416 // Of the same length:
1417 require!(in_len == arg_tys[1].simd_size(tcx),
1418 "expected {} argument with length {} (same as input type `{}`), \
1419 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1420 arg_tys[1].simd_size(tcx));
1421 require!(in_len == arg_tys[2].simd_size(tcx),
1422 "expected {} argument with length {} (same as input type `{}`), \
1423 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1424 arg_tys[2].simd_size(tcx));
1426 // The return type must match the first argument type
1427 require!(ret_ty == in_ty,
1428 "expected return type `{}`, found `{}`",
1431 // This counts how many pointers
1432 fn ptr_count(t: Ty<'_>) -> usize {
1434 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1440 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1442 ty::RawPtr(p) => non_ptr(p.ty),
1447 // The second argument must be a simd vector with an element type that's a pointer
1448 // to the element type of the first argument
1449 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1450 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1451 non_ptr(arg_tys[1].simd_type(tcx))),
1453 require!(false, "expected element type `{}` of second argument `{}` \
1454 to be a pointer to the element type `{}` of the first \
1455 argument `{}`, found `{}` != `*_ {}`",
1456 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1457 arg_tys[1].simd_type(tcx), in_elem);
1461 assert!(pointer_count > 0);
1462 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1463 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1465 // The element type of the third argument must be a signed integer type of any width:
1466 match arg_tys[2].simd_type(tcx).sty {
1469 require!(false, "expected element type `{}` of third argument `{}` \
1470 to be a signed integer type",
1471 arg_tys[2].simd_type(tcx), arg_tys[2]);
1475 // Alignment of T, must be a constant integer value:
1476 let alignment_ty = bx.type_i32();
1477 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1479 // Truncate the mask vector to a vector of i1s:
1480 let (mask, mask_ty) = {
1481 let i1 = bx.type_i1();
1482 let i1xn = bx.type_vector(i1, in_len as u64);
1483 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1486 // Type of the vector of pointers:
1487 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1488 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1490 // Type of the vector of elements:
1491 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1492 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1494 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1495 llvm_elem_vec_str, llvm_pointer_vec_str);
1496 let f = bx.declare_cfn(&llvm_intrinsic,
1498 llvm_pointer_vec_ty,
1501 llvm_elem_vec_ty], llvm_elem_vec_ty));
1502 llvm::SetUnnamedAddr(f, false);
1503 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1508 if name == "simd_scatter" {
1509 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1510 // mask: <N x i{M}>) -> ()
1511 // * N: number of elements in the input vectors
1512 // * T: type of the element to load
1513 // * M: any integer width is supported, will be truncated to i1
1515 // All types must be simd vector types
1516 require_simd!(in_ty, "first");
1517 require_simd!(arg_tys[1], "second");
1518 require_simd!(arg_tys[2], "third");
1520 // Of the same length:
1521 require!(in_len == arg_tys[1].simd_size(tcx),
1522 "expected {} argument with length {} (same as input type `{}`), \
1523 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1524 arg_tys[1].simd_size(tcx));
1525 require!(in_len == arg_tys[2].simd_size(tcx),
1526 "expected {} argument with length {} (same as input type `{}`), \
1527 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1528 arg_tys[2].simd_size(tcx));
1530 // This counts how many pointers
1531 fn ptr_count(t: Ty<'_>) -> usize {
1533 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1539 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1541 ty::RawPtr(p) => non_ptr(p.ty),
1546 // The second argument must be a simd vector with an element type that's a pointer
1547 // to the element type of the first argument
1548 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1549 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1550 => (ptr_count(arg_tys[1].simd_type(tcx)),
1551 non_ptr(arg_tys[1].simd_type(tcx))),
1553 require!(false, "expected element type `{}` of second argument `{}` \
1554 to be a pointer to the element type `{}` of the first \
1555 argument `{}`, found `{}` != `*mut {}`",
1556 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1557 arg_tys[1].simd_type(tcx), in_elem);
1561 assert!(pointer_count > 0);
1562 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1563 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1565 // The element type of the third argument must be a signed integer type of any width:
1566 match arg_tys[2].simd_type(tcx).sty {
1569 require!(false, "expected element type `{}` of third argument `{}` \
1570 to be a signed integer type",
1571 arg_tys[2].simd_type(tcx), arg_tys[2]);
1575 // Alignment of T, must be a constant integer value:
1576 let alignment_ty = bx.type_i32();
1577 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1579 // Truncate the mask vector to a vector of i1s:
1580 let (mask, mask_ty) = {
1581 let i1 = bx.type_i1();
1582 let i1xn = bx.type_vector(i1, in_len as u64);
1583 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1586 let ret_t = bx.type_void();
1588 // Type of the vector of pointers:
1589 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1590 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1592 // Type of the vector of elements:
1593 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1594 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1596 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1597 llvm_elem_vec_str, llvm_pointer_vec_str);
1598 let f = bx.declare_cfn(&llvm_intrinsic,
1599 bx.type_func(&[llvm_elem_vec_ty,
1600 llvm_pointer_vec_ty,
1603 llvm::SetUnnamedAddr(f, false);
1604 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1609 macro_rules! arith_red {
1610 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1612 require!(ret_ty == in_elem,
1613 "expected return type `{}` (element of input `{}`), found `{}`",
1614 in_elem, in_ty, ret_ty);
1615 return match in_elem.sty {
1616 ty::Int(_) | ty::Uint(_) => {
1617 let r = bx.$integer_reduce(args[0].immediate());
1619 // if overflow occurs, the result is the
1620 // mathematical result modulo 2^n:
1621 if name.contains("mul") {
1622 Ok(bx.mul(args[1].immediate(), r))
1624 Ok(bx.add(args[1].immediate(), r))
1627 Ok(bx.$integer_reduce(args[0].immediate()))
1631 let acc = if $ordered {
1632 // ordered arithmetic reductions take an accumulator
1635 // unordered arithmetic reductions use the identity accumulator
1636 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1637 match f.bit_width() {
1638 32 => bx.const_real(bx.type_f32(), identity_acc),
1639 64 => bx.const_real(bx.type_f64(), identity_acc),
1642 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1643 $name, in_ty, in_elem, v, ret_ty
1648 Ok(bx.$float_reduce(acc, args[0].immediate()))
1652 "unsupported {} from `{}` with element `{}` to `{}`",
1653 $name, in_ty, in_elem, ret_ty
1661 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1662 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1663 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1664 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1666 macro_rules! minmax_red {
1667 ($name:tt: $int_red:ident, $float_red:ident) => {
1669 require!(ret_ty == in_elem,
1670 "expected return type `{}` (element of input `{}`), found `{}`",
1671 in_elem, in_ty, ret_ty);
1672 return match in_elem.sty {
1674 Ok(bx.$int_red(args[0].immediate(), true))
1677 Ok(bx.$int_red(args[0].immediate(), false))
1680 Ok(bx.$float_red(args[0].immediate()))
1683 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1684 $name, in_ty, in_elem, ret_ty)
1692 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1693 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1695 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1696 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1698 macro_rules! bitwise_red {
1699 ($name:tt : $red:ident, $boolean:expr) => {
1701 let input = if !$boolean {
1702 require!(ret_ty == in_elem,
1703 "expected return type `{}` (element of input `{}`), found `{}`",
1704 in_elem, in_ty, ret_ty);
1708 ty::Int(_) | ty::Uint(_) => {},
1710 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1711 $name, in_ty, in_elem, ret_ty)
1715 // boolean reductions operate on vectors of i1s:
1716 let i1 = bx.type_i1();
1717 let i1xn = bx.type_vector(i1, in_len as u64);
1718 bx.trunc(args[0].immediate(), i1xn)
1720 return match in_elem.sty {
1721 ty::Int(_) | ty::Uint(_) => {
1722 let r = bx.$red(input);
1727 bx.zext(r, bx.type_bool())
1732 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1733 $name, in_ty, in_elem, ret_ty)
1740 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1741 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1742 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1743 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1744 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1746 if name == "simd_cast" {
1747 require_simd!(ret_ty, "return");
1748 let out_len = ret_ty.simd_size(tcx);
1749 require!(in_len == out_len,
1750 "expected return type with length {} (same as input type `{}`), \
1751 found `{}` with length {}",
1754 // casting cares about nominal type, not just structural type
1755 let out_elem = ret_ty.simd_type(tcx);
1757 if in_elem == out_elem { return Ok(args[0].immediate()); }
1759 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1761 let (in_style, in_width) = match in_elem.sty {
1762 // vectors of pointer-sized integers should've been
1763 // disallowed before here, so this unwrap is safe.
1764 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1765 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1766 ty::Float(f) => (Style::Float, f.bit_width()),
1767 _ => (Style::Unsupported, 0)
1769 let (out_style, out_width) = match out_elem.sty {
1770 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1771 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1772 ty::Float(f) => (Style::Float, f.bit_width()),
1773 _ => (Style::Unsupported, 0)
1776 match (in_style, out_style) {
1777 (Style::Int(in_is_signed), Style::Int(_)) => {
1778 return Ok(match in_width.cmp(&out_width) {
1779 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1780 Ordering::Equal => args[0].immediate(),
1781 Ordering::Less => if in_is_signed {
1782 bx.sext(args[0].immediate(), llret_ty)
1784 bx.zext(args[0].immediate(), llret_ty)
1788 (Style::Int(in_is_signed), Style::Float) => {
1789 return Ok(if in_is_signed {
1790 bx.sitofp(args[0].immediate(), llret_ty)
1792 bx.uitofp(args[0].immediate(), llret_ty)
1795 (Style::Float, Style::Int(out_is_signed)) => {
1796 return Ok(if out_is_signed {
1797 bx.fptosi(args[0].immediate(), llret_ty)
1799 bx.fptoui(args[0].immediate(), llret_ty)
1802 (Style::Float, Style::Float) => {
1803 return Ok(match in_width.cmp(&out_width) {
1804 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1805 Ordering::Equal => args[0].immediate(),
1806 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1809 _ => {/* Unsupported. Fallthrough. */}
1812 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1816 macro_rules! arith {
1817 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1818 $(if name == stringify!($name) {
1820 $($(ty::$p(_))|* => {
1821 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1826 "unsupported operation on `{}` with element `{}`",
1833 simd_add: Uint, Int => add, Float => fadd;
1834 simd_sub: Uint, Int => sub, Float => fsub;
1835 simd_mul: Uint, Int => mul, Float => fmul;
1836 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1837 simd_rem: Uint => urem, Int => srem, Float => frem;
1838 simd_shl: Uint, Int => shl;
1839 simd_shr: Uint => lshr, Int => ashr;
1840 simd_and: Uint, Int => and;
1841 simd_or: Uint, Int => or;
1842 simd_xor: Uint, Int => xor;
1843 simd_fmax: Float => maxnum;
1844 simd_fmin: Float => minnum;
1848 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1849 let lhs = args[0].immediate();
1850 let rhs = args[1].immediate();
1851 let is_add = name == "simd_saturating_add";
1852 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1853 let (signed, elem_width, elem_ty) = match in_elem.sty {
1857 i.bit_width().unwrap_or(ptr_bits),
1858 bx.cx.type_int_from_ty(i)
1863 i.bit_width().unwrap_or(ptr_bits),
1864 bx.cx.type_uint_from_ty(i)
1868 "expected element type `{}` of vector type `{}` \
1869 to be a signed or unsigned integer type",
1870 arg_tys[0].simd_type(tcx), arg_tys[0]
1874 let llvm_intrinsic = &format!(
1875 "llvm.{}{}.sat.v{}i{}",
1876 if signed { 's' } else { 'u' },
1877 if is_add { "add" } else { "sub" },
1880 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1882 let f = bx.declare_cfn(
1884 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1886 llvm::SetUnnamedAddr(f, false);
1887 let v = bx.call(f, &[lhs, rhs], None);
1891 span_bug!(span, "unknown SIMD intrinsic");
1894 // Returns the width of an int Ty, and if it's signed or not
1895 // Returns None if the type is not an integer
1896 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1898 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1900 ty::Int(t) => Some((match t {
1901 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1902 ast::IntTy::I8 => 8,
1903 ast::IntTy::I16 => 16,
1904 ast::IntTy::I32 => 32,
1905 ast::IntTy::I64 => 64,
1906 ast::IntTy::I128 => 128,
1908 ty::Uint(t) => Some((match t {
1909 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1910 ast::UintTy::U8 => 8,
1911 ast::UintTy::U16 => 16,
1912 ast::UintTy::U32 => 32,
1913 ast::UintTy::U64 => 64,
1914 ast::UintTy::U128 => 128,
1920 // Returns the width of a float Ty
1921 // Returns None if the type is not a float
1922 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1924 ty::Float(t) => Some(t.bit_width() as u64),