1 use crate::abi::{Abi, FnAbi, 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;
10 use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh};
11 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
12 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
13 use rustc_codegen_ssa::mir::operand::OperandRef;
14 use rustc_codegen_ssa::mir::place::PlaceRef;
15 use rustc_codegen_ssa::traits::*;
17 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
18 use rustc_middle::ty::{self, Ty};
19 use rustc_middle::{bug, span_bug};
20 use rustc_span::{sym, symbol::kw, Span, Symbol};
21 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
22 use rustc_target::spec::PanicStrategy;
24 use std::cmp::Ordering;
27 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<&'ll Value> {
28 let llvm_name = match name {
29 sym::sqrtf32 => "llvm.sqrt.f32",
30 sym::sqrtf64 => "llvm.sqrt.f64",
31 sym::powif32 => "llvm.powi.f32",
32 sym::powif64 => "llvm.powi.f64",
33 sym::sinf32 => "llvm.sin.f32",
34 sym::sinf64 => "llvm.sin.f64",
35 sym::cosf32 => "llvm.cos.f32",
36 sym::cosf64 => "llvm.cos.f64",
37 sym::powf32 => "llvm.pow.f32",
38 sym::powf64 => "llvm.pow.f64",
39 sym::expf32 => "llvm.exp.f32",
40 sym::expf64 => "llvm.exp.f64",
41 sym::exp2f32 => "llvm.exp2.f32",
42 sym::exp2f64 => "llvm.exp2.f64",
43 sym::logf32 => "llvm.log.f32",
44 sym::logf64 => "llvm.log.f64",
45 sym::log10f32 => "llvm.log10.f32",
46 sym::log10f64 => "llvm.log10.f64",
47 sym::log2f32 => "llvm.log2.f32",
48 sym::log2f64 => "llvm.log2.f64",
49 sym::fmaf32 => "llvm.fma.f32",
50 sym::fmaf64 => "llvm.fma.f64",
51 sym::fabsf32 => "llvm.fabs.f32",
52 sym::fabsf64 => "llvm.fabs.f64",
53 sym::minnumf32 => "llvm.minnum.f32",
54 sym::minnumf64 => "llvm.minnum.f64",
55 sym::maxnumf32 => "llvm.maxnum.f32",
56 sym::maxnumf64 => "llvm.maxnum.f64",
57 sym::copysignf32 => "llvm.copysign.f32",
58 sym::copysignf64 => "llvm.copysign.f64",
59 sym::floorf32 => "llvm.floor.f32",
60 sym::floorf64 => "llvm.floor.f64",
61 sym::ceilf32 => "llvm.ceil.f32",
62 sym::ceilf64 => "llvm.ceil.f64",
63 sym::truncf32 => "llvm.trunc.f32",
64 sym::truncf64 => "llvm.trunc.f64",
65 sym::rintf32 => "llvm.rint.f32",
66 sym::rintf64 => "llvm.rint.f64",
67 sym::nearbyintf32 => "llvm.nearbyint.f32",
68 sym::nearbyintf64 => "llvm.nearbyint.f64",
69 sym::roundf32 => "llvm.round.f32",
70 sym::roundf64 => "llvm.round.f64",
73 Some(cx.get_intrinsic(&llvm_name))
76 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
77 fn codegen_intrinsic_call(
79 instance: ty::Instance<'tcx>,
80 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
81 args: &[OperandRef<'tcx, &'ll Value>],
86 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
88 let (def_id, substs) = match *callee_ty.kind() {
89 ty::FnDef(def_id, substs) => (def_id, substs),
90 _ => bug!("expected fn item type, found {}", callee_ty),
93 let sig = callee_ty.fn_sig(tcx);
94 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
95 let arg_tys = sig.inputs();
96 let ret_ty = sig.output();
97 let name = tcx.item_name(def_id);
98 let name_str = &*name.as_str();
100 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
101 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
103 let simple = get_simple_intrinsic(self, name);
104 let llval = match name {
105 _ if simple.is_some() => self.call(
107 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
111 let expect = self.get_intrinsic(&("llvm.expect.i1"));
112 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
115 let expect = self.get_intrinsic(&("llvm.expect.i1"));
116 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
129 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
130 self.call(llfn, &[], None)
133 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
134 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
137 match fn_abi.ret.layout.abi {
138 abi::Abi::Scalar(ref scalar) => {
140 Primitive::Int(..) => {
141 if self.cx().size_of(ret_ty).bytes() < 4 {
142 // `va_arg` should not be called on a integer type
143 // less than 4 bytes in length. If it is, promote
144 // the integer to a `i32` and truncate the result
145 // back to the smaller type.
146 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
147 self.trunc(promoted_result, llret_ty)
149 emit_va_arg(self, args[0], ret_ty)
152 Primitive::F64 | Primitive::Pointer => {
153 emit_va_arg(self, args[0], ret_ty)
155 // `va_arg` should never be used with the return type f32.
156 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
159 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
163 sym::volatile_load | sym::unaligned_volatile_load => {
164 let tp_ty = substs.type_at(0);
165 let mut ptr = args[0].immediate();
166 if let PassMode::Cast(ty) = fn_abi.ret.mode {
167 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
169 let load = self.volatile_load(ptr);
170 let align = if name == sym::unaligned_volatile_load {
173 self.align_of(tp_ty).bytes() as u32
176 llvm::LLVMSetAlignment(load, align);
178 self.to_immediate(load, self.layout_of(tp_ty))
180 sym::volatile_store => {
181 let dst = args[0].deref(self.cx());
182 args[1].val.volatile_store(self, dst);
185 sym::unaligned_volatile_store => {
186 let dst = args[0].deref(self.cx());
187 args[1].val.unaligned_volatile_store(self, dst);
190 sym::prefetch_read_data
191 | sym::prefetch_write_data
192 | sym::prefetch_read_instruction
193 | sym::prefetch_write_instruction => {
194 let expect = self.get_intrinsic(&("llvm.prefetch"));
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),
222 | sym::saturating_add
223 | sym::saturating_sub => {
225 match int_type_width_signed(ty, self) {
226 Some((width, signed)) => match name {
227 sym::ctlz | sym::cttz => {
228 let y = self.const_bool(false);
229 let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
230 self.call(llfn, &[args[0].immediate(), y], None)
232 sym::ctlz_nonzero | sym::cttz_nonzero => {
233 let y = self.const_bool(true);
234 let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
235 let llfn = self.get_intrinsic(llvm_name);
236 self.call(llfn, &[args[0].immediate(), y], None)
238 sym::ctpop => self.call(
239 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
240 &[args[0].immediate()],
245 args[0].immediate() // byte swap a u8/i8 is just a no-op
248 self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
249 &[args[0].immediate()],
254 sym::bitreverse => self.call(
255 self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
256 &[args[0].immediate()],
259 sym::rotate_left | sym::rotate_right => {
260 let is_left = name == sym::rotate_left;
261 let val = args[0].immediate();
262 let raw_shift = args[1].immediate();
263 // rotate = funnel shift with first two args the same
265 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
266 let llfn = self.get_intrinsic(llvm_name);
267 self.call(llfn, &[val, val, raw_shift], None)
269 sym::saturating_add | sym::saturating_sub => {
270 let is_add = name == sym::saturating_add;
271 let lhs = args[0].immediate();
272 let rhs = args[1].immediate();
273 let llvm_name = &format!(
275 if signed { 's' } else { 'u' },
276 if is_add { "add" } else { "sub" },
279 let llfn = self.get_intrinsic(llvm_name);
280 self.call(llfn, &[lhs, rhs], None)
285 span_invalid_monomorphization_error(
289 "invalid monomorphization of `{}` intrinsic: \
290 expected basic integer type, found `{}`",
301 let tp_ty = substs.type_at(0);
302 let layout = self.layout_of(tp_ty).layout;
303 let use_integer_compare = match layout.abi {
304 Scalar(_) | ScalarPair(_, _) => true,
305 Uninhabited | Vector { .. } => false,
306 Aggregate { .. } => {
307 // For rusty ABIs, small aggregates are actually passed
308 // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
309 // so we re-use that same threshold here.
310 layout.size <= self.data_layout().pointer_size * 2
314 let a = args[0].immediate();
315 let b = args[1].immediate();
316 if layout.size.bytes() == 0 {
317 self.const_bool(true)
318 } else if use_integer_compare {
319 let integer_ty = self.type_ix(layout.size.bits());
320 let ptr_ty = self.type_ptr_to(integer_ty);
321 let a_ptr = self.bitcast(a, ptr_ty);
322 let a_val = self.load(a_ptr, layout.align.abi);
323 let b_ptr = self.bitcast(b, ptr_ty);
324 let b_val = self.load(b_ptr, layout.align.abi);
325 self.icmp(IntPredicate::IntEQ, a_val, b_val)
327 let i8p_ty = self.type_i8p();
328 let a_ptr = self.bitcast(a, i8p_ty);
329 let b_ptr = self.bitcast(b, i8p_ty);
330 let n = self.const_usize(layout.size.bytes());
331 let llfn = self.get_intrinsic("memcmp");
332 let cmp = self.call(llfn, &[a_ptr, b_ptr, n], None);
333 self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0))
337 _ if name_str.starts_with("simd_") => {
338 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
344 _ => bug!("unknown intrinsic '{}'", name),
347 if !fn_abi.ret.is_ignore() {
348 if let PassMode::Cast(ty) = fn_abi.ret.mode {
349 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
350 let ptr = self.pointercast(result.llval, ptr_llty);
351 self.store(llval, ptr, result.align);
353 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
355 .store(self, result);
360 fn abort(&mut self) {
361 let fnname = self.get_intrinsic(&("llvm.trap"));
362 self.call(fnname, &[], None);
365 fn assume(&mut self, val: Self::Value) {
366 let assume_intrinsic = self.get_intrinsic("llvm.assume");
367 self.call(assume_intrinsic, &[val], None);
370 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
371 let expect = self.get_intrinsic(&"llvm.expect.i1");
372 self.call(expect, &[cond, self.const_bool(expected)], None)
375 fn sideeffect(&mut self) {
376 // This kind of check would make a ton of sense in the caller, but currently the only
377 // caller of this function is in `rustc_codegen_ssa`, which is agnostic to whether LLVM
378 // codegen backend being used, and so is unable to check the LLVM version.
379 if unsafe { llvm::LLVMRustVersionMajor() } < 12 {
380 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
381 self.call(fnname, &[], None);
385 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
386 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
387 self.call(intrinsic, &[va_list], None)
390 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
391 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
392 self.call(intrinsic, &[va_list], None)
397 bx: &mut Builder<'a, 'll, 'tcx>,
398 try_func: &'ll Value,
400 catch_func: &'ll Value,
403 if bx.sess().panic_strategy() == PanicStrategy::Abort {
404 bx.call(try_func, &[data], None);
405 // Return 0 unconditionally from the intrinsic call;
406 // we can never unwind.
407 let ret_align = bx.tcx().data_layout.i32_align.abi;
408 bx.store(bx.const_i32(0), dest, ret_align);
409 } else if wants_msvc_seh(bx.sess()) {
410 codegen_msvc_try(bx, try_func, data, catch_func, dest);
411 } else if bx.sess().target.is_like_emscripten {
412 codegen_emcc_try(bx, try_func, data, catch_func, dest);
414 codegen_gnu_try(bx, try_func, data, catch_func, dest);
418 // MSVC's definition of the `rust_try` function.
420 // This implementation uses the new exception handling instructions in LLVM
421 // which have support in LLVM for SEH on MSVC targets. Although these
422 // instructions are meant to work for all targets, as of the time of this
423 // writing, however, LLVM does not recommend the usage of these new instructions
424 // as the old ones are still more optimized.
426 bx: &mut Builder<'a, 'll, 'tcx>,
427 try_func: &'ll Value,
429 catch_func: &'ll Value,
432 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
433 bx.set_personality_fn(bx.eh_personality());
435 let mut normal = bx.build_sibling_block("normal");
436 let mut catchswitch = bx.build_sibling_block("catchswitch");
437 let mut catchpad_rust = bx.build_sibling_block("catchpad_rust");
438 let mut catchpad_foreign = bx.build_sibling_block("catchpad_foreign");
439 let mut caught = bx.build_sibling_block("caught");
441 let try_func = llvm::get_param(bx.llfn(), 0);
442 let data = llvm::get_param(bx.llfn(), 1);
443 let catch_func = llvm::get_param(bx.llfn(), 2);
445 // We're generating an IR snippet that looks like:
447 // declare i32 @rust_try(%try_func, %data, %catch_func) {
448 // %slot = alloca i8*
449 // invoke %try_func(%data) to label %normal unwind label %catchswitch
455 // %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
458 // %tok = catchpad within %cs [%type_descriptor, 8, %slot]
460 // call %catch_func(%data, %ptr)
461 // catchret from %tok to label %caught
464 // %tok = catchpad within %cs [null, 64, null]
465 // call %catch_func(%data, null)
466 // catchret from %tok to label %caught
472 // This structure follows the basic usage of throw/try/catch in LLVM.
473 // For example, compile this C++ snippet to see what LLVM generates:
475 // struct rust_panic {
476 // rust_panic(const rust_panic&);
483 // void (*try_func)(void*),
485 // void (*catch_func)(void*, void*) noexcept
490 // } catch(rust_panic& a) {
491 // catch_func(data, &a);
494 // catch_func(data, NULL);
499 // More information can be found in libstd's seh.rs implementation.
500 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
501 let slot = bx.alloca(bx.type_i8p(), ptr_align);
502 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
504 normal.ret(bx.const_i32(0));
506 let cs = catchswitch.catch_switch(None, None, 2);
507 catchswitch.add_handler(cs, catchpad_rust.llbb());
508 catchswitch.add_handler(cs, catchpad_foreign.llbb());
510 // We can't use the TypeDescriptor defined in libpanic_unwind because it
511 // might be in another DLL and the SEH encoding only supports specifying
512 // a TypeDescriptor from the current module.
514 // However this isn't an issue since the MSVC runtime uses string
515 // comparison on the type name to match TypeDescriptors rather than
518 // So instead we generate a new TypeDescriptor in each module that uses
519 // `try` and let the linker merge duplicate definitions in the same
522 // When modifying, make sure that the type_name string exactly matches
523 // the one used in src/libpanic_unwind/seh.rs.
524 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
525 let type_name = bx.const_bytes(b"rust_panic\0");
527 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
528 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
530 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
531 llvm::SetUniqueComdat(bx.llmod, tydesc);
532 llvm::LLVMSetInitializer(tydesc, type_info);
535 // The flag value of 8 indicates that we are catching the exception by
536 // reference instead of by value. We can't use catch by value because
537 // that requires copying the exception object, which we don't support
538 // since our exception object effectively contains a Box.
540 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
541 let flags = bx.const_i32(8);
542 let funclet = catchpad_rust.catch_pad(cs, &[tydesc, flags, slot]);
543 let ptr = catchpad_rust.load(slot, ptr_align);
544 catchpad_rust.call(catch_func, &[data, ptr], Some(&funclet));
545 catchpad_rust.catch_ret(&funclet, caught.llbb());
547 // The flag value of 64 indicates a "catch-all".
548 let flags = bx.const_i32(64);
549 let null = bx.const_null(bx.type_i8p());
550 let funclet = catchpad_foreign.catch_pad(cs, &[null, flags, null]);
551 catchpad_foreign.call(catch_func, &[data, null], Some(&funclet));
552 catchpad_foreign.catch_ret(&funclet, caught.llbb());
554 caught.ret(bx.const_i32(1));
557 // Note that no invoke is used here because by definition this function
558 // can't panic (that's what it's catching).
559 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
560 let i32_align = bx.tcx().data_layout.i32_align.abi;
561 bx.store(ret, dest, i32_align);
564 // Definition of the standard `try` function for Rust using the GNU-like model
565 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
568 // This codegen is a little surprising because we always call a shim
569 // function instead of inlining the call to `invoke` manually here. This is done
570 // because in LLVM we're only allowed to have one personality per function
571 // definition. The call to the `try` intrinsic is being inlined into the
572 // function calling it, and that function may already have other personality
573 // functions in play. By calling a shim we're guaranteed that our shim will have
574 // the right personality function.
576 bx: &mut Builder<'a, 'll, 'tcx>,
577 try_func: &'ll Value,
579 catch_func: &'ll Value,
582 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
583 // Codegens the shims described above:
586 // invoke %try_func(%data) normal %normal unwind %catch
592 // (%ptr, _) = landingpad
593 // call %catch_func(%data, %ptr)
595 let mut then = bx.build_sibling_block("then");
596 let mut catch = bx.build_sibling_block("catch");
598 let try_func = llvm::get_param(bx.llfn(), 0);
599 let data = llvm::get_param(bx.llfn(), 1);
600 let catch_func = llvm::get_param(bx.llfn(), 2);
601 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
602 then.ret(bx.const_i32(0));
604 // Type indicator for the exception being thrown.
606 // The first value in this tuple is a pointer to the exception object
607 // being thrown. The second value is a "selector" indicating which of
608 // the landing pad clauses the exception's type had been matched to.
609 // rust_try ignores the selector.
610 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
611 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
612 let tydesc = bx.const_null(bx.type_i8p());
613 catch.add_clause(vals, tydesc);
614 let ptr = catch.extract_value(vals, 0);
615 catch.call(catch_func, &[data, ptr], None);
616 catch.ret(bx.const_i32(1));
619 // Note that no invoke is used here because by definition this function
620 // can't panic (that's what it's catching).
621 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
622 let i32_align = bx.tcx().data_layout.i32_align.abi;
623 bx.store(ret, dest, i32_align);
626 // Variant of codegen_gnu_try used for emscripten where Rust panics are
627 // implemented using C++ exceptions. Here we use exceptions of a specific type
628 // (`struct rust_panic`) to represent Rust panics.
630 bx: &mut Builder<'a, 'll, 'tcx>,
631 try_func: &'ll Value,
633 catch_func: &'ll Value,
636 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
637 // Codegens the shims described above:
640 // invoke %try_func(%data) normal %normal unwind %catch
646 // (%ptr, %selector) = landingpad
647 // %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
648 // %is_rust_panic = %selector == %rust_typeid
649 // %catch_data = alloca { i8*, i8 }
650 // %catch_data[0] = %ptr
651 // %catch_data[1] = %is_rust_panic
652 // call %catch_func(%data, %catch_data)
654 let mut then = bx.build_sibling_block("then");
655 let mut catch = bx.build_sibling_block("catch");
657 let try_func = llvm::get_param(bx.llfn(), 0);
658 let data = llvm::get_param(bx.llfn(), 1);
659 let catch_func = llvm::get_param(bx.llfn(), 2);
660 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
661 then.ret(bx.const_i32(0));
663 // Type indicator for the exception being thrown.
665 // The first value in this tuple is a pointer to the exception object
666 // being thrown. The second value is a "selector" indicating which of
667 // the landing pad clauses the exception's type had been matched to.
668 let tydesc = bx.eh_catch_typeinfo();
669 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
670 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 2);
671 catch.add_clause(vals, tydesc);
672 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
673 let ptr = catch.extract_value(vals, 0);
674 let selector = catch.extract_value(vals, 1);
676 // Check if the typeid we got is the one for a Rust panic.
677 let llvm_eh_typeid_for = bx.get_intrinsic("llvm.eh.typeid.for");
678 let rust_typeid = catch.call(llvm_eh_typeid_for, &[tydesc], None);
679 let is_rust_panic = catch.icmp(IntPredicate::IntEQ, selector, rust_typeid);
680 let is_rust_panic = catch.zext(is_rust_panic, bx.type_bool());
682 // We need to pass two values to catch_func (ptr and is_rust_panic), so
683 // create an alloca and pass a pointer to that.
684 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
685 let i8_align = bx.tcx().data_layout.i8_align.abi;
687 catch.alloca(bx.type_struct(&[bx.type_i8p(), bx.type_bool()], false), ptr_align);
688 let catch_data_0 = catch.inbounds_gep(catch_data, &[bx.const_usize(0), bx.const_usize(0)]);
689 catch.store(ptr, catch_data_0, ptr_align);
690 let catch_data_1 = catch.inbounds_gep(catch_data, &[bx.const_usize(0), bx.const_usize(1)]);
691 catch.store(is_rust_panic, catch_data_1, i8_align);
692 let catch_data = catch.bitcast(catch_data, bx.type_i8p());
694 catch.call(catch_func, &[data, catch_data], None);
695 catch.ret(bx.const_i32(1));
698 // Note that no invoke is used here because by definition this function
699 // can't panic (that's what it's catching).
700 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
701 let i32_align = bx.tcx().data_layout.i32_align.abi;
702 bx.store(ret, dest, i32_align);
705 // Helper function to give a Block to a closure to codegen a shim function.
706 // This is currently primarily used for the `try` intrinsic functions above.
707 fn gen_fn<'ll, 'tcx>(
708 cx: &CodegenCx<'ll, 'tcx>,
710 rust_fn_sig: ty::PolyFnSig<'tcx>,
711 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
713 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
714 let llfn = cx.declare_fn(name, &fn_abi);
715 cx.set_frame_pointer_type(llfn);
716 cx.apply_target_cpu_attr(llfn);
717 // FIXME(eddyb) find a nicer way to do this.
718 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
719 let llbb = Builder::append_block(cx, llfn, "entry-block");
720 let bx = Builder::build(cx, llbb);
725 // Helper function used to get a handle to the `__rust_try` function used to
728 // This function is only generated once and is then cached.
729 fn get_rust_try_fn<'ll, 'tcx>(
730 cx: &CodegenCx<'ll, 'tcx>,
731 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
733 if let Some(llfn) = cx.rust_try_fn.get() {
737 // Define the type up front for the signature of the rust_try function.
739 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
740 // `unsafe fn(*mut i8) -> ()`
741 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
745 hir::Unsafety::Unsafe,
748 // `unsafe fn(*mut i8, *mut i8) -> ()`
749 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
750 [i8p, i8p].iter().cloned(),
753 hir::Unsafety::Unsafe,
756 // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
757 let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
758 vec![try_fn_ty, i8p, catch_fn_ty].into_iter(),
761 hir::Unsafety::Unsafe,
764 let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
765 cx.rust_try_fn.set(Some(rust_try));
769 fn generic_simd_intrinsic(
770 bx: &mut Builder<'a, 'll, 'tcx>,
773 args: &[OperandRef<'tcx, &'ll Value>],
777 ) -> Result<&'ll Value, ()> {
778 // macros for error handling:
779 macro_rules! emit_error {
783 ($msg: tt, $($fmt: tt)*) => {
784 span_invalid_monomorphization_error(
786 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
791 macro_rules! return_error {
794 emit_error!($($fmt)*);
800 macro_rules! require {
801 ($cond: expr, $($fmt: tt)*) => {
803 return_error!($($fmt)*);
808 macro_rules! require_simd {
809 ($ty: expr, $position: expr) => {
810 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
816 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), callee_ty.fn_sig(tcx));
817 let arg_tys = sig.inputs();
818 let name_str = &*name.as_str();
820 if name == sym::simd_select_bitmask {
821 let in_ty = arg_tys[0];
822 let m_len = match in_ty.kind() {
823 // Note that this `.unwrap()` crashes for isize/usize, that's sort
824 // of intentional as there's not currently a use case for that.
825 ty::Int(i) => i.bit_width().unwrap(),
826 ty::Uint(i) => i.bit_width().unwrap(),
827 _ => return_error!("`{}` is not an integral type", in_ty),
829 require_simd!(arg_tys[1], "argument");
830 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
832 // Allow masks for vectors with fewer than 8 elements to be
833 // represented with a u8 or i8.
834 m_len == v_len || (m_len == 8 && v_len < 8),
835 "mismatched lengths: mask length `{}` != other vector length `{}`",
839 let i1 = bx.type_i1();
840 let im = bx.type_ix(v_len);
841 let i1xn = bx.type_vector(i1, v_len);
842 let m_im = bx.trunc(args[0].immediate(), im);
843 let m_i1s = bx.bitcast(m_im, i1xn);
844 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
847 // every intrinsic below takes a SIMD vector as its first argument
848 require_simd!(arg_tys[0], "input");
849 let in_ty = arg_tys[0];
851 let comparison = match name {
852 sym::simd_eq => Some(hir::BinOpKind::Eq),
853 sym::simd_ne => Some(hir::BinOpKind::Ne),
854 sym::simd_lt => Some(hir::BinOpKind::Lt),
855 sym::simd_le => Some(hir::BinOpKind::Le),
856 sym::simd_gt => Some(hir::BinOpKind::Gt),
857 sym::simd_ge => Some(hir::BinOpKind::Ge),
861 let (in_len, in_elem) = arg_tys[0].simd_size_and_type(bx.tcx());
862 if let Some(cmp_op) = comparison {
863 require_simd!(ret_ty, "return");
865 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
868 "expected return type with length {} (same as input type `{}`), \
869 found `{}` with length {}",
876 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
877 "expected return type with integer elements, found `{}` with non-integer `{}`",
882 return Ok(compare_simd_types(
892 if let Some(stripped) = name_str.strip_prefix("simd_shuffle") {
893 let n: u64 = stripped.parse().unwrap_or_else(|_| {
894 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
897 require_simd!(ret_ty, "return");
899 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
902 "expected return type of length {}, found `{}` with length {}",
909 "expected return element type `{}` (element of input `{}`), \
910 found `{}` with element type `{}`",
917 let total_len = u128::from(in_len) * 2;
919 let vector = args[2].immediate();
921 let indices: Option<Vec<_>> = (0..n)
924 let val = bx.const_get_elt(vector, i as u64);
925 match bx.const_to_opt_u128(val, true) {
927 emit_error!("shuffle index #{} is not a constant", arg_idx);
930 Some(idx) if idx >= total_len => {
932 "shuffle index #{} is out of bounds (limit {})",
938 Some(idx) => Some(bx.const_i32(idx as i32)),
942 let indices = match indices {
944 None => return Ok(bx.const_null(llret_ty)),
947 return Ok(bx.shuffle_vector(
950 bx.const_vector(&indices),
954 if name == sym::simd_insert {
956 in_elem == arg_tys[2],
957 "expected inserted type `{}` (element of input `{}`), found `{}`",
962 return Ok(bx.insert_element(
968 if name == sym::simd_extract {
971 "expected return type `{}` (element of input `{}`), found `{}`",
976 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
979 if name == sym::simd_select {
980 let m_elem_ty = in_elem;
982 require_simd!(arg_tys[1], "argument");
983 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
986 "mismatched lengths: mask length `{}` != other vector length `{}`",
990 match m_elem_ty.kind() {
992 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
994 // truncate the mask to a vector of i1s
995 let i1 = bx.type_i1();
996 let i1xn = bx.type_vector(i1, m_len as u64);
997 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
998 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1001 if name == sym::simd_bitmask {
1002 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1003 // vector mask and returns an unsigned integer containing the most
1004 // significant bit (MSB) of each lane.
1006 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1008 let expected_int_bits = in_len.max(8);
1009 match ret_ty.kind() {
1010 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1011 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1014 // Integer vector <i{in_bitwidth} x in_len>:
1015 let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
1017 args[0].immediate(),
1018 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1021 args[0].immediate(),
1022 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1025 "vector argument `{}`'s element type `{}`, expected integer element type",
1031 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1034 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1037 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1038 // Truncate vector to an <i1 x N>
1039 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1040 // Bitcast <i1 x N> to iN:
1041 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1042 // Zero-extend iN to the bitmask type:
1043 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1046 fn simd_simple_float_intrinsic(
1048 in_elem: &::rustc_middle::ty::TyS<'_>,
1049 in_ty: &::rustc_middle::ty::TyS<'_>,
1051 bx: &mut Builder<'a, 'll, 'tcx>,
1053 args: &[OperandRef<'tcx, &'ll Value>],
1054 ) -> Result<&'ll Value, ()> {
1055 macro_rules! emit_error {
1059 ($msg: tt, $($fmt: tt)*) => {
1060 span_invalid_monomorphization_error(
1062 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1066 macro_rules! return_error {
1069 emit_error!($($fmt)*);
1075 let (elem_ty_str, elem_ty) = if let ty::Float(f) = in_elem.kind() {
1076 let elem_ty = bx.cx.type_float_from_ty(*f);
1077 match f.bit_width() {
1078 32 => ("f32", elem_ty),
1079 64 => ("f64", elem_ty),
1082 "unsupported element type `{}` of floating-point vector `{}`",
1089 return_error!("`{}` is not a floating-point type", in_ty);
1092 let vec_ty = bx.type_vector(elem_ty, in_len);
1094 let (intr_name, fn_ty) = match name {
1095 sym::simd_ceil => ("ceil", bx.type_func(&[vec_ty], vec_ty)),
1096 sym::simd_fabs => ("fabs", bx.type_func(&[vec_ty], vec_ty)),
1097 sym::simd_fcos => ("cos", bx.type_func(&[vec_ty], vec_ty)),
1098 sym::simd_fexp2 => ("exp2", bx.type_func(&[vec_ty], vec_ty)),
1099 sym::simd_fexp => ("exp", bx.type_func(&[vec_ty], vec_ty)),
1100 sym::simd_flog10 => ("log10", bx.type_func(&[vec_ty], vec_ty)),
1101 sym::simd_flog2 => ("log2", bx.type_func(&[vec_ty], vec_ty)),
1102 sym::simd_flog => ("log", bx.type_func(&[vec_ty], vec_ty)),
1103 sym::simd_floor => ("floor", bx.type_func(&[vec_ty], vec_ty)),
1104 sym::simd_fma => ("fma", bx.type_func(&[vec_ty, vec_ty, vec_ty], vec_ty)),
1105 sym::simd_fpowi => ("powi", bx.type_func(&[vec_ty, bx.type_i32()], vec_ty)),
1106 sym::simd_fpow => ("pow", bx.type_func(&[vec_ty, vec_ty], vec_ty)),
1107 sym::simd_fsin => ("sin", bx.type_func(&[vec_ty], vec_ty)),
1108 sym::simd_fsqrt => ("sqrt", bx.type_func(&[vec_ty], vec_ty)),
1109 sym::simd_round => ("round", bx.type_func(&[vec_ty], vec_ty)),
1110 sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
1111 _ => return_error!("unrecognized intrinsic `{}`", name),
1113 let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str);
1114 let f = bx.declare_cfn(&llvm_name, llvm::UnnamedAddr::No, fn_ty);
1115 let c = bx.call(f, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1138 return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1142 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1143 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1144 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1145 let p0s: String = "p0".repeat(no_pointers);
1146 match *elem_ty.kind() {
1147 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1148 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1149 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1150 _ => unreachable!(),
1155 cx: &CodegenCx<'ll, '_>,
1158 mut no_pointers: usize,
1160 // FIXME: use cx.layout_of(ty).llvm_type() ?
1161 let mut elem_ty = match *elem_ty.kind() {
1162 ty::Int(v) => cx.type_int_from_ty(v),
1163 ty::Uint(v) => cx.type_uint_from_ty(v),
1164 ty::Float(v) => cx.type_float_from_ty(v),
1165 _ => unreachable!(),
1167 while no_pointers > 0 {
1168 elem_ty = cx.type_ptr_to(elem_ty);
1171 cx.type_vector(elem_ty, vec_len)
1174 if name == sym::simd_gather {
1175 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1176 // mask: <N x i{M}>) -> <N x T>
1177 // * N: number of elements in the input vectors
1178 // * T: type of the element to load
1179 // * M: any integer width is supported, will be truncated to i1
1181 // All types must be simd vector types
1182 require_simd!(in_ty, "first");
1183 require_simd!(arg_tys[1], "second");
1184 require_simd!(arg_tys[2], "third");
1185 require_simd!(ret_ty, "return");
1187 // Of the same length:
1188 let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1189 let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1192 "expected {} argument with length {} (same as input type `{}`), \
1193 found `{}` with length {}",
1202 "expected {} argument with length {} (same as input type `{}`), \
1203 found `{}` with length {}",
1211 // The return type must match the first argument type
1212 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1214 // This counts how many pointers
1215 fn ptr_count(t: Ty<'_>) -> usize {
1217 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1223 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1225 ty::RawPtr(p) => non_ptr(p.ty),
1230 // The second argument must be a simd vector with an element type that's a pointer
1231 // to the element type of the first argument
1232 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1233 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1234 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1235 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(element_ty1), non_ptr(element_ty1)),
1239 "expected element type `{}` of second argument `{}` \
1240 to be a pointer to the element type `{}` of the first \
1241 argument `{}`, found `{}` != `*_ {}`",
1252 assert!(pointer_count > 0);
1253 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1254 assert_eq!(underlying_ty, non_ptr(element_ty0));
1256 // The element type of the third argument must be a signed integer type of any width:
1257 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1258 match element_ty2.kind() {
1263 "expected element type `{}` of third argument `{}` \
1264 to be a signed integer type",
1271 // Alignment of T, must be a constant integer value:
1272 let alignment_ty = bx.type_i32();
1273 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1275 // Truncate the mask vector to a vector of i1s:
1276 let (mask, mask_ty) = {
1277 let i1 = bx.type_i1();
1278 let i1xn = bx.type_vector(i1, in_len);
1279 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1282 // Type of the vector of pointers:
1283 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1284 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1286 // Type of the vector of elements:
1287 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1288 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1290 let llvm_intrinsic =
1291 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1292 let f = bx.declare_cfn(
1294 llvm::UnnamedAddr::No,
1296 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1300 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1304 if name == sym::simd_scatter {
1305 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1306 // mask: <N x i{M}>) -> ()
1307 // * N: number of elements in the input vectors
1308 // * T: type of the element to load
1309 // * M: any integer width is supported, will be truncated to i1
1311 // All types must be simd vector types
1312 require_simd!(in_ty, "first");
1313 require_simd!(arg_tys[1], "second");
1314 require_simd!(arg_tys[2], "third");
1316 // Of the same length:
1317 let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1318 let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1320 in_len == element_len1,
1321 "expected {} argument with length {} (same as input type `{}`), \
1322 found `{}` with length {}",
1330 in_len == element_len2,
1331 "expected {} argument with length {} (same as input type `{}`), \
1332 found `{}` with length {}",
1340 // This counts how many pointers
1341 fn ptr_count(t: Ty<'_>) -> usize {
1343 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1349 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1351 ty::RawPtr(p) => non_ptr(p.ty),
1356 // The second argument must be a simd vector with an element type that's a pointer
1357 // to the element type of the first argument
1358 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1359 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1360 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1361 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1362 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1363 (ptr_count(element_ty1), non_ptr(element_ty1))
1368 "expected element type `{}` of second argument `{}` \
1369 to be a pointer to the element type `{}` of the first \
1370 argument `{}`, found `{}` != `*mut {}`",
1381 assert!(pointer_count > 0);
1382 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1383 assert_eq!(underlying_ty, non_ptr(element_ty0));
1385 // The element type of the third argument must be a signed integer type of any width:
1386 match element_ty2.kind() {
1391 "expected element type `{}` of third argument `{}` \
1392 be a signed integer type",
1399 // Alignment of T, must be a constant integer value:
1400 let alignment_ty = bx.type_i32();
1401 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1403 // Truncate the mask vector to a vector of i1s:
1404 let (mask, mask_ty) = {
1405 let i1 = bx.type_i1();
1406 let i1xn = bx.type_vector(i1, in_len);
1407 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1410 let ret_t = bx.type_void();
1412 // Type of the vector of pointers:
1413 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1414 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1416 // Type of the vector of elements:
1417 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1418 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1420 let llvm_intrinsic =
1421 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1422 let f = bx.declare_cfn(
1424 llvm::UnnamedAddr::No,
1425 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1427 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1431 macro_rules! arith_red {
1432 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1433 $identity:expr) => {
1434 if name == sym::$name {
1437 "expected return type `{}` (element of input `{}`), found `{}`",
1442 return match in_elem.kind() {
1443 ty::Int(_) | ty::Uint(_) => {
1444 let r = bx.$integer_reduce(args[0].immediate());
1446 // if overflow occurs, the result is the
1447 // mathematical result modulo 2^n:
1448 Ok(bx.$op(args[1].immediate(), r))
1450 Ok(bx.$integer_reduce(args[0].immediate()))
1454 let acc = if $ordered {
1455 // ordered arithmetic reductions take an accumulator
1458 // unordered arithmetic reductions use the identity accumulator
1459 match f.bit_width() {
1460 32 => bx.const_real(bx.type_f32(), $identity),
1461 64 => bx.const_real(bx.type_f64(), $identity),
1464 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1473 Ok(bx.$float_reduce(acc, args[0].immediate()))
1476 "unsupported {} from `{}` with element `{}` to `{}`",
1487 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1488 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1490 simd_reduce_add_unordered: vector_reduce_add,
1491 vector_reduce_fadd_fast,
1497 simd_reduce_mul_unordered: vector_reduce_mul,
1498 vector_reduce_fmul_fast,
1504 macro_rules! minmax_red {
1505 ($name:ident: $int_red:ident, $float_red:ident) => {
1506 if name == sym::$name {
1509 "expected return type `{}` (element of input `{}`), found `{}`",
1514 return match in_elem.kind() {
1515 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1516 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1517 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1519 "unsupported {} from `{}` with element `{}` to `{}`",
1530 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1531 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1533 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1534 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1536 macro_rules! bitwise_red {
1537 ($name:ident : $red:ident, $boolean:expr) => {
1538 if name == sym::$name {
1539 let input = if !$boolean {
1542 "expected return type `{}` (element of input `{}`), found `{}`",
1549 match in_elem.kind() {
1550 ty::Int(_) | ty::Uint(_) => {}
1552 "unsupported {} from `{}` with element `{}` to `{}`",
1560 // boolean reductions operate on vectors of i1s:
1561 let i1 = bx.type_i1();
1562 let i1xn = bx.type_vector(i1, in_len as u64);
1563 bx.trunc(args[0].immediate(), i1xn)
1565 return match in_elem.kind() {
1566 ty::Int(_) | ty::Uint(_) => {
1567 let r = bx.$red(input);
1568 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1571 "unsupported {} from `{}` with element `{}` to `{}`",
1582 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
1583 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
1584 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
1585 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
1586 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
1588 if name == sym::simd_cast {
1589 require_simd!(ret_ty, "return");
1590 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1593 "expected return type with length {} (same as input type `{}`), \
1594 found `{}` with length {}",
1600 // casting cares about nominal type, not just structural type
1601 if in_elem == out_elem {
1602 return Ok(args[0].immediate());
1607 Int(/* is signed? */ bool),
1611 let (in_style, in_width) = match in_elem.kind() {
1612 // vectors of pointer-sized integers should've been
1613 // disallowed before here, so this unwrap is safe.
1614 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1615 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1616 ty::Float(f) => (Style::Float, f.bit_width()),
1617 _ => (Style::Unsupported, 0),
1619 let (out_style, out_width) = match out_elem.kind() {
1620 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1621 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1622 ty::Float(f) => (Style::Float, f.bit_width()),
1623 _ => (Style::Unsupported, 0),
1626 match (in_style, out_style) {
1627 (Style::Int(in_is_signed), Style::Int(_)) => {
1628 return Ok(match in_width.cmp(&out_width) {
1629 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1630 Ordering::Equal => args[0].immediate(),
1633 bx.sext(args[0].immediate(), llret_ty)
1635 bx.zext(args[0].immediate(), llret_ty)
1640 (Style::Int(in_is_signed), Style::Float) => {
1641 return Ok(if in_is_signed {
1642 bx.sitofp(args[0].immediate(), llret_ty)
1644 bx.uitofp(args[0].immediate(), llret_ty)
1647 (Style::Float, Style::Int(out_is_signed)) => {
1648 return Ok(if out_is_signed {
1649 bx.fptosi(args[0].immediate(), llret_ty)
1651 bx.fptoui(args[0].immediate(), llret_ty)
1654 (Style::Float, Style::Float) => {
1655 return Ok(match in_width.cmp(&out_width) {
1656 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1657 Ordering::Equal => args[0].immediate(),
1658 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1661 _ => { /* Unsupported. Fallthrough. */ }
1665 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1672 macro_rules! arith_binary {
1673 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1674 $(if name == sym::$name {
1675 match in_elem.kind() {
1676 $($(ty::$p(_))|* => {
1677 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1682 "unsupported operation on `{}` with element `{}`",
1689 simd_add: Uint, Int => add, Float => fadd;
1690 simd_sub: Uint, Int => sub, Float => fsub;
1691 simd_mul: Uint, Int => mul, Float => fmul;
1692 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1693 simd_rem: Uint => urem, Int => srem, Float => frem;
1694 simd_shl: Uint, Int => shl;
1695 simd_shr: Uint => lshr, Int => ashr;
1696 simd_and: Uint, Int => and;
1697 simd_or: Uint, Int => or;
1698 simd_xor: Uint, Int => xor;
1699 simd_fmax: Float => maxnum;
1700 simd_fmin: Float => minnum;
1703 macro_rules! arith_unary {
1704 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1705 $(if name == sym::$name {
1706 match in_elem.kind() {
1707 $($(ty::$p(_))|* => {
1708 return Ok(bx.$call(args[0].immediate()))
1713 "unsupported operation on `{}` with element `{}`",
1720 simd_neg: Int => neg, Float => fneg;
1723 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
1724 let lhs = args[0].immediate();
1725 let rhs = args[1].immediate();
1726 let is_add = name == sym::simd_saturating_add;
1727 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1728 let (signed, elem_width, elem_ty) = match *in_elem.kind() {
1729 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
1730 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
1733 "expected element type `{}` of vector type `{}` \
1734 to be a signed or unsigned integer type",
1735 arg_tys[0].simd_size_and_type(bx.tcx()).1,
1740 let llvm_intrinsic = &format!(
1741 "llvm.{}{}.sat.v{}i{}",
1742 if signed { 's' } else { 'u' },
1743 if is_add { "add" } else { "sub" },
1747 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1749 let f = bx.declare_cfn(
1751 llvm::UnnamedAddr::No,
1752 bx.type_func(&[vec_ty, vec_ty], vec_ty),
1754 let v = bx.call(f, &[lhs, rhs], None);
1758 span_bug!(span, "unknown SIMD intrinsic");
1761 // Returns the width of an int Ty, and if it's signed or not
1762 // Returns None if the type is not an integer
1763 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1765 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1768 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), true))
1771 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), false))