1 use crate::abi::{Abi, FnAbi, FnAbiLlvmExt, LlvmType, PassMode};
2 use crate::builder::Builder;
3 use crate::context::CodegenCx;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::va_arg::emit_va_arg;
8 use crate::value::Value;
11 use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh};
12 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
13 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
14 use rustc_codegen_ssa::mir::operand::OperandRef;
15 use rustc_codegen_ssa::mir::place::PlaceRef;
16 use rustc_codegen_ssa::traits::*;
18 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
19 use rustc_middle::ty::{self, Ty};
20 use rustc_middle::{bug, span_bug};
21 use rustc_span::{sym, symbol::kw, Span, Symbol};
22 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
23 use rustc_target::spec::PanicStrategy;
25 use std::cmp::Ordering;
28 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<(&'ll Type, &'ll Value)> {
29 let llvm_name = match name {
30 sym::sqrtf32 => "llvm.sqrt.f32",
31 sym::sqrtf64 => "llvm.sqrt.f64",
32 sym::powif32 => "llvm.powi.f32",
33 sym::powif64 => "llvm.powi.f64",
34 sym::sinf32 => "llvm.sin.f32",
35 sym::sinf64 => "llvm.sin.f64",
36 sym::cosf32 => "llvm.cos.f32",
37 sym::cosf64 => "llvm.cos.f64",
38 sym::powf32 => "llvm.pow.f32",
39 sym::powf64 => "llvm.pow.f64",
40 sym::expf32 => "llvm.exp.f32",
41 sym::expf64 => "llvm.exp.f64",
42 sym::exp2f32 => "llvm.exp2.f32",
43 sym::exp2f64 => "llvm.exp2.f64",
44 sym::logf32 => "llvm.log.f32",
45 sym::logf64 => "llvm.log.f64",
46 sym::log10f32 => "llvm.log10.f32",
47 sym::log10f64 => "llvm.log10.f64",
48 sym::log2f32 => "llvm.log2.f32",
49 sym::log2f64 => "llvm.log2.f64",
50 sym::fmaf32 => "llvm.fma.f32",
51 sym::fmaf64 => "llvm.fma.f64",
52 sym::fabsf32 => "llvm.fabs.f32",
53 sym::fabsf64 => "llvm.fabs.f64",
54 sym::minnumf32 => "llvm.minnum.f32",
55 sym::minnumf64 => "llvm.minnum.f64",
56 sym::maxnumf32 => "llvm.maxnum.f32",
57 sym::maxnumf64 => "llvm.maxnum.f64",
58 sym::copysignf32 => "llvm.copysign.f32",
59 sym::copysignf64 => "llvm.copysign.f64",
60 sym::floorf32 => "llvm.floor.f32",
61 sym::floorf64 => "llvm.floor.f64",
62 sym::ceilf32 => "llvm.ceil.f32",
63 sym::ceilf64 => "llvm.ceil.f64",
64 sym::truncf32 => "llvm.trunc.f32",
65 sym::truncf64 => "llvm.trunc.f64",
66 sym::rintf32 => "llvm.rint.f32",
67 sym::rintf64 => "llvm.rint.f64",
68 sym::nearbyintf32 => "llvm.nearbyint.f32",
69 sym::nearbyintf64 => "llvm.nearbyint.f64",
70 sym::roundf32 => "llvm.round.f32",
71 sym::roundf64 => "llvm.round.f64",
74 Some(cx.get_intrinsic(&llvm_name))
77 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
78 fn codegen_intrinsic_call(
80 instance: ty::Instance<'tcx>,
81 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
82 args: &[OperandRef<'tcx, &'ll Value>],
87 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
89 let (def_id, substs) = match *callee_ty.kind() {
90 ty::FnDef(def_id, substs) => (def_id, substs),
91 _ => bug!("expected fn item type, found {}", callee_ty),
94 let sig = callee_ty.fn_sig(tcx);
95 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
96 let arg_tys = sig.inputs();
97 let ret_ty = sig.output();
98 let name = tcx.item_name(def_id);
99 let name_str = &*name.as_str();
101 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
102 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
104 let simple = get_simple_intrinsic(self, name);
105 let llval = match name {
106 _ if simple.is_some() => {
107 let (simple_ty, simple_fn) = simple.unwrap();
111 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
116 self.call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(true)])
118 sym::unlikely => self
119 .call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(false)]),
130 sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[]),
132 self.call_intrinsic("llvm.va_copy", &[args[0].immediate(), args[1].immediate()])
135 match fn_abi.ret.layout.abi {
136 abi::Abi::Scalar(ref scalar) => {
138 Primitive::Int(..) => {
139 if self.cx().size_of(ret_ty).bytes() < 4 {
140 // `va_arg` should not be called on a integer type
141 // less than 4 bytes in length. If it is, promote
142 // the integer to a `i32` and truncate the result
143 // back to the smaller type.
144 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
145 self.trunc(promoted_result, llret_ty)
147 emit_va_arg(self, args[0], ret_ty)
150 Primitive::F64 | Primitive::Pointer => {
151 emit_va_arg(self, args[0], ret_ty)
153 // `va_arg` should never be used with the return type f32.
154 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
157 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
161 sym::volatile_load | sym::unaligned_volatile_load => {
162 let tp_ty = substs.type_at(0);
163 let ptr = args[0].immediate();
164 let load = if let PassMode::Cast(ty) = fn_abi.ret.mode {
165 let llty = ty.llvm_type(self);
166 let ptr = self.pointercast(ptr, self.type_ptr_to(llty));
167 self.volatile_load(llty, ptr)
169 self.volatile_load(self.layout_of(tp_ty).llvm_type(self), ptr)
171 let align = if name == sym::unaligned_volatile_load {
174 self.align_of(tp_ty).bytes() as u32
177 llvm::LLVMSetAlignment(load, align);
179 self.to_immediate(load, self.layout_of(tp_ty))
181 sym::volatile_store => {
182 let dst = args[0].deref(self.cx());
183 args[1].val.volatile_store(self, dst);
186 sym::unaligned_volatile_store => {
187 let dst = args[0].deref(self.cx());
188 args[1].val.unaligned_volatile_store(self, dst);
191 sym::prefetch_read_data
192 | sym::prefetch_write_data
193 | sym::prefetch_read_instruction
194 | sym::prefetch_write_instruction => {
195 let (rw, cache_type) = match name {
196 sym::prefetch_read_data => (0, 1),
197 sym::prefetch_write_data => (1, 1),
198 sym::prefetch_read_instruction => (0, 0),
199 sym::prefetch_write_instruction => (1, 0),
208 self.const_i32(cache_type),
221 | sym::saturating_add
222 | sym::saturating_sub => {
224 match int_type_width_signed(ty, self) {
225 Some((width, signed)) => match name {
226 sym::ctlz | sym::cttz => {
227 let y = self.const_bool(false);
229 &format!("llvm.{}.i{}", name, width),
230 &[args[0].immediate(), y],
233 sym::ctlz_nonzero | sym::cttz_nonzero => {
234 let y = self.const_bool(true);
235 let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
236 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
238 sym::ctpop => self.call_intrinsic(
239 &format!("llvm.ctpop.i{}", width),
240 &[args[0].immediate()],
244 args[0].immediate() // byte swap a u8/i8 is just a no-op
247 &format!("llvm.bswap.i{}", width),
248 &[args[0].immediate()],
252 sym::bitreverse => self.call_intrinsic(
253 &format!("llvm.bitreverse.i{}", width),
254 &[args[0].immediate()],
256 sym::rotate_left | sym::rotate_right => {
257 let is_left = name == sym::rotate_left;
258 let val = args[0].immediate();
259 let raw_shift = args[1].immediate();
260 // rotate = funnel shift with first two args the same
262 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
263 self.call_intrinsic(llvm_name, &[val, val, raw_shift])
265 sym::saturating_add | sym::saturating_sub => {
266 let is_add = name == sym::saturating_add;
267 let lhs = args[0].immediate();
268 let rhs = args[1].immediate();
269 let llvm_name = &format!(
271 if signed { 's' } else { 'u' },
272 if is_add { "add" } else { "sub" },
275 self.call_intrinsic(llvm_name, &[lhs, rhs])
280 span_invalid_monomorphization_error(
284 "invalid monomorphization of `{}` intrinsic: \
285 expected basic integer type, found `{}`",
296 let tp_ty = substs.type_at(0);
297 let layout = self.layout_of(tp_ty).layout;
298 let use_integer_compare = match layout.abi {
299 Scalar(_) | ScalarPair(_, _) => true,
300 Uninhabited | Vector { .. } => false,
301 Aggregate { .. } => {
302 // For rusty ABIs, small aggregates are actually passed
303 // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
304 // so we re-use that same threshold here.
305 layout.size <= self.data_layout().pointer_size * 2
309 let a = args[0].immediate();
310 let b = args[1].immediate();
311 if layout.size.bytes() == 0 {
312 self.const_bool(true)
313 } else if use_integer_compare {
314 let integer_ty = self.type_ix(layout.size.bits());
315 let ptr_ty = self.type_ptr_to(integer_ty);
316 let a_ptr = self.bitcast(a, ptr_ty);
317 let a_val = self.load(integer_ty, a_ptr, layout.align.abi);
318 let b_ptr = self.bitcast(b, ptr_ty);
319 let b_val = self.load(integer_ty, b_ptr, layout.align.abi);
320 self.icmp(IntPredicate::IntEQ, a_val, b_val)
322 let i8p_ty = self.type_i8p();
323 let a_ptr = self.bitcast(a, i8p_ty);
324 let b_ptr = self.bitcast(b, i8p_ty);
325 let n = self.const_usize(layout.size.bytes());
326 let cmp = self.call_intrinsic("memcmp", &[a_ptr, b_ptr, n]);
327 self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0))
332 args[0].val.store(self, result);
334 // We need to "use" the argument in some way LLVM can't introspect, and on
335 // targets that support it we can typically leverage inline assembly to do
336 // this. LLVM's interpretation of inline assembly is that it's, well, a black
337 // box. This isn't the greatest implementation since it probably deoptimizes
338 // more than we want, but it's so far good enough.
339 crate::asm::inline_asm_call(
347 ast::LlvmAsmDialect::Att,
350 .unwrap_or_else(|| bug!("failed to generate inline asm call for `black_box`"));
352 // We have copied the value to `result` already.
356 _ if name_str.starts_with("simd_") => {
357 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
363 _ => bug!("unknown intrinsic '{}'", name),
366 if !fn_abi.ret.is_ignore() {
367 if let PassMode::Cast(ty) = fn_abi.ret.mode {
368 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
369 let ptr = self.pointercast(result.llval, ptr_llty);
370 self.store(llval, ptr, result.align);
372 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
374 .store(self, result);
379 fn abort(&mut self) {
380 self.call_intrinsic("llvm.trap", &[]);
383 fn assume(&mut self, val: Self::Value) {
384 self.call_intrinsic("llvm.assume", &[val]);
387 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
388 self.call_intrinsic("llvm.expect.i1", &[cond, self.const_bool(expected)])
391 fn sideeffect(&mut self) {
392 // This kind of check would make a ton of sense in the caller, but currently the only
393 // caller of this function is in `rustc_codegen_ssa`, which is agnostic to whether LLVM
394 // codegen backend being used, and so is unable to check the LLVM version.
395 if unsafe { llvm::LLVMRustVersionMajor() } < 12 {
396 self.call_intrinsic("llvm.sideeffect", &[]);
400 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
401 self.call_intrinsic("llvm.va_start", &[va_list])
404 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
405 self.call_intrinsic("llvm.va_end", &[va_list])
410 bx: &mut Builder<'a, 'll, 'tcx>,
411 try_func: &'ll Value,
413 catch_func: &'ll Value,
416 if bx.sess().panic_strategy() == PanicStrategy::Abort {
417 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
418 bx.call(try_func_ty, try_func, &[data], None);
419 // Return 0 unconditionally from the intrinsic call;
420 // we can never unwind.
421 let ret_align = bx.tcx().data_layout.i32_align.abi;
422 bx.store(bx.const_i32(0), dest, ret_align);
423 } else if wants_msvc_seh(bx.sess()) {
424 codegen_msvc_try(bx, try_func, data, catch_func, dest);
425 } else if bx.sess().target.is_like_emscripten {
426 codegen_emcc_try(bx, try_func, data, catch_func, dest);
428 codegen_gnu_try(bx, try_func, data, catch_func, dest);
432 // MSVC's definition of the `rust_try` function.
434 // This implementation uses the new exception handling instructions in LLVM
435 // which have support in LLVM for SEH on MSVC targets. Although these
436 // instructions are meant to work for all targets, as of the time of this
437 // writing, however, LLVM does not recommend the usage of these new instructions
438 // as the old ones are still more optimized.
440 bx: &mut Builder<'a, 'll, 'tcx>,
441 try_func: &'ll Value,
443 catch_func: &'ll Value,
446 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
447 bx.set_personality_fn(bx.eh_personality());
449 let mut normal = bx.build_sibling_block("normal");
450 let mut catchswitch = bx.build_sibling_block("catchswitch");
451 let mut catchpad_rust = bx.build_sibling_block("catchpad_rust");
452 let mut catchpad_foreign = bx.build_sibling_block("catchpad_foreign");
453 let mut caught = bx.build_sibling_block("caught");
455 let try_func = llvm::get_param(bx.llfn(), 0);
456 let data = llvm::get_param(bx.llfn(), 1);
457 let catch_func = llvm::get_param(bx.llfn(), 2);
459 // We're generating an IR snippet that looks like:
461 // declare i32 @rust_try(%try_func, %data, %catch_func) {
462 // %slot = alloca i8*
463 // invoke %try_func(%data) to label %normal unwind label %catchswitch
469 // %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
472 // %tok = catchpad within %cs [%type_descriptor, 8, %slot]
474 // call %catch_func(%data, %ptr)
475 // catchret from %tok to label %caught
478 // %tok = catchpad within %cs [null, 64, null]
479 // call %catch_func(%data, null)
480 // catchret from %tok to label %caught
486 // This structure follows the basic usage of throw/try/catch in LLVM.
487 // For example, compile this C++ snippet to see what LLVM generates:
489 // struct rust_panic {
490 // rust_panic(const rust_panic&);
497 // void (*try_func)(void*),
499 // void (*catch_func)(void*, void*) noexcept
504 // } catch(rust_panic& a) {
505 // catch_func(data, &a);
508 // catch_func(data, NULL);
513 // More information can be found in libstd's seh.rs implementation.
514 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
515 let slot = bx.alloca(bx.type_i8p(), ptr_align);
516 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
517 bx.invoke(try_func_ty, try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
519 normal.ret(bx.const_i32(0));
521 let cs = catchswitch.catch_switch(None, None, 2);
522 catchswitch.add_handler(cs, catchpad_rust.llbb());
523 catchswitch.add_handler(cs, catchpad_foreign.llbb());
525 // We can't use the TypeDescriptor defined in libpanic_unwind because it
526 // might be in another DLL and the SEH encoding only supports specifying
527 // a TypeDescriptor from the current module.
529 // However this isn't an issue since the MSVC runtime uses string
530 // comparison on the type name to match TypeDescriptors rather than
533 // So instead we generate a new TypeDescriptor in each module that uses
534 // `try` and let the linker merge duplicate definitions in the same
537 // When modifying, make sure that the type_name string exactly matches
538 // the one used in src/libpanic_unwind/seh.rs.
539 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
540 let type_name = bx.const_bytes(b"rust_panic\0");
542 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
543 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
545 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
546 llvm::SetUniqueComdat(bx.llmod, tydesc);
547 llvm::LLVMSetInitializer(tydesc, type_info);
550 // The flag value of 8 indicates that we are catching the exception by
551 // reference instead of by value. We can't use catch by value because
552 // that requires copying the exception object, which we don't support
553 // since our exception object effectively contains a Box.
555 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
556 let flags = bx.const_i32(8);
557 let funclet = catchpad_rust.catch_pad(cs, &[tydesc, flags, slot]);
558 let ptr = catchpad_rust.load(bx.type_i8p(), slot, ptr_align);
559 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
560 catchpad_rust.call(catch_ty, catch_func, &[data, ptr], Some(&funclet));
561 catchpad_rust.catch_ret(&funclet, caught.llbb());
563 // The flag value of 64 indicates a "catch-all".
564 let flags = bx.const_i32(64);
565 let null = bx.const_null(bx.type_i8p());
566 let funclet = catchpad_foreign.catch_pad(cs, &[null, flags, null]);
567 catchpad_foreign.call(catch_ty, catch_func, &[data, null], Some(&funclet));
568 catchpad_foreign.catch_ret(&funclet, caught.llbb());
570 caught.ret(bx.const_i32(1));
573 // Note that no invoke is used here because by definition this function
574 // can't panic (that's what it's catching).
575 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
576 let i32_align = bx.tcx().data_layout.i32_align.abi;
577 bx.store(ret, dest, i32_align);
580 // Definition of the standard `try` function for Rust using the GNU-like model
581 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
584 // This codegen is a little surprising because we always call a shim
585 // function instead of inlining the call to `invoke` manually here. This is done
586 // because in LLVM we're only allowed to have one personality per function
587 // definition. The call to the `try` intrinsic is being inlined into the
588 // function calling it, and that function may already have other personality
589 // functions in play. By calling a shim we're guaranteed that our shim will have
590 // the right personality function.
592 bx: &mut Builder<'a, 'll, 'tcx>,
593 try_func: &'ll Value,
595 catch_func: &'ll Value,
598 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
599 // Codegens the shims described above:
602 // invoke %try_func(%data) normal %normal unwind %catch
608 // (%ptr, _) = landingpad
609 // call %catch_func(%data, %ptr)
611 let mut then = bx.build_sibling_block("then");
612 let mut catch = bx.build_sibling_block("catch");
614 let try_func = llvm::get_param(bx.llfn(), 0);
615 let data = llvm::get_param(bx.llfn(), 1);
616 let catch_func = llvm::get_param(bx.llfn(), 2);
617 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
618 bx.invoke(try_func_ty, try_func, &[data], then.llbb(), catch.llbb(), None);
619 then.ret(bx.const_i32(0));
621 // Type indicator for the exception being thrown.
623 // The first value in this tuple is a pointer to the exception object
624 // being thrown. The second value is a "selector" indicating which of
625 // the landing pad clauses the exception's type had been matched to.
626 // rust_try ignores the selector.
627 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
628 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
629 let tydesc = bx.const_null(bx.type_i8p());
630 catch.add_clause(vals, tydesc);
631 let ptr = catch.extract_value(vals, 0);
632 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
633 catch.call(catch_ty, catch_func, &[data, ptr], None);
634 catch.ret(bx.const_i32(1));
637 // Note that no invoke is used here because by definition this function
638 // can't panic (that's what it's catching).
639 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
640 let i32_align = bx.tcx().data_layout.i32_align.abi;
641 bx.store(ret, dest, i32_align);
644 // Variant of codegen_gnu_try used for emscripten where Rust panics are
645 // implemented using C++ exceptions. Here we use exceptions of a specific type
646 // (`struct rust_panic`) to represent Rust panics.
648 bx: &mut Builder<'a, 'll, 'tcx>,
649 try_func: &'ll Value,
651 catch_func: &'ll Value,
654 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
655 // Codegens the shims described above:
658 // invoke %try_func(%data) normal %normal unwind %catch
664 // (%ptr, %selector) = landingpad
665 // %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
666 // %is_rust_panic = %selector == %rust_typeid
667 // %catch_data = alloca { i8*, i8 }
668 // %catch_data[0] = %ptr
669 // %catch_data[1] = %is_rust_panic
670 // call %catch_func(%data, %catch_data)
672 let mut then = bx.build_sibling_block("then");
673 let mut catch = bx.build_sibling_block("catch");
675 let try_func = llvm::get_param(bx.llfn(), 0);
676 let data = llvm::get_param(bx.llfn(), 1);
677 let catch_func = llvm::get_param(bx.llfn(), 2);
678 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
679 bx.invoke(try_func_ty, try_func, &[data], then.llbb(), catch.llbb(), None);
680 then.ret(bx.const_i32(0));
682 // Type indicator for the exception being thrown.
684 // The first value in this tuple is a pointer to the exception object
685 // being thrown. The second value is a "selector" indicating which of
686 // the landing pad clauses the exception's type had been matched to.
687 let tydesc = bx.eh_catch_typeinfo();
688 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
689 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 2);
690 catch.add_clause(vals, tydesc);
691 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
692 let ptr = catch.extract_value(vals, 0);
693 let selector = catch.extract_value(vals, 1);
695 // Check if the typeid we got is the one for a Rust panic.
696 let rust_typeid = catch.call_intrinsic("llvm.eh.typeid.for", &[tydesc]);
697 let is_rust_panic = catch.icmp(IntPredicate::IntEQ, selector, rust_typeid);
698 let is_rust_panic = catch.zext(is_rust_panic, bx.type_bool());
700 // We need to pass two values to catch_func (ptr and is_rust_panic), so
701 // create an alloca and pass a pointer to that.
702 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
703 let i8_align = bx.tcx().data_layout.i8_align.abi;
704 let catch_data_type = bx.type_struct(&[bx.type_i8p(), bx.type_bool()], false);
705 let catch_data = catch.alloca(catch_data_type, ptr_align);
706 let catch_data_0 = catch.inbounds_gep(
709 &[bx.const_usize(0), bx.const_usize(0)],
711 catch.store(ptr, catch_data_0, ptr_align);
712 let catch_data_1 = catch.inbounds_gep(
715 &[bx.const_usize(0), bx.const_usize(1)],
717 catch.store(is_rust_panic, catch_data_1, i8_align);
718 let catch_data = catch.bitcast(catch_data, bx.type_i8p());
720 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
721 catch.call(catch_ty, catch_func, &[data, catch_data], None);
722 catch.ret(bx.const_i32(1));
725 // Note that no invoke is used here because by definition this function
726 // can't panic (that's what it's catching).
727 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
728 let i32_align = bx.tcx().data_layout.i32_align.abi;
729 bx.store(ret, dest, i32_align);
732 // Helper function to give a Block to a closure to codegen a shim function.
733 // This is currently primarily used for the `try` intrinsic functions above.
734 fn gen_fn<'ll, 'tcx>(
735 cx: &CodegenCx<'ll, 'tcx>,
737 rust_fn_sig: ty::PolyFnSig<'tcx>,
738 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
739 ) -> (&'ll Type, &'ll Value) {
740 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
741 let llty = fn_abi.llvm_type(cx);
742 let llfn = cx.declare_fn(name, &fn_abi);
743 cx.set_frame_pointer_type(llfn);
744 cx.apply_target_cpu_attr(llfn);
745 // FIXME(eddyb) find a nicer way to do this.
746 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
747 let llbb = Builder::append_block(cx, llfn, "entry-block");
748 let bx = Builder::build(cx, llbb);
753 // Helper function used to get a handle to the `__rust_try` function used to
756 // This function is only generated once and is then cached.
757 fn get_rust_try_fn<'ll, 'tcx>(
758 cx: &CodegenCx<'ll, 'tcx>,
759 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
760 ) -> (&'ll Type, &'ll Value) {
761 if let Some(llfn) = cx.rust_try_fn.get() {
765 // Define the type up front for the signature of the rust_try function.
767 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
768 // `unsafe fn(*mut i8) -> ()`
769 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
773 hir::Unsafety::Unsafe,
776 // `unsafe fn(*mut i8, *mut i8) -> ()`
777 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
778 [i8p, i8p].iter().cloned(),
781 hir::Unsafety::Unsafe,
784 // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
785 let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
786 vec![try_fn_ty, i8p, catch_fn_ty].into_iter(),
789 hir::Unsafety::Unsafe,
792 let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
793 cx.rust_try_fn.set(Some(rust_try));
797 fn generic_simd_intrinsic(
798 bx: &mut Builder<'a, 'll, 'tcx>,
801 args: &[OperandRef<'tcx, &'ll Value>],
805 ) -> Result<&'ll Value, ()> {
806 // macros for error handling:
807 macro_rules! emit_error {
811 ($msg: tt, $($fmt: tt)*) => {
812 span_invalid_monomorphization_error(
814 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
819 macro_rules! return_error {
822 emit_error!($($fmt)*);
828 macro_rules! require {
829 ($cond: expr, $($fmt: tt)*) => {
831 return_error!($($fmt)*);
836 macro_rules! require_simd {
837 ($ty: expr, $position: expr) => {
838 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
844 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), callee_ty.fn_sig(tcx));
845 let arg_tys = sig.inputs();
846 let name_str = &*name.as_str();
848 if name == sym::simd_select_bitmask {
849 let in_ty = arg_tys[0];
850 let m_len = match in_ty.kind() {
851 // Note that this `.unwrap()` crashes for isize/usize, that's sort
852 // of intentional as there's not currently a use case for that.
853 ty::Int(i) => i.bit_width().unwrap(),
854 ty::Uint(i) => i.bit_width().unwrap(),
855 _ => return_error!("`{}` is not an integral type", in_ty),
857 require_simd!(arg_tys[1], "argument");
858 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
860 // Allow masks for vectors with fewer than 8 elements to be
861 // represented with a u8 or i8.
862 m_len == v_len || (m_len == 8 && v_len < 8),
863 "mismatched lengths: mask length `{}` != other vector length `{}`",
867 let i1 = bx.type_i1();
868 let im = bx.type_ix(v_len);
869 let i1xn = bx.type_vector(i1, v_len);
870 let m_im = bx.trunc(args[0].immediate(), im);
871 let m_i1s = bx.bitcast(m_im, i1xn);
872 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
875 // every intrinsic below takes a SIMD vector as its first argument
876 require_simd!(arg_tys[0], "input");
877 let in_ty = arg_tys[0];
879 let comparison = match name {
880 sym::simd_eq => Some(hir::BinOpKind::Eq),
881 sym::simd_ne => Some(hir::BinOpKind::Ne),
882 sym::simd_lt => Some(hir::BinOpKind::Lt),
883 sym::simd_le => Some(hir::BinOpKind::Le),
884 sym::simd_gt => Some(hir::BinOpKind::Gt),
885 sym::simd_ge => Some(hir::BinOpKind::Ge),
889 let (in_len, in_elem) = arg_tys[0].simd_size_and_type(bx.tcx());
890 if let Some(cmp_op) = comparison {
891 require_simd!(ret_ty, "return");
893 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
896 "expected return type with length {} (same as input type `{}`), \
897 found `{}` with length {}",
904 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
905 "expected return type with integer elements, found `{}` with non-integer `{}`",
910 return Ok(compare_simd_types(
920 if let Some(stripped) = name_str.strip_prefix("simd_shuffle") {
921 let n: u64 = stripped.parse().unwrap_or_else(|_| {
922 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
925 require_simd!(ret_ty, "return");
927 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
930 "expected return type of length {}, found `{}` with length {}",
937 "expected return element type `{}` (element of input `{}`), \
938 found `{}` with element type `{}`",
945 let total_len = u128::from(in_len) * 2;
947 let vector = args[2].immediate();
949 let indices: Option<Vec<_>> = (0..n)
952 let val = bx.const_get_elt(vector, i as u64);
953 match bx.const_to_opt_u128(val, true) {
955 emit_error!("shuffle index #{} is not a constant", arg_idx);
958 Some(idx) if idx >= total_len => {
960 "shuffle index #{} is out of bounds (limit {})",
966 Some(idx) => Some(bx.const_i32(idx as i32)),
970 let indices = match indices {
972 None => return Ok(bx.const_null(llret_ty)),
975 return Ok(bx.shuffle_vector(
978 bx.const_vector(&indices),
982 if name == sym::simd_insert {
984 in_elem == arg_tys[2],
985 "expected inserted type `{}` (element of input `{}`), found `{}`",
990 return Ok(bx.insert_element(
996 if name == sym::simd_extract {
999 "expected return type `{}` (element of input `{}`), found `{}`",
1004 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1007 if name == sym::simd_select {
1008 let m_elem_ty = in_elem;
1010 require_simd!(arg_tys[1], "argument");
1011 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1014 "mismatched lengths: mask length `{}` != other vector length `{}`",
1018 match m_elem_ty.kind() {
1020 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1022 // truncate the mask to a vector of i1s
1023 let i1 = bx.type_i1();
1024 let i1xn = bx.type_vector(i1, m_len as u64);
1025 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1026 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1029 if name == sym::simd_bitmask {
1030 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1031 // vector mask and returns an unsigned integer containing the most
1032 // significant bit (MSB) of each lane.
1034 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1036 let expected_int_bits = in_len.max(8);
1037 match ret_ty.kind() {
1038 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1039 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1042 // Integer vector <i{in_bitwidth} x in_len>:
1043 let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
1045 args[0].immediate(),
1046 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1049 args[0].immediate(),
1050 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1053 "vector argument `{}`'s element type `{}`, expected integer element type",
1059 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1062 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1065 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1066 // Truncate vector to an <i1 x N>
1067 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1068 // Bitcast <i1 x N> to iN:
1069 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1070 // Zero-extend iN to the bitmask type:
1071 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1074 fn simd_simple_float_intrinsic(
1076 in_elem: &::rustc_middle::ty::TyS<'_>,
1077 in_ty: &::rustc_middle::ty::TyS<'_>,
1079 bx: &mut Builder<'a, 'll, 'tcx>,
1081 args: &[OperandRef<'tcx, &'ll Value>],
1082 ) -> Result<&'ll Value, ()> {
1083 macro_rules! emit_error {
1087 ($msg: tt, $($fmt: tt)*) => {
1088 span_invalid_monomorphization_error(
1090 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1094 macro_rules! return_error {
1097 emit_error!($($fmt)*);
1103 let (elem_ty_str, elem_ty) = if let ty::Float(f) = in_elem.kind() {
1104 let elem_ty = bx.cx.type_float_from_ty(*f);
1105 match f.bit_width() {
1106 32 => ("f32", elem_ty),
1107 64 => ("f64", elem_ty),
1110 "unsupported element type `{}` of floating-point vector `{}`",
1117 return_error!("`{}` is not a floating-point type", in_ty);
1120 let vec_ty = bx.type_vector(elem_ty, in_len);
1122 let (intr_name, fn_ty) = match name {
1123 sym::simd_ceil => ("ceil", bx.type_func(&[vec_ty], vec_ty)),
1124 sym::simd_fabs => ("fabs", bx.type_func(&[vec_ty], vec_ty)),
1125 sym::simd_fcos => ("cos", bx.type_func(&[vec_ty], vec_ty)),
1126 sym::simd_fexp2 => ("exp2", bx.type_func(&[vec_ty], vec_ty)),
1127 sym::simd_fexp => ("exp", bx.type_func(&[vec_ty], vec_ty)),
1128 sym::simd_flog10 => ("log10", bx.type_func(&[vec_ty], vec_ty)),
1129 sym::simd_flog2 => ("log2", bx.type_func(&[vec_ty], vec_ty)),
1130 sym::simd_flog => ("log", bx.type_func(&[vec_ty], vec_ty)),
1131 sym::simd_floor => ("floor", bx.type_func(&[vec_ty], vec_ty)),
1132 sym::simd_fma => ("fma", bx.type_func(&[vec_ty, vec_ty, vec_ty], vec_ty)),
1133 sym::simd_fpowi => ("powi", bx.type_func(&[vec_ty, bx.type_i32()], vec_ty)),
1134 sym::simd_fpow => ("pow", bx.type_func(&[vec_ty, vec_ty], vec_ty)),
1135 sym::simd_fsin => ("sin", bx.type_func(&[vec_ty], vec_ty)),
1136 sym::simd_fsqrt => ("sqrt", bx.type_func(&[vec_ty], vec_ty)),
1137 sym::simd_round => ("round", bx.type_func(&[vec_ty], vec_ty)),
1138 sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
1139 _ => return_error!("unrecognized intrinsic `{}`", name),
1141 let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str);
1142 let f = bx.declare_cfn(&llvm_name, llvm::UnnamedAddr::No, fn_ty);
1144 bx.call(fn_ty, f, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1167 return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1171 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1172 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1173 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1174 let p0s: String = "p0".repeat(no_pointers);
1175 match *elem_ty.kind() {
1176 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1177 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1178 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1179 _ => unreachable!(),
1184 cx: &CodegenCx<'ll, '_>,
1187 mut no_pointers: usize,
1189 // FIXME: use cx.layout_of(ty).llvm_type() ?
1190 let mut elem_ty = match *elem_ty.kind() {
1191 ty::Int(v) => cx.type_int_from_ty(v),
1192 ty::Uint(v) => cx.type_uint_from_ty(v),
1193 ty::Float(v) => cx.type_float_from_ty(v),
1194 _ => unreachable!(),
1196 while no_pointers > 0 {
1197 elem_ty = cx.type_ptr_to(elem_ty);
1200 cx.type_vector(elem_ty, vec_len)
1203 if name == sym::simd_gather {
1204 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1205 // mask: <N x i{M}>) -> <N x T>
1206 // * N: number of elements in the input vectors
1207 // * T: type of the element to load
1208 // * M: any integer width is supported, will be truncated to i1
1210 // All types must be simd vector types
1211 require_simd!(in_ty, "first");
1212 require_simd!(arg_tys[1], "second");
1213 require_simd!(arg_tys[2], "third");
1214 require_simd!(ret_ty, "return");
1216 // Of the same length:
1217 let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1218 let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1221 "expected {} argument with length {} (same as input type `{}`), \
1222 found `{}` with length {}",
1231 "expected {} argument with length {} (same as input type `{}`), \
1232 found `{}` with length {}",
1240 // The return type must match the first argument type
1241 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1243 // This counts how many pointers
1244 fn ptr_count(t: Ty<'_>) -> usize {
1246 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1252 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1254 ty::RawPtr(p) => non_ptr(p.ty),
1259 // The second argument must be a simd vector with an element type that's a pointer
1260 // to the element type of the first argument
1261 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1262 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1263 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1264 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(element_ty1), non_ptr(element_ty1)),
1268 "expected element type `{}` of second argument `{}` \
1269 to be a pointer to the element type `{}` of the first \
1270 argument `{}`, found `{}` != `*_ {}`",
1281 assert!(pointer_count > 0);
1282 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1283 assert_eq!(underlying_ty, non_ptr(element_ty0));
1285 // The element type of the third argument must be a signed integer type of any width:
1286 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1287 match element_ty2.kind() {
1292 "expected element type `{}` of third argument `{}` \
1293 to be a signed integer type",
1300 // Alignment of T, must be a constant integer value:
1301 let alignment_ty = bx.type_i32();
1302 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1304 // Truncate the mask vector to a vector of i1s:
1305 let (mask, mask_ty) = {
1306 let i1 = bx.type_i1();
1307 let i1xn = bx.type_vector(i1, in_len);
1308 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1311 // Type of the vector of pointers:
1312 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1313 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1315 // Type of the vector of elements:
1316 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1317 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1319 let llvm_intrinsic =
1320 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1321 let fn_ty = bx.type_func(
1322 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1325 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1327 bx.call(fn_ty, f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1331 if name == sym::simd_scatter {
1332 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1333 // mask: <N x i{M}>) -> ()
1334 // * N: number of elements in the input vectors
1335 // * T: type of the element to load
1336 // * M: any integer width is supported, will be truncated to i1
1338 // All types must be simd vector types
1339 require_simd!(in_ty, "first");
1340 require_simd!(arg_tys[1], "second");
1341 require_simd!(arg_tys[2], "third");
1343 // Of the same length:
1344 let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1345 let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1347 in_len == element_len1,
1348 "expected {} argument with length {} (same as input type `{}`), \
1349 found `{}` with length {}",
1357 in_len == element_len2,
1358 "expected {} argument with length {} (same as input type `{}`), \
1359 found `{}` with length {}",
1367 // This counts how many pointers
1368 fn ptr_count(t: Ty<'_>) -> usize {
1370 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1376 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1378 ty::RawPtr(p) => non_ptr(p.ty),
1383 // The second argument must be a simd vector with an element type that's a pointer
1384 // to the element type of the first argument
1385 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1386 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1387 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1388 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1389 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1390 (ptr_count(element_ty1), non_ptr(element_ty1))
1395 "expected element type `{}` of second argument `{}` \
1396 to be a pointer to the element type `{}` of the first \
1397 argument `{}`, found `{}` != `*mut {}`",
1408 assert!(pointer_count > 0);
1409 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1410 assert_eq!(underlying_ty, non_ptr(element_ty0));
1412 // The element type of the third argument must be a signed integer type of any width:
1413 match element_ty2.kind() {
1418 "expected element type `{}` of third argument `{}` \
1419 be a signed integer type",
1426 // Alignment of T, must be a constant integer value:
1427 let alignment_ty = bx.type_i32();
1428 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1430 // Truncate the mask vector to a vector of i1s:
1431 let (mask, mask_ty) = {
1432 let i1 = bx.type_i1();
1433 let i1xn = bx.type_vector(i1, in_len);
1434 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1437 let ret_t = bx.type_void();
1439 // Type of the vector of pointers:
1440 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1441 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1443 // Type of the vector of elements:
1444 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1445 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1447 let llvm_intrinsic =
1448 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1450 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t);
1451 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1453 bx.call(fn_ty, f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1457 macro_rules! arith_red {
1458 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1459 $identity:expr) => {
1460 if name == sym::$name {
1463 "expected return type `{}` (element of input `{}`), found `{}`",
1468 return match in_elem.kind() {
1469 ty::Int(_) | ty::Uint(_) => {
1470 let r = bx.$integer_reduce(args[0].immediate());
1472 // if overflow occurs, the result is the
1473 // mathematical result modulo 2^n:
1474 Ok(bx.$op(args[1].immediate(), r))
1476 Ok(bx.$integer_reduce(args[0].immediate()))
1480 let acc = if $ordered {
1481 // ordered arithmetic reductions take an accumulator
1484 // unordered arithmetic reductions use the identity accumulator
1485 match f.bit_width() {
1486 32 => bx.const_real(bx.type_f32(), $identity),
1487 64 => bx.const_real(bx.type_f64(), $identity),
1490 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1499 Ok(bx.$float_reduce(acc, args[0].immediate()))
1502 "unsupported {} from `{}` with element `{}` to `{}`",
1513 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1514 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1516 simd_reduce_add_unordered: vector_reduce_add,
1517 vector_reduce_fadd_fast,
1523 simd_reduce_mul_unordered: vector_reduce_mul,
1524 vector_reduce_fmul_fast,
1530 macro_rules! minmax_red {
1531 ($name:ident: $int_red:ident, $float_red:ident) => {
1532 if name == sym::$name {
1535 "expected return type `{}` (element of input `{}`), found `{}`",
1540 return match in_elem.kind() {
1541 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1542 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1543 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1545 "unsupported {} from `{}` with element `{}` to `{}`",
1556 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1557 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1559 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1560 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1562 macro_rules! bitwise_red {
1563 ($name:ident : $red:ident, $boolean:expr) => {
1564 if name == sym::$name {
1565 let input = if !$boolean {
1568 "expected return type `{}` (element of input `{}`), found `{}`",
1575 match in_elem.kind() {
1576 ty::Int(_) | ty::Uint(_) => {}
1578 "unsupported {} from `{}` with element `{}` to `{}`",
1586 // boolean reductions operate on vectors of i1s:
1587 let i1 = bx.type_i1();
1588 let i1xn = bx.type_vector(i1, in_len as u64);
1589 bx.trunc(args[0].immediate(), i1xn)
1591 return match in_elem.kind() {
1592 ty::Int(_) | ty::Uint(_) => {
1593 let r = bx.$red(input);
1594 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1597 "unsupported {} from `{}` with element `{}` to `{}`",
1608 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
1609 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
1610 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
1611 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
1612 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
1614 if name == sym::simd_cast {
1615 require_simd!(ret_ty, "return");
1616 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1619 "expected return type with length {} (same as input type `{}`), \
1620 found `{}` with length {}",
1626 // casting cares about nominal type, not just structural type
1627 if in_elem == out_elem {
1628 return Ok(args[0].immediate());
1633 Int(/* is signed? */ bool),
1637 let (in_style, in_width) = match in_elem.kind() {
1638 // vectors of pointer-sized integers should've been
1639 // disallowed before here, so this unwrap is safe.
1640 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1641 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1642 ty::Float(f) => (Style::Float, f.bit_width()),
1643 _ => (Style::Unsupported, 0),
1645 let (out_style, out_width) = match out_elem.kind() {
1646 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1647 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1648 ty::Float(f) => (Style::Float, f.bit_width()),
1649 _ => (Style::Unsupported, 0),
1652 match (in_style, out_style) {
1653 (Style::Int(in_is_signed), Style::Int(_)) => {
1654 return Ok(match in_width.cmp(&out_width) {
1655 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1656 Ordering::Equal => args[0].immediate(),
1659 bx.sext(args[0].immediate(), llret_ty)
1661 bx.zext(args[0].immediate(), llret_ty)
1666 (Style::Int(in_is_signed), Style::Float) => {
1667 return Ok(if in_is_signed {
1668 bx.sitofp(args[0].immediate(), llret_ty)
1670 bx.uitofp(args[0].immediate(), llret_ty)
1673 (Style::Float, Style::Int(out_is_signed)) => {
1674 return Ok(if out_is_signed {
1675 bx.fptosi(args[0].immediate(), llret_ty)
1677 bx.fptoui(args[0].immediate(), llret_ty)
1680 (Style::Float, Style::Float) => {
1681 return Ok(match in_width.cmp(&out_width) {
1682 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1683 Ordering::Equal => args[0].immediate(),
1684 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1687 _ => { /* Unsupported. Fallthrough. */ }
1691 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1698 macro_rules! arith_binary {
1699 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1700 $(if name == sym::$name {
1701 match in_elem.kind() {
1702 $($(ty::$p(_))|* => {
1703 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1708 "unsupported operation on `{}` with element `{}`",
1715 simd_add: Uint, Int => add, Float => fadd;
1716 simd_sub: Uint, Int => sub, Float => fsub;
1717 simd_mul: Uint, Int => mul, Float => fmul;
1718 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1719 simd_rem: Uint => urem, Int => srem, Float => frem;
1720 simd_shl: Uint, Int => shl;
1721 simd_shr: Uint => lshr, Int => ashr;
1722 simd_and: Uint, Int => and;
1723 simd_or: Uint, Int => or;
1724 simd_xor: Uint, Int => xor;
1725 simd_fmax: Float => maxnum;
1726 simd_fmin: Float => minnum;
1729 macro_rules! arith_unary {
1730 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1731 $(if name == sym::$name {
1732 match in_elem.kind() {
1733 $($(ty::$p(_))|* => {
1734 return Ok(bx.$call(args[0].immediate()))
1739 "unsupported operation on `{}` with element `{}`",
1746 simd_neg: Int => neg, Float => fneg;
1749 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
1750 let lhs = args[0].immediate();
1751 let rhs = args[1].immediate();
1752 let is_add = name == sym::simd_saturating_add;
1753 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1754 let (signed, elem_width, elem_ty) = match *in_elem.kind() {
1755 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
1756 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
1759 "expected element type `{}` of vector type `{}` \
1760 to be a signed or unsigned integer type",
1761 arg_tys[0].simd_size_and_type(bx.tcx()).1,
1766 let llvm_intrinsic = &format!(
1767 "llvm.{}{}.sat.v{}i{}",
1768 if signed { 's' } else { 'u' },
1769 if is_add { "add" } else { "sub" },
1773 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1775 let fn_ty = bx.type_func(&[vec_ty, vec_ty], vec_ty);
1776 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1777 let v = bx.call(fn_ty, f, &[lhs, rhs], None);
1781 span_bug!(span, "unknown SIMD intrinsic");
1784 // Returns the width of an int Ty, and if it's signed or not
1785 // Returns None if the type is not an integer
1786 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1788 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1791 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), true))
1794 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), false))