1 #![allow(non_upper_case_globals)]
6 use crate::abi::{Abi, FnType, LlvmType, PassMode};
7 use crate::context::CodegenCx;
8 use crate::type_::Type;
9 use crate::type_of::LayoutLlvmExt;
10 use crate::builder::Builder;
11 use crate::value::Value;
12 use crate::va_arg::emit_va_arg;
13 use rustc_codegen_ssa::MemFlags;
14 use rustc_codegen_ssa::mir::place::PlaceRef;
15 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
16 use rustc_codegen_ssa::glue;
17 use rustc_codegen_ssa::base::{to_immediate, wants_msvc_seh, compare_simd_types};
18 use rustc::ty::{self, Ty};
19 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, Primitive};
20 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
22 use syntax::ast::{self, FloatTy};
23 use syntax::symbol::LocalInternedString;
25 use rustc_codegen_ssa::traits::*;
27 use rustc::session::Session;
30 use std::cmp::Ordering;
31 use std::{iter, i128, u128};
33 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
34 let llvm_name = match name {
35 "sqrtf32" => "llvm.sqrt.f32",
36 "sqrtf64" => "llvm.sqrt.f64",
37 "powif32" => "llvm.powi.f32",
38 "powif64" => "llvm.powi.f64",
39 "sinf32" => "llvm.sin.f32",
40 "sinf64" => "llvm.sin.f64",
41 "cosf32" => "llvm.cos.f32",
42 "cosf64" => "llvm.cos.f64",
43 "powf32" => "llvm.pow.f32",
44 "powf64" => "llvm.pow.f64",
45 "expf32" => "llvm.exp.f32",
46 "expf64" => "llvm.exp.f64",
47 "exp2f32" => "llvm.exp2.f32",
48 "exp2f64" => "llvm.exp2.f64",
49 "logf32" => "llvm.log.f32",
50 "logf64" => "llvm.log.f64",
51 "log10f32" => "llvm.log10.f32",
52 "log10f64" => "llvm.log10.f64",
53 "log2f32" => "llvm.log2.f32",
54 "log2f64" => "llvm.log2.f64",
55 "fmaf32" => "llvm.fma.f32",
56 "fmaf64" => "llvm.fma.f64",
57 "fabsf32" => "llvm.fabs.f32",
58 "fabsf64" => "llvm.fabs.f64",
59 "copysignf32" => "llvm.copysign.f32",
60 "copysignf64" => "llvm.copysign.f64",
61 "floorf32" => "llvm.floor.f32",
62 "floorf64" => "llvm.floor.f64",
63 "ceilf32" => "llvm.ceil.f32",
64 "ceilf64" => "llvm.ceil.f64",
65 "truncf32" => "llvm.trunc.f32",
66 "truncf64" => "llvm.trunc.f64",
67 "rintf32" => "llvm.rint.f32",
68 "rintf64" => "llvm.rint.f64",
69 "nearbyintf32" => "llvm.nearbyint.f32",
70 "nearbyintf64" => "llvm.nearbyint.f64",
71 "roundf32" => "llvm.round.f32",
72 "roundf64" => "llvm.round.f64",
73 "assume" => "llvm.assume",
74 "abort" => "llvm.trap",
77 Some(cx.get_intrinsic(&llvm_name))
80 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
81 fn codegen_intrinsic_call(
84 fn_ty: &FnType<'tcx, Ty<'tcx>>,
85 args: &[OperandRef<'tcx, &'ll Value>],
91 let (def_id, substs) = match callee_ty.sty {
92 ty::FnDef(def_id, substs) => (def_id, substs),
93 _ => bug!("expected fn item type, found {}", callee_ty)
96 let sig = callee_ty.fn_sig(tcx);
97 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
98 let arg_tys = sig.inputs();
99 let ret_ty = sig.output();
100 let name = &*tcx.item_name(def_id).as_str();
102 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
103 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align.abi);
105 let simple = get_simple_intrinsic(self, name);
106 let llval = match name {
107 _ if simple.is_some() => {
108 self.call(simple.unwrap(),
109 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
116 let expect = self.get_intrinsic(&("llvm.expect.i1"));
117 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
120 let expect = self.get_intrinsic(&("llvm.expect.i1"));
121 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
132 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
133 self.call(llfn, &[], None)
136 let tp_ty = substs.type_at(0);
137 self.const_usize(self.size_of(tp_ty).bytes())
140 self.va_start(args[0].immediate())
143 self.va_end(args[0].immediate())
146 let va_list = match (tcx.lang_items().va_list(), &result.layout.ty.sty) {
147 (Some(did), ty::Adt(def, _)) if def.did == did => args[0].immediate(),
148 (Some(_), _) => self.load(args[0].immediate(),
149 tcx.data_layout.pointer_align.abi),
150 (None, _) => bug!("`va_list` language item must be defined")
152 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
153 self.call(intrinsic, &[llresult, va_list], None);
157 match fn_ty.ret.layout.abi {
158 layout::Abi::Scalar(ref scalar) => {
160 Primitive::Int(..) => {
161 if self.cx().size_of(ret_ty).bytes() < 4 {
162 // va_arg should not be called on a integer type
163 // less than 4 bytes in length. If it is, promote
164 // the integer to a `i32` and truncate the result
165 // back to the smaller type.
166 let promoted_result = emit_va_arg(self, args[0],
168 self.trunc(promoted_result, llret_ty)
170 emit_va_arg(self, args[0], ret_ty)
173 Primitive::Float(FloatTy::F64) |
174 Primitive::Pointer => {
175 emit_va_arg(self, args[0], ret_ty)
177 // `va_arg` should never be used with the return type f32.
178 Primitive::Float(FloatTy::F32) => {
179 bug!("the va_arg intrinsic does not work with `f32`")
184 bug!("the va_arg intrinsic does not work with non-scalar types")
189 let tp_ty = substs.type_at(0);
190 if let OperandValue::Pair(_, meta) = args[0].val {
191 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
194 self.const_usize(self.size_of(tp_ty).bytes())
198 let tp_ty = substs.type_at(0);
199 self.const_usize(self.align_of(tp_ty).bytes())
201 "min_align_of_val" => {
202 let tp_ty = substs.type_at(0);
203 if let OperandValue::Pair(_, meta) = args[0].val {
204 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
207 self.const_usize(self.align_of(tp_ty).bytes())
211 let tp_ty = substs.type_at(0);
212 self.const_usize(self.layout_of(tp_ty).align.pref.bytes())
215 let tp_ty = substs.type_at(0);
216 let ty_name = LocalInternedString::intern(&tp_ty.to_string());
217 self.const_str_slice(ty_name)
220 self.const_u64(self.tcx.type_id_hash(substs.type_at(0)))
223 let ty = substs.type_at(0);
224 if !self.layout_of(ty).is_zst() {
225 // Just zero out the stack slot.
226 // If we store a zero constant, LLVM will drown in vreg allocation for large
227 // data structures, and the generated code will be awful. (A telltale sign of
228 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
240 // Effectively no-ops
241 "uninit" | "forget" => {
245 let tp_ty = substs.type_at(0);
247 self.const_bool(self.type_needs_drop(tp_ty))
250 let ptr = args[0].immediate();
251 let offset = args[1].immediate();
252 self.inbounds_gep(ptr, &[offset])
255 let ptr = args[0].immediate();
256 let offset = args[1].immediate();
257 self.gep(ptr, &[offset])
260 "copy_nonoverlapping" => {
261 copy_intrinsic(self, false, false, substs.type_at(0),
262 args[1].immediate(), args[0].immediate(), args[2].immediate());
266 copy_intrinsic(self, true, false, substs.type_at(0),
267 args[1].immediate(), args[0].immediate(), args[2].immediate());
271 memset_intrinsic(self, false, substs.type_at(0),
272 args[0].immediate(), args[1].immediate(), args[2].immediate());
276 "volatile_copy_nonoverlapping_memory" => {
277 copy_intrinsic(self, false, true, substs.type_at(0),
278 args[0].immediate(), args[1].immediate(), args[2].immediate());
281 "volatile_copy_memory" => {
282 copy_intrinsic(self, true, true, substs.type_at(0),
283 args[0].immediate(), args[1].immediate(), args[2].immediate());
286 "volatile_set_memory" => {
287 memset_intrinsic(self, true, substs.type_at(0),
288 args[0].immediate(), args[1].immediate(), args[2].immediate());
291 "volatile_load" | "unaligned_volatile_load" => {
292 let tp_ty = substs.type_at(0);
293 let mut ptr = args[0].immediate();
294 if let PassMode::Cast(ty) = fn_ty.ret.mode {
295 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
297 let load = self.volatile_load(ptr);
298 let align = if name == "unaligned_volatile_load" {
301 self.align_of(tp_ty).bytes() as u32
304 llvm::LLVMSetAlignment(load, align);
306 to_immediate(self, load, self.layout_of(tp_ty))
308 "volatile_store" => {
309 let dst = args[0].deref(self.cx());
310 args[1].val.volatile_store(self, dst);
313 "unaligned_volatile_store" => {
314 let dst = args[0].deref(self.cx());
315 args[1].val.unaligned_volatile_store(self, dst);
318 "prefetch_read_data" | "prefetch_write_data" |
319 "prefetch_read_instruction" | "prefetch_write_instruction" => {
320 let expect = self.get_intrinsic(&("llvm.prefetch"));
321 let (rw, cache_type) = match name {
322 "prefetch_read_data" => (0, 1),
323 "prefetch_write_data" => (1, 1),
324 "prefetch_read_instruction" => (0, 0),
325 "prefetch_write_instruction" => (1, 0),
332 self.const_i32(cache_type)
335 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
336 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
337 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
338 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
339 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
341 match int_type_width_signed(ty, self) {
342 Some((width, signed)) =>
345 let y = self.const_bool(false);
346 let llfn = self.get_intrinsic(
347 &format!("llvm.{}.i{}", name, width),
349 self.call(llfn, &[args[0].immediate(), y], None)
351 "ctlz_nonzero" | "cttz_nonzero" => {
352 let y = self.const_bool(true);
353 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
354 let llfn = self.get_intrinsic(llvm_name);
355 self.call(llfn, &[args[0].immediate(), y], None)
357 "ctpop" => self.call(
358 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
359 &[args[0].immediate()],
364 args[0].immediate() // byte swap a u8/i8 is just a no-op
368 &format!("llvm.bswap.i{}", width),
370 &[args[0].immediate()],
378 &format!("llvm.bitreverse.i{}", width),
380 &[args[0].immediate()],
384 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
385 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
386 if signed { 's' } else { 'u' },
388 let llfn = self.get_intrinsic(&intrinsic);
390 // Convert `i1` to a `bool`, and write it to the out parameter
391 let pair = self.call(llfn, &[
395 let val = self.extract_value(pair, 0);
396 let overflow = self.extract_value(pair, 1);
397 let overflow = self.zext(overflow, self.type_bool());
399 let dest = result.project_field(self, 0);
400 self.store(val, dest.llval, dest.align);
401 let dest = result.project_field(self, 1);
402 self.store(overflow, dest.llval, dest.align);
406 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
407 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
408 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
411 self.exactsdiv(args[0].immediate(), args[1].immediate())
413 self.exactudiv(args[0].immediate(), args[1].immediate())
417 self.sdiv(args[0].immediate(), args[1].immediate())
419 self.udiv(args[0].immediate(), args[1].immediate())
423 self.srem(args[0].immediate(), args[1].immediate())
425 self.urem(args[0].immediate(), args[1].immediate())
427 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
430 self.ashr(args[0].immediate(), args[1].immediate())
432 self.lshr(args[0].immediate(), args[1].immediate())
434 "rotate_left" | "rotate_right" => {
435 let is_left = name == "rotate_left";
436 let val = args[0].immediate();
437 let raw_shift = args[1].immediate();
438 if llvm_util::get_major_version() >= 7 {
439 // rotate = funnel shift with first two args the same
440 let llvm_name = &format!("llvm.fsh{}.i{}",
441 if is_left { 'l' } else { 'r' }, width);
442 let llfn = self.get_intrinsic(llvm_name);
443 self.call(llfn, &[val, val, raw_shift], None)
445 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
446 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
447 let width = self.const_uint(
451 let shift = self.urem(raw_shift, width);
452 let width_minus_raw_shift = self.sub(width, raw_shift);
453 let inv_shift = self.urem(width_minus_raw_shift, width);
454 let shift1 = self.shl(
456 if is_left { shift } else { inv_shift },
458 let shift2 = self.lshr(
460 if !is_left { shift } else { inv_shift },
462 self.or(shift1, shift2)
465 "saturating_add" | "saturating_sub" => {
466 let is_add = name == "saturating_add";
467 let lhs = args[0].immediate();
468 let rhs = args[1].immediate();
469 if llvm_util::get_major_version() >= 8 {
470 let llvm_name = &format!("llvm.{}{}.sat.i{}",
471 if signed { 's' } else { 'u' },
472 if is_add { "add" } else { "sub" },
474 let llfn = self.get_intrinsic(llvm_name);
475 self.call(llfn, &[lhs, rhs], None)
477 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
478 if signed { 's' } else { 'u' },
479 if is_add { "add" } else { "sub" },
481 let llfn = self.get_intrinsic(llvm_name);
482 let pair = self.call(llfn, &[lhs, rhs], None);
483 let val = self.extract_value(pair, 0);
484 let overflow = self.extract_value(pair, 1);
485 let llty = self.type_ix(width);
487 let limit = if signed {
488 let limit_lo = self.const_uint_big(
489 llty, (i128::MIN >> (128 - width)) as u128);
490 let limit_hi = self.const_uint_big(
491 llty, (i128::MAX >> (128 - width)) as u128);
493 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
494 self.select(neg, limit_hi, limit_lo)
496 self.const_uint_big(llty, u128::MAX >> (128 - width))
498 self.const_uint(llty, 0)
500 self.select(overflow, limit, val)
506 span_invalid_monomorphization_error(
508 &format!("invalid monomorphization of `{}` intrinsic: \
509 expected basic integer type, found `{}`", name, ty));
515 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
516 match float_type_width(arg_tys[0]) {
519 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
520 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
521 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
522 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
523 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
527 span_invalid_monomorphization_error(
529 &format!("invalid monomorphization of `{}` intrinsic: \
530 expected basic float type, found `{}`", name, arg_tys[0]));
537 "discriminant_value" => {
538 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
541 name if name.starts_with("simd_") => {
542 match generic_simd_intrinsic(self, name,
551 // This requires that atomic intrinsics follow a specific naming pattern:
552 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
553 name if name.starts_with("atomic_") => {
554 use rustc_codegen_ssa::common::AtomicOrdering::*;
555 use rustc_codegen_ssa::common::
556 {SynchronizationScope, AtomicRmwBinOp};
558 let split: Vec<&str> = name.split('_').collect();
560 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
561 let (order, failorder) = match split.len() {
562 2 => (SequentiallyConsistent, SequentiallyConsistent),
563 3 => match split[2] {
564 "unordered" => (Unordered, Unordered),
565 "relaxed" => (Monotonic, Monotonic),
566 "acq" => (Acquire, Acquire),
567 "rel" => (Release, Monotonic),
568 "acqrel" => (AcquireRelease, Acquire),
569 "failrelaxed" if is_cxchg =>
570 (SequentiallyConsistent, Monotonic),
571 "failacq" if is_cxchg =>
572 (SequentiallyConsistent, Acquire),
573 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
575 4 => match (split[2], split[3]) {
576 ("acq", "failrelaxed") if is_cxchg =>
577 (Acquire, Monotonic),
578 ("acqrel", "failrelaxed") if is_cxchg =>
579 (AcquireRelease, Monotonic),
580 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
582 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
585 let invalid_monomorphization = |ty| {
586 span_invalid_monomorphization_error(tcx.sess, span,
587 &format!("invalid monomorphization of `{}` intrinsic: \
588 expected basic integer type, found `{}`", name, ty));
592 "cxchg" | "cxchgweak" => {
593 let ty = substs.type_at(0);
594 if int_type_width_signed(ty, self).is_some() {
595 let weak = split[1] == "cxchgweak";
596 let pair = self.atomic_cmpxchg(
603 let val = self.extract_value(pair, 0);
604 let success = self.extract_value(pair, 1);
605 let success = self.zext(success, self.type_bool());
607 let dest = result.project_field(self, 0);
608 self.store(val, dest.llval, dest.align);
609 let dest = result.project_field(self, 1);
610 self.store(success, dest.llval, dest.align);
613 return invalid_monomorphization(ty);
618 let ty = substs.type_at(0);
619 if int_type_width_signed(ty, self).is_some() {
620 let size = self.size_of(ty);
621 self.atomic_load(args[0].immediate(), order, size)
623 return invalid_monomorphization(ty);
628 let ty = substs.type_at(0);
629 if int_type_width_signed(ty, self).is_some() {
630 let size = self.size_of(ty);
639 return invalid_monomorphization(ty);
644 self.atomic_fence(order, SynchronizationScope::CrossThread);
648 "singlethreadfence" => {
649 self.atomic_fence(order, SynchronizationScope::SingleThread);
653 // These are all AtomicRMW ops
655 let atom_op = match op {
656 "xchg" => AtomicRmwBinOp::AtomicXchg,
657 "xadd" => AtomicRmwBinOp::AtomicAdd,
658 "xsub" => AtomicRmwBinOp::AtomicSub,
659 "and" => AtomicRmwBinOp::AtomicAnd,
660 "nand" => AtomicRmwBinOp::AtomicNand,
661 "or" => AtomicRmwBinOp::AtomicOr,
662 "xor" => AtomicRmwBinOp::AtomicXor,
663 "max" => AtomicRmwBinOp::AtomicMax,
664 "min" => AtomicRmwBinOp::AtomicMin,
665 "umax" => AtomicRmwBinOp::AtomicUMax,
666 "umin" => AtomicRmwBinOp::AtomicUMin,
667 _ => self.sess().fatal("unknown atomic operation")
670 let ty = substs.type_at(0);
671 if int_type_width_signed(ty, self).is_some() {
679 return invalid_monomorphization(ty);
685 "nontemporal_store" => {
686 let dst = args[0].deref(self.cx());
687 args[1].val.nontemporal_store(self, dst);
691 _ => bug!("unknown intrinsic '{}'", name),
694 if !fn_ty.ret.is_ignore() {
695 if let PassMode::Cast(ty) = fn_ty.ret.mode {
696 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
697 let ptr = self.pointercast(result.llval, ptr_llty);
698 self.store(llval, ptr, result.align);
700 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
701 .val.store(self, result);
706 fn abort(&mut self) {
707 let fnname = self.get_intrinsic(&("llvm.trap"));
708 self.call(fnname, &[], None);
711 fn assume(&mut self, val: Self::Value) {
712 let assume_intrinsic = self.get_intrinsic("llvm.assume");
713 self.call(assume_intrinsic, &[val], None);
716 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
717 let expect = self.get_intrinsic(&"llvm.expect.i1");
718 self.call(expect, &[cond, self.const_bool(expected)], None)
721 fn va_start(&mut self, list: &'ll Value) -> &'ll Value {
722 let target = &self.cx.tcx.sess.target.target;
723 let arch = &target.arch;
724 // A pointer to the architecture specific structure is passed to this
725 // function. For pointer variants (i686, RISC-V, Windows, etc), we
726 // should do do nothing, as the address to the pointer is needed. For
727 // architectures with a architecture specific structure (`Aarch64`,
728 // `X86_64`, etc), this function should load the structure from the
730 let va_list = match &**arch {
731 _ if target.options.is_like_windows => list,
732 "aarch64" if target.target_os == "ios" => list,
733 "aarch64" | "x86_64" | "powerpc" =>
734 self.load(list, self.tcx().data_layout.pointer_align.abi),
737 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
738 self.call(intrinsic, &[va_list], None)
741 fn va_end(&mut self, list: &'ll Value) -> &'ll Value {
742 let target = &self.cx.tcx.sess.target.target;
743 let arch = &target.arch;
744 // See the comment in `va_start` for the purpose of the following.
745 let va_list = match &**arch {
746 _ if target.options.is_like_windows => list,
747 "aarch64" if target.target_os == "ios" => list,
748 "aarch64" | "x86_64" | "powerpc" =>
749 self.load(list, self.tcx().data_layout.pointer_align.abi),
752 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
753 self.call(intrinsic, &[va_list], None)
758 bx: &mut Builder<'a, 'll, 'tcx>,
766 let (size, align) = bx.size_and_align_of(ty);
767 let size = bx.mul(bx.const_usize(size.bytes()), count);
768 let flags = if volatile {
774 bx.memmove(dst, align, src, align, size, flags);
776 bx.memcpy(dst, align, src, align, size, flags);
781 bx: &mut Builder<'a, 'll, 'tcx>,
788 let (size, align) = bx.size_and_align_of(ty);
789 let size = bx.mul(bx.const_usize(size.bytes()), count);
790 let flags = if volatile {
795 bx.memset(dst, val, size, align, flags);
799 bx: &mut Builder<'a, 'll, 'tcx>,
802 local_ptr: &'ll Value,
805 if bx.sess().no_landing_pads() {
806 bx.call(func, &[data], None);
807 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
808 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
809 } else if wants_msvc_seh(bx.sess()) {
810 codegen_msvc_try(bx, func, data, local_ptr, dest);
812 codegen_gnu_try(bx, func, data, local_ptr, dest);
816 // MSVC's definition of the `rust_try` function.
818 // This implementation uses the new exception handling instructions in LLVM
819 // which have support in LLVM for SEH on MSVC targets. Although these
820 // instructions are meant to work for all targets, as of the time of this
821 // writing, however, LLVM does not recommend the usage of these new instructions
822 // as the old ones are still more optimized.
824 bx: &mut Builder<'a, 'll, 'tcx>,
827 local_ptr: &'ll Value,
830 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
831 bx.set_personality_fn(bx.eh_personality());
833 let mut normal = bx.build_sibling_block("normal");
834 let mut catchswitch = bx.build_sibling_block("catchswitch");
835 let mut catchpad = bx.build_sibling_block("catchpad");
836 let mut caught = bx.build_sibling_block("caught");
838 let func = llvm::get_param(bx.llfn(), 0);
839 let data = llvm::get_param(bx.llfn(), 1);
840 let local_ptr = llvm::get_param(bx.llfn(), 2);
842 // We're generating an IR snippet that looks like:
844 // declare i32 @rust_try(%func, %data, %ptr) {
845 // %slot = alloca i64*
846 // invoke %func(%data) to label %normal unwind label %catchswitch
852 // %cs = catchswitch within none [%catchpad] unwind to caller
855 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
856 // %ptr[0] = %slot[0]
857 // %ptr[1] = %slot[1]
858 // catchret from %tok to label %caught
864 // This structure follows the basic usage of throw/try/catch in LLVM.
865 // For example, compile this C++ snippet to see what LLVM generates:
867 // #include <stdint.h>
869 // int bar(void (*foo)(void), uint64_t *ret) {
873 // } catch(uint64_t a[2]) {
880 // More information can be found in libstd's seh.rs implementation.
881 let i64p = bx.type_ptr_to(bx.type_i64());
882 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
883 let slot = bx.alloca(i64p, "slot", ptr_align);
884 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
886 normal.ret(bx.const_i32(0));
888 let cs = catchswitch.catch_switch(None, None, 1);
889 catchswitch.add_handler(cs, catchpad.llbb());
891 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
892 Some(did) => bx.get_static(did),
893 None => bug!("msvc_try_filter not defined"),
895 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
896 let addr = catchpad.load(slot, ptr_align);
898 let i64_align = bx.tcx().data_layout.i64_align.abi;
899 let arg1 = catchpad.load(addr, i64_align);
900 let val1 = bx.const_i32(1);
901 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
902 let arg2 = catchpad.load(gep1, i64_align);
903 let local_ptr = catchpad.bitcast(local_ptr, i64p);
904 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
905 catchpad.store(arg1, local_ptr, i64_align);
906 catchpad.store(arg2, gep2, i64_align);
907 catchpad.catch_ret(&funclet, caught.llbb());
909 caught.ret(bx.const_i32(1));
912 // Note that no invoke is used here because by definition this function
913 // can't panic (that's what it's catching).
914 let ret = bx.call(llfn, &[func, data, local_ptr], None);
915 let i32_align = bx.tcx().data_layout.i32_align.abi;
916 bx.store(ret, dest, i32_align);
919 // Definition of the standard "try" function for Rust using the GNU-like model
920 // of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke
923 // This codegen is a little surprising because we always call a shim
924 // function instead of inlining the call to `invoke` manually here. This is done
925 // because in LLVM we're only allowed to have one personality per function
926 // definition. The call to the `try` intrinsic is being inlined into the
927 // function calling it, and that function may already have other personality
928 // functions in play. By calling a shim we're guaranteed that our shim will have
929 // the right personality function.
931 bx: &mut Builder<'a, 'll, 'tcx>,
934 local_ptr: &'ll Value,
937 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
938 // Codegens the shims described above:
941 // invoke %func(%args...) normal %normal unwind %catch
947 // (ptr, _) = landingpad
948 // store ptr, %local_ptr
951 // Note that the `local_ptr` data passed into the `try` intrinsic is
952 // expected to be `*mut *mut u8` for this to actually work, but that's
953 // managed by the standard library.
955 let mut then = bx.build_sibling_block("then");
956 let mut catch = bx.build_sibling_block("catch");
958 let func = llvm::get_param(bx.llfn(), 0);
959 let data = llvm::get_param(bx.llfn(), 1);
960 let local_ptr = llvm::get_param(bx.llfn(), 2);
961 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
962 then.ret(bx.const_i32(0));
964 // Type indicator for the exception being thrown.
966 // The first value in this tuple is a pointer to the exception object
967 // being thrown. The second value is a "selector" indicating which of
968 // the landing pad clauses the exception's type had been matched to.
969 // rust_try ignores the selector.
970 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
971 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
972 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
973 let ptr = catch.extract_value(vals, 0);
974 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
975 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
976 catch.store(ptr, bitcast, ptr_align);
977 catch.ret(bx.const_i32(1));
980 // Note that no invoke is used here because by definition this function
981 // can't panic (that's what it's catching).
982 let ret = bx.call(llfn, &[func, data, local_ptr], None);
983 let i32_align = bx.tcx().data_layout.i32_align.abi;
984 bx.store(ret, dest, i32_align);
987 // Helper function to give a Block to a closure to codegen a shim function.
988 // This is currently primarily used for the `try` intrinsic functions above.
989 fn gen_fn<'ll, 'tcx>(
990 cx: &CodegenCx<'ll, 'tcx>,
992 inputs: Vec<Ty<'tcx>>,
994 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
996 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1000 hir::Unsafety::Unsafe,
1003 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1004 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
1005 let bx = Builder::new_block(cx, llfn, "entry-block");
1010 // Helper function used to get a handle to the `__rust_try` function used to
1011 // catch exceptions.
1013 // This function is only generated once and is then cached.
1014 fn get_rust_try_fn<'ll, 'tcx>(
1015 cx: &CodegenCx<'ll, 'tcx>,
1016 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1018 if let Some(llfn) = cx.rust_try_fn.get() {
1022 // Define the type up front for the signature of the rust_try function.
1024 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1025 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1029 hir::Unsafety::Unsafe,
1032 let output = tcx.types.i32;
1033 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1034 cx.rust_try_fn.set(Some(rust_try));
1038 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1039 span_err!(a, b, E0511, "{}", c);
1042 fn generic_simd_intrinsic(
1043 bx: &mut Builder<'a, 'll, 'tcx>,
1045 callee_ty: Ty<'tcx>,
1046 args: &[OperandRef<'tcx, &'ll Value>],
1048 llret_ty: &'ll Type,
1050 ) -> Result<&'ll Value, ()> {
1051 // macros for error handling:
1052 macro_rules! emit_error {
1056 ($msg: tt, $($fmt: tt)*) => {
1057 span_invalid_monomorphization_error(
1059 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1064 macro_rules! return_error {
1067 emit_error!($($fmt)*);
1073 macro_rules! require {
1074 ($cond: expr, $($fmt: tt)*) => {
1076 return_error!($($fmt)*);
1081 macro_rules! require_simd {
1082 ($ty: expr, $position: expr) => {
1083 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1088 let sig = tcx.normalize_erasing_late_bound_regions(
1089 ty::ParamEnv::reveal_all(),
1090 &callee_ty.fn_sig(tcx),
1092 let arg_tys = sig.inputs();
1094 if name == "simd_select_bitmask" {
1095 let in_ty = arg_tys[0];
1096 let m_len = match in_ty.sty {
1097 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1098 // of intentional as there's not currently a use case for that.
1099 ty::Int(i) => i.bit_width().unwrap(),
1100 ty::Uint(i) => i.bit_width().unwrap(),
1101 _ => return_error!("`{}` is not an integral type", in_ty),
1103 require_simd!(arg_tys[1], "argument");
1104 let v_len = arg_tys[1].simd_size(tcx);
1105 require!(m_len == v_len,
1106 "mismatched lengths: mask length `{}` != other vector length `{}`",
1109 let i1 = bx.type_i1();
1110 let i1xn = bx.type_vector(i1, m_len as u64);
1111 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1112 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1115 // every intrinsic below takes a SIMD vector as its first argument
1116 require_simd!(arg_tys[0], "input");
1117 let in_ty = arg_tys[0];
1118 let in_elem = arg_tys[0].simd_type(tcx);
1119 let in_len = arg_tys[0].simd_size(tcx);
1121 let comparison = match name {
1122 "simd_eq" => Some(hir::BinOpKind::Eq),
1123 "simd_ne" => Some(hir::BinOpKind::Ne),
1124 "simd_lt" => Some(hir::BinOpKind::Lt),
1125 "simd_le" => Some(hir::BinOpKind::Le),
1126 "simd_gt" => Some(hir::BinOpKind::Gt),
1127 "simd_ge" => Some(hir::BinOpKind::Ge),
1131 if let Some(cmp_op) = comparison {
1132 require_simd!(ret_ty, "return");
1134 let out_len = ret_ty.simd_size(tcx);
1135 require!(in_len == out_len,
1136 "expected return type with length {} (same as input type `{}`), \
1137 found `{}` with length {}",
1140 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1141 "expected return type with integer elements, found `{}` with non-integer `{}`",
1143 ret_ty.simd_type(tcx));
1145 return Ok(compare_simd_types(bx,
1146 args[0].immediate(),
1147 args[1].immediate(),
1153 if name.starts_with("simd_shuffle") {
1154 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1155 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1157 require_simd!(ret_ty, "return");
1159 let out_len = ret_ty.simd_size(tcx);
1160 require!(out_len == n,
1161 "expected return type of length {}, found `{}` with length {}",
1162 n, ret_ty, out_len);
1163 require!(in_elem == ret_ty.simd_type(tcx),
1164 "expected return element type `{}` (element of input `{}`), \
1165 found `{}` with element type `{}`",
1167 ret_ty, ret_ty.simd_type(tcx));
1169 let total_len = in_len as u128 * 2;
1171 let vector = args[2].immediate();
1173 let indices: Option<Vec<_>> = (0..n)
1176 let val = bx.const_get_elt(vector, i as u64);
1177 match bx.const_to_opt_u128(val, true) {
1179 emit_error!("shuffle index #{} is not a constant", arg_idx);
1182 Some(idx) if idx >= total_len => {
1183 emit_error!("shuffle index #{} is out of bounds (limit {})",
1184 arg_idx, total_len);
1187 Some(idx) => Some(bx.const_i32(idx as i32)),
1191 let indices = match indices {
1193 None => return Ok(bx.const_null(llret_ty))
1196 return Ok(bx.shuffle_vector(args[0].immediate(),
1197 args[1].immediate(),
1198 bx.const_vector(&indices)))
1201 if name == "simd_insert" {
1202 require!(in_elem == arg_tys[2],
1203 "expected inserted type `{}` (element of input `{}`), found `{}`",
1204 in_elem, in_ty, arg_tys[2]);
1205 return Ok(bx.insert_element(args[0].immediate(),
1206 args[2].immediate(),
1207 args[1].immediate()))
1209 if name == "simd_extract" {
1210 require!(ret_ty == in_elem,
1211 "expected return type `{}` (element of input `{}`), found `{}`",
1212 in_elem, in_ty, ret_ty);
1213 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1216 if name == "simd_select" {
1217 let m_elem_ty = in_elem;
1219 require_simd!(arg_tys[1], "argument");
1220 let v_len = arg_tys[1].simd_size(tcx);
1221 require!(m_len == v_len,
1222 "mismatched lengths: mask length `{}` != other vector length `{}`",
1225 match m_elem_ty.sty {
1227 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1229 // truncate the mask to a vector of i1s
1230 let i1 = bx.type_i1();
1231 let i1xn = bx.type_vector(i1, m_len as u64);
1232 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1233 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1236 if name == "simd_bitmask" {
1237 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1238 // vector mask and returns an unsigned integer containing the most
1239 // significant bit (MSB) of each lane.
1240 use rustc_target::abi::HasDataLayout;
1242 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1244 let expected_int_bits = in_len.max(8);
1246 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1248 "bitmask `{}`, expected `u{}`",
1249 ret_ty, expected_int_bits
1253 // Integer vector <i{in_bitwidth} x in_len>:
1254 let (i_xn, in_elem_bitwidth) = match in_elem.sty {
1256 args[0].immediate(),
1257 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1260 args[0].immediate(),
1261 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1264 "vector argument `{}`'s element type `{}`, expected integer element type",
1269 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1270 let shift_indices = vec![
1271 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _); in_len
1273 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1274 // Truncate vector to an <i1 x N>
1275 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1276 // Bitcast <i1 x N> to iN:
1277 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1278 // Zero-extend iN to the bitmask type:
1279 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1282 fn simd_simple_float_intrinsic(
1284 in_elem: &::rustc::ty::TyS<'_>,
1285 in_ty: &::rustc::ty::TyS<'_>,
1287 bx: &mut Builder<'a, 'll, 'tcx>,
1289 args: &[OperandRef<'tcx, &'ll Value>],
1290 ) -> Result<&'ll Value, ()> {
1291 macro_rules! emit_error {
1295 ($msg: tt, $($fmt: tt)*) => {
1296 span_invalid_monomorphization_error(
1298 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1302 macro_rules! return_error {
1305 emit_error!($($fmt)*);
1310 let ety = match in_elem.sty {
1311 ty::Float(f) if f.bit_width() == 32 => {
1312 if in_len < 2 || in_len > 16 {
1314 "unsupported floating-point vector `{}` with length `{}` \
1315 out-of-range [2, 16]",
1320 ty::Float(f) if f.bit_width() == 64 => {
1321 if in_len < 2 || in_len > 8 {
1322 return_error!("unsupported floating-point vector `{}` with length `{}` \
1323 out-of-range [2, 8]",
1329 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1333 return_error!("`{}` is not a floating-point type", in_ty);
1337 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1338 let intrinsic = bx.get_intrinsic(&llvm_name);
1339 let c = bx.call(intrinsic,
1340 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1342 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1348 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1351 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1354 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1357 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1360 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1363 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1366 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1369 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1372 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1375 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1378 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1381 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1384 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1387 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1389 _ => { /* fallthrough */ }
1393 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1394 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1395 fn llvm_vector_str(elem_ty: ty::Ty<'_>, vec_len: usize, no_pointers: usize) -> String {
1396 let p0s: String = "p0".repeat(no_pointers);
1398 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1399 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1400 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1401 _ => unreachable!(),
1405 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty<'_>, vec_len: usize,
1406 mut no_pointers: usize) -> &'ll Type {
1407 // FIXME: use cx.layout_of(ty).llvm_type() ?
1408 let mut elem_ty = match elem_ty.sty {
1409 ty::Int(v) => cx.type_int_from_ty( v),
1410 ty::Uint(v) => cx.type_uint_from_ty( v),
1411 ty::Float(v) => cx.type_float_from_ty( v),
1412 _ => unreachable!(),
1414 while no_pointers > 0 {
1415 elem_ty = cx.type_ptr_to(elem_ty);
1418 cx.type_vector(elem_ty, vec_len as u64)
1422 if name == "simd_gather" {
1423 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1424 // mask: <N x i{M}>) -> <N x T>
1425 // * N: number of elements in the input vectors
1426 // * T: type of the element to load
1427 // * M: any integer width is supported, will be truncated to i1
1429 // All types must be simd vector types
1430 require_simd!(in_ty, "first");
1431 require_simd!(arg_tys[1], "second");
1432 require_simd!(arg_tys[2], "third");
1433 require_simd!(ret_ty, "return");
1435 // Of the same length:
1436 require!(in_len == arg_tys[1].simd_size(tcx),
1437 "expected {} argument with length {} (same as input type `{}`), \
1438 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1439 arg_tys[1].simd_size(tcx));
1440 require!(in_len == arg_tys[2].simd_size(tcx),
1441 "expected {} argument with length {} (same as input type `{}`), \
1442 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1443 arg_tys[2].simd_size(tcx));
1445 // The return type must match the first argument type
1446 require!(ret_ty == in_ty,
1447 "expected return type `{}`, found `{}`",
1450 // This counts how many pointers
1451 fn ptr_count(t: ty::Ty<'_>) -> usize {
1453 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1459 fn non_ptr(t: ty::Ty<'_>) -> ty::Ty<'_> {
1461 ty::RawPtr(p) => non_ptr(p.ty),
1466 // The second argument must be a simd vector with an element type that's a pointer
1467 // to the element type of the first argument
1468 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1469 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1470 non_ptr(arg_tys[1].simd_type(tcx))),
1472 require!(false, "expected element type `{}` of second argument `{}` \
1473 to be a pointer to the element type `{}` of the first \
1474 argument `{}`, found `{}` != `*_ {}`",
1475 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1476 arg_tys[1].simd_type(tcx), in_elem);
1480 assert!(pointer_count > 0);
1481 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1482 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1484 // The element type of the third argument must be a signed integer type of any width:
1485 match arg_tys[2].simd_type(tcx).sty {
1488 require!(false, "expected element type `{}` of third argument `{}` \
1489 to be a signed integer type",
1490 arg_tys[2].simd_type(tcx), arg_tys[2]);
1494 // Alignment of T, must be a constant integer value:
1495 let alignment_ty = bx.type_i32();
1496 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1498 // Truncate the mask vector to a vector of i1s:
1499 let (mask, mask_ty) = {
1500 let i1 = bx.type_i1();
1501 let i1xn = bx.type_vector(i1, in_len as u64);
1502 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1505 // Type of the vector of pointers:
1506 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1507 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1509 // Type of the vector of elements:
1510 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1511 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1513 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1514 llvm_elem_vec_str, llvm_pointer_vec_str);
1515 let f = bx.declare_cfn(&llvm_intrinsic,
1517 llvm_pointer_vec_ty,
1520 llvm_elem_vec_ty], llvm_elem_vec_ty));
1521 llvm::SetUnnamedAddr(f, false);
1522 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1527 if name == "simd_scatter" {
1528 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1529 // mask: <N x i{M}>) -> ()
1530 // * N: number of elements in the input vectors
1531 // * T: type of the element to load
1532 // * M: any integer width is supported, will be truncated to i1
1534 // All types must be simd vector types
1535 require_simd!(in_ty, "first");
1536 require_simd!(arg_tys[1], "second");
1537 require_simd!(arg_tys[2], "third");
1539 // Of the same length:
1540 require!(in_len == arg_tys[1].simd_size(tcx),
1541 "expected {} argument with length {} (same as input type `{}`), \
1542 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1543 arg_tys[1].simd_size(tcx));
1544 require!(in_len == arg_tys[2].simd_size(tcx),
1545 "expected {} argument with length {} (same as input type `{}`), \
1546 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1547 arg_tys[2].simd_size(tcx));
1549 // This counts how many pointers
1550 fn ptr_count(t: ty::Ty<'_>) -> usize {
1552 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1558 fn non_ptr(t: ty::Ty<'_>) -> ty::Ty<'_> {
1560 ty::RawPtr(p) => non_ptr(p.ty),
1565 // The second argument must be a simd vector with an element type that's a pointer
1566 // to the element type of the first argument
1567 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1568 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1569 => (ptr_count(arg_tys[1].simd_type(tcx)),
1570 non_ptr(arg_tys[1].simd_type(tcx))),
1572 require!(false, "expected element type `{}` of second argument `{}` \
1573 to be a pointer to the element type `{}` of the first \
1574 argument `{}`, found `{}` != `*mut {}`",
1575 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1576 arg_tys[1].simd_type(tcx), in_elem);
1580 assert!(pointer_count > 0);
1581 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1582 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1584 // The element type of the third argument must be a signed integer type of any width:
1585 match arg_tys[2].simd_type(tcx).sty {
1588 require!(false, "expected element type `{}` of third argument `{}` \
1589 to be a signed integer type",
1590 arg_tys[2].simd_type(tcx), arg_tys[2]);
1594 // Alignment of T, must be a constant integer value:
1595 let alignment_ty = bx.type_i32();
1596 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1598 // Truncate the mask vector to a vector of i1s:
1599 let (mask, mask_ty) = {
1600 let i1 = bx.type_i1();
1601 let i1xn = bx.type_vector(i1, in_len as u64);
1602 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1605 let ret_t = bx.type_void();
1607 // Type of the vector of pointers:
1608 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1609 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1611 // Type of the vector of elements:
1612 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1613 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1615 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1616 llvm_elem_vec_str, llvm_pointer_vec_str);
1617 let f = bx.declare_cfn(&llvm_intrinsic,
1618 bx.type_func(&[llvm_elem_vec_ty,
1619 llvm_pointer_vec_ty,
1622 llvm::SetUnnamedAddr(f, false);
1623 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1628 macro_rules! arith_red {
1629 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1631 require!(ret_ty == in_elem,
1632 "expected return type `{}` (element of input `{}`), found `{}`",
1633 in_elem, in_ty, ret_ty);
1634 return match in_elem.sty {
1635 ty::Int(_) | ty::Uint(_) => {
1636 let r = bx.$integer_reduce(args[0].immediate());
1638 // if overflow occurs, the result is the
1639 // mathematical result modulo 2^n:
1640 if name.contains("mul") {
1641 Ok(bx.mul(args[1].immediate(), r))
1643 Ok(bx.add(args[1].immediate(), r))
1646 Ok(bx.$integer_reduce(args[0].immediate()))
1650 // ordered arithmetic reductions take an accumulator
1651 let acc = if $ordered {
1652 let acc = args[1].immediate();
1653 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1654 // * if the accumulator of the fadd isn't 0, incorrect
1655 // code is generated
1656 // * if the accumulator of the fmul isn't 1, incorrect
1657 // code is generated
1658 match bx.const_get_real(acc) {
1659 None => return_error!("accumulator of {} is not a constant", $name),
1660 Some((v, loses_info)) => {
1661 if $name.contains("mul") && v != 1.0_f64 {
1662 return_error!("accumulator of {} is not 1.0", $name);
1663 } else if $name.contains("add") && v != 0.0_f64 {
1664 return_error!("accumulator of {} is not 0.0", $name);
1665 } else if loses_info {
1666 return_error!("accumulator of {} loses information", $name);
1672 // unordered arithmetic reductions do not:
1673 match f.bit_width() {
1674 32 => bx.const_undef(bx.type_f32()),
1675 64 => bx.const_undef(bx.type_f64()),
1678 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1679 $name, in_ty, in_elem, v, ret_ty
1684 Ok(bx.$float_reduce(acc, args[0].immediate()))
1688 "unsupported {} from `{}` with element `{}` to `{}`",
1689 $name, in_ty, in_elem, ret_ty
1697 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1698 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1699 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1700 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1702 macro_rules! minmax_red {
1703 ($name:tt: $int_red:ident, $float_red:ident) => {
1705 require!(ret_ty == in_elem,
1706 "expected return type `{}` (element of input `{}`), found `{}`",
1707 in_elem, in_ty, ret_ty);
1708 return match in_elem.sty {
1710 Ok(bx.$int_red(args[0].immediate(), true))
1713 Ok(bx.$int_red(args[0].immediate(), false))
1716 Ok(bx.$float_red(args[0].immediate()))
1719 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1720 $name, in_ty, in_elem, ret_ty)
1728 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1729 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1731 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1732 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1734 macro_rules! bitwise_red {
1735 ($name:tt : $red:ident, $boolean:expr) => {
1737 let input = if !$boolean {
1738 require!(ret_ty == in_elem,
1739 "expected return type `{}` (element of input `{}`), found `{}`",
1740 in_elem, in_ty, ret_ty);
1744 ty::Int(_) | ty::Uint(_) => {},
1746 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1747 $name, in_ty, in_elem, ret_ty)
1751 // boolean reductions operate on vectors of i1s:
1752 let i1 = bx.type_i1();
1753 let i1xn = bx.type_vector(i1, in_len as u64);
1754 bx.trunc(args[0].immediate(), i1xn)
1756 return match in_elem.sty {
1757 ty::Int(_) | ty::Uint(_) => {
1758 let r = bx.$red(input);
1763 bx.zext(r, bx.type_bool())
1768 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1769 $name, in_ty, in_elem, ret_ty)
1776 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1777 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1778 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1779 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1780 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1782 if name == "simd_cast" {
1783 require_simd!(ret_ty, "return");
1784 let out_len = ret_ty.simd_size(tcx);
1785 require!(in_len == out_len,
1786 "expected return type with length {} (same as input type `{}`), \
1787 found `{}` with length {}",
1790 // casting cares about nominal type, not just structural type
1791 let out_elem = ret_ty.simd_type(tcx);
1793 if in_elem == out_elem { return Ok(args[0].immediate()); }
1795 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1797 let (in_style, in_width) = match in_elem.sty {
1798 // vectors of pointer-sized integers should've been
1799 // disallowed before here, so this unwrap is safe.
1800 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1801 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1802 ty::Float(f) => (Style::Float, f.bit_width()),
1803 _ => (Style::Unsupported, 0)
1805 let (out_style, out_width) = match out_elem.sty {
1806 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1807 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1808 ty::Float(f) => (Style::Float, f.bit_width()),
1809 _ => (Style::Unsupported, 0)
1812 match (in_style, out_style) {
1813 (Style::Int(in_is_signed), Style::Int(_)) => {
1814 return Ok(match in_width.cmp(&out_width) {
1815 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1816 Ordering::Equal => args[0].immediate(),
1817 Ordering::Less => if in_is_signed {
1818 bx.sext(args[0].immediate(), llret_ty)
1820 bx.zext(args[0].immediate(), llret_ty)
1824 (Style::Int(in_is_signed), Style::Float) => {
1825 return Ok(if in_is_signed {
1826 bx.sitofp(args[0].immediate(), llret_ty)
1828 bx.uitofp(args[0].immediate(), llret_ty)
1831 (Style::Float, Style::Int(out_is_signed)) => {
1832 return Ok(if out_is_signed {
1833 bx.fptosi(args[0].immediate(), llret_ty)
1835 bx.fptoui(args[0].immediate(), llret_ty)
1838 (Style::Float, Style::Float) => {
1839 return Ok(match in_width.cmp(&out_width) {
1840 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1841 Ordering::Equal => args[0].immediate(),
1842 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1845 _ => {/* Unsupported. Fallthrough. */}
1848 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1852 macro_rules! arith {
1853 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1854 $(if name == stringify!($name) {
1856 $($(ty::$p(_))|* => {
1857 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1862 "unsupported operation on `{}` with element `{}`",
1869 simd_add: Uint, Int => add, Float => fadd;
1870 simd_sub: Uint, Int => sub, Float => fsub;
1871 simd_mul: Uint, Int => mul, Float => fmul;
1872 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1873 simd_rem: Uint => urem, Int => srem, Float => frem;
1874 simd_shl: Uint, Int => shl;
1875 simd_shr: Uint => lshr, Int => ashr;
1876 simd_and: Uint, Int => and;
1877 simd_or: Uint, Int => or;
1878 simd_xor: Uint, Int => xor;
1879 simd_fmax: Float => maxnum;
1880 simd_fmin: Float => minnum;
1884 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1885 let lhs = args[0].immediate();
1886 let rhs = args[1].immediate();
1887 let is_add = name == "simd_saturating_add";
1888 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1889 let (signed, elem_width, elem_ty) = match in_elem.sty {
1893 i.bit_width().unwrap_or(ptr_bits),
1894 bx.cx.type_int_from_ty(i)
1899 i.bit_width().unwrap_or(ptr_bits),
1900 bx.cx.type_uint_from_ty(i)
1904 "expected element type `{}` of vector type `{}` \
1905 to be a signed or unsigned integer type",
1906 arg_tys[0].simd_type(tcx), arg_tys[0]
1910 let llvm_intrinsic = &format!(
1911 "llvm.{}{}.sat.v{}i{}",
1912 if signed { 's' } else { 'u' },
1913 if is_add { "add" } else { "sub" },
1916 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1918 let f = bx.declare_cfn(
1920 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1922 llvm::SetUnnamedAddr(f, false);
1923 let v = bx.call(f, &[lhs, rhs], None);
1927 span_bug!(span, "unknown SIMD intrinsic");
1930 // Returns the width of an int Ty, and if it's signed or not
1931 // Returns None if the type is not an integer
1932 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1934 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1936 ty::Int(t) => Some((match t {
1937 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1938 ast::IntTy::I8 => 8,
1939 ast::IntTy::I16 => 16,
1940 ast::IntTy::I32 => 32,
1941 ast::IntTy::I64 => 64,
1942 ast::IntTy::I128 => 128,
1944 ty::Uint(t) => Some((match t {
1945 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1946 ast::UintTy::U8 => 8,
1947 ast::UintTy::U16 => 16,
1948 ast::UintTy::U32 => 32,
1949 ast::UintTy::U64 => 64,
1950 ast::UintTy::U128 => 128,
1956 // Returns the width of a float Ty
1957 // Returns None if the type is not a float
1958 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1960 ty::Float(t) => Some(t.bit_width() as u64),