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;
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::{FnAbiOf, HasTyCtxt, LayoutOf};
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, Align, HasDataLayout, Primitive};
22 use rustc_target::spec::{HasTargetSpec, PanicStrategy};
24 use std::cmp::Ordering;
27 fn get_simple_intrinsic<'ll>(
28 cx: &CodegenCx<'ll, '_>,
30 ) -> Option<(&'ll Type, &'ll Value)> {
31 let llvm_name = match name {
32 sym::sqrtf32 => "llvm.sqrt.f32",
33 sym::sqrtf64 => "llvm.sqrt.f64",
34 sym::powif32 => "llvm.powi.f32",
35 sym::powif64 => "llvm.powi.f64",
36 sym::sinf32 => "llvm.sin.f32",
37 sym::sinf64 => "llvm.sin.f64",
38 sym::cosf32 => "llvm.cos.f32",
39 sym::cosf64 => "llvm.cos.f64",
40 sym::powf32 => "llvm.pow.f32",
41 sym::powf64 => "llvm.pow.f64",
42 sym::expf32 => "llvm.exp.f32",
43 sym::expf64 => "llvm.exp.f64",
44 sym::exp2f32 => "llvm.exp2.f32",
45 sym::exp2f64 => "llvm.exp2.f64",
46 sym::logf32 => "llvm.log.f32",
47 sym::logf64 => "llvm.log.f64",
48 sym::log10f32 => "llvm.log10.f32",
49 sym::log10f64 => "llvm.log10.f64",
50 sym::log2f32 => "llvm.log2.f32",
51 sym::log2f64 => "llvm.log2.f64",
52 sym::fmaf32 => "llvm.fma.f32",
53 sym::fmaf64 => "llvm.fma.f64",
54 sym::fabsf32 => "llvm.fabs.f32",
55 sym::fabsf64 => "llvm.fabs.f64",
56 sym::minnumf32 => "llvm.minnum.f32",
57 sym::minnumf64 => "llvm.minnum.f64",
58 sym::maxnumf32 => "llvm.maxnum.f32",
59 sym::maxnumf64 => "llvm.maxnum.f64",
60 sym::copysignf32 => "llvm.copysign.f32",
61 sym::copysignf64 => "llvm.copysign.f64",
62 sym::floorf32 => "llvm.floor.f32",
63 sym::floorf64 => "llvm.floor.f64",
64 sym::ceilf32 => "llvm.ceil.f32",
65 sym::ceilf64 => "llvm.ceil.f64",
66 sym::truncf32 => "llvm.trunc.f32",
67 sym::truncf64 => "llvm.trunc.f64",
68 sym::rintf32 => "llvm.rint.f32",
69 sym::rintf64 => "llvm.rint.f64",
70 sym::nearbyintf32 => "llvm.nearbyint.f32",
71 sym::nearbyintf64 => "llvm.nearbyint.f64",
72 sym::roundf32 => "llvm.round.f32",
73 sym::roundf64 => "llvm.round.f64",
74 sym::ptr_mask => "llvm.ptrmask",
77 Some(cx.get_intrinsic(llvm_name))
80 impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
81 fn codegen_intrinsic_call(
83 instance: ty::Instance<'tcx>,
84 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
85 args: &[OperandRef<'tcx, &'ll Value>],
90 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
92 let ty::FnDef(def_id, substs) = *callee_ty.kind() else {
93 bug!("expected fn item type, found {}", callee_ty);
96 let sig = callee_ty.fn_sig(tcx);
97 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
98 let arg_tys = sig.inputs();
99 let ret_ty = sig.output();
100 let name = tcx.item_name(def_id);
102 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
103 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
105 let simple = get_simple_intrinsic(self, name);
106 let llval = match name {
107 _ if simple.is_some() => {
108 let (simple_ty, simple_fn) = simple.unwrap();
112 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
117 self.call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(true)])
119 sym::unlikely => self
120 .call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(false)]),
131 sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[]),
133 self.call_intrinsic("llvm.va_copy", &[args[0].immediate(), args[1].immediate()])
136 match fn_abi.ret.layout.abi {
137 abi::Abi::Scalar(scalar) => {
138 match scalar.primitive() {
139 Primitive::Int(..) => {
140 if self.cx().size_of(ret_ty).bytes() < 4 {
141 // `va_arg` should not be called on an integer type
142 // less than 4 bytes in length. If it is, promote
143 // the integer to an `i32` and truncate the result
144 // back to the smaller type.
145 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
146 self.trunc(promoted_result, llret_ty)
148 emit_va_arg(self, args[0], ret_ty)
151 Primitive::F64 | Primitive::Pointer => {
152 emit_va_arg(self, args[0], ret_ty)
154 // `va_arg` should never be used with the return type f32.
155 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
158 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
162 sym::volatile_load | sym::unaligned_volatile_load => {
163 let tp_ty = substs.type_at(0);
164 let ptr = args[0].immediate();
165 let load = if let PassMode::Cast(ty, _) = &fn_abi.ret.mode {
166 let llty = ty.llvm_type(self);
167 let ptr = self.pointercast(ptr, self.type_ptr_to(llty));
168 self.volatile_load(llty, ptr)
170 self.volatile_load(self.layout_of(tp_ty).llvm_type(self), ptr)
172 let align = if name == sym::unaligned_volatile_load {
175 self.align_of(tp_ty).bytes() as u32
178 llvm::LLVMSetAlignment(load, align);
180 self.to_immediate(load, self.layout_of(tp_ty))
182 sym::volatile_store => {
183 let dst = args[0].deref(self.cx());
184 args[1].val.volatile_store(self, dst);
187 sym::unaligned_volatile_store => {
188 let dst = args[0].deref(self.cx());
189 args[1].val.unaligned_volatile_store(self, dst);
192 sym::prefetch_read_data
193 | sym::prefetch_write_data
194 | sym::prefetch_read_instruction
195 | sym::prefetch_write_instruction => {
196 let (rw, cache_type) = match name {
197 sym::prefetch_read_data => (0, 1),
198 sym::prefetch_write_data => (1, 1),
199 sym::prefetch_read_instruction => (0, 0),
200 sym::prefetch_write_instruction => (1, 0),
209 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);
230 &format!("llvm.{}.i{}", name, width),
231 &[args[0].immediate(), y],
234 sym::ctlz_nonzero => {
235 let y = self.const_bool(true);
236 let llvm_name = &format!("llvm.ctlz.i{}", width);
237 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
239 sym::cttz_nonzero => {
240 let y = self.const_bool(true);
241 let llvm_name = &format!("llvm.cttz.i{}", width);
242 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
244 sym::ctpop => self.call_intrinsic(
245 &format!("llvm.ctpop.i{}", width),
246 &[args[0].immediate()],
250 args[0].immediate() // byte swap a u8/i8 is just a no-op
253 &format!("llvm.bswap.i{}", width),
254 &[args[0].immediate()],
258 sym::bitreverse => self.call_intrinsic(
259 &format!("llvm.bitreverse.i{}", width),
260 &[args[0].immediate()],
262 sym::rotate_left | sym::rotate_right => {
263 let is_left = name == sym::rotate_left;
264 let val = args[0].immediate();
265 let raw_shift = args[1].immediate();
266 // rotate = funnel shift with first two args the same
268 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
269 self.call_intrinsic(llvm_name, &[val, val, raw_shift])
271 sym::saturating_add | sym::saturating_sub => {
272 let is_add = name == sym::saturating_add;
273 let lhs = args[0].immediate();
274 let rhs = args[1].immediate();
275 let llvm_name = &format!(
277 if signed { 's' } else { 'u' },
278 if is_add { "add" } else { "sub" },
281 self.call_intrinsic(llvm_name, &[lhs, rhs])
286 span_invalid_monomorphization_error(
290 "invalid monomorphization of `{}` intrinsic: \
291 expected basic integer type, found `{}`",
302 let tp_ty = substs.type_at(0);
303 let layout = self.layout_of(tp_ty).layout;
304 let use_integer_compare = match layout.abi() {
305 Scalar(_) | ScalarPair(_, _) => true,
306 Uninhabited | Vector { .. } => false,
307 Aggregate { .. } => {
308 // For rusty ABIs, small aggregates are actually passed
309 // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
310 // so we re-use that same threshold here.
311 layout.size() <= self.data_layout().pointer_size * 2
315 let a = args[0].immediate();
316 let b = args[1].immediate();
317 if layout.size().bytes() == 0 {
318 self.const_bool(true)
319 } else if use_integer_compare {
320 let integer_ty = self.type_ix(layout.size().bits());
321 let ptr_ty = self.type_ptr_to(integer_ty);
322 let a_ptr = self.bitcast(a, ptr_ty);
323 let a_val = self.load(integer_ty, a_ptr, layout.align().abi);
324 let b_ptr = self.bitcast(b, ptr_ty);
325 let b_val = self.load(integer_ty, b_ptr, layout.align().abi);
326 self.icmp(IntPredicate::IntEQ, a_val, b_val)
328 let i8p_ty = self.type_i8p();
329 let a_ptr = self.bitcast(a, i8p_ty);
330 let b_ptr = self.bitcast(b, i8p_ty);
331 let n = self.const_usize(layout.size().bytes());
332 let cmp = self.call_intrinsic("memcmp", &[a_ptr, b_ptr, n]);
333 match self.cx.sess().target.arch.as_ref() {
334 "avr" | "msp430" => self.icmp(IntPredicate::IntEQ, cmp, self.const_i16(0)),
335 _ => self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0)),
341 args[0].val.store(self, result);
343 // We need to "use" the argument in some way LLVM can't introspect, and on
344 // targets that support it we can typically leverage inline assembly to do
345 // this. LLVM's interpretation of inline assembly is that it's, well, a black
346 // box. This isn't the greatest implementation since it probably deoptimizes
347 // more than we want, but it's so far good enough.
348 crate::asm::inline_asm_call(
356 llvm::AsmDialect::Att,
361 .unwrap_or_else(|| bug!("failed to generate inline asm call for `black_box`"));
363 // We have copied the value to `result` already.
367 _ if name.as_str().starts_with("simd_") => {
368 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
374 _ => bug!("unknown intrinsic '{}'", name),
377 if !fn_abi.ret.is_ignore() {
378 if let PassMode::Cast(ty, _) = &fn_abi.ret.mode {
379 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
380 let ptr = self.pointercast(result.llval, ptr_llty);
381 self.store(llval, ptr, result.align);
383 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
385 .store(self, result);
390 fn abort(&mut self) {
391 self.call_intrinsic("llvm.trap", &[]);
394 fn assume(&mut self, val: Self::Value) {
395 self.call_intrinsic("llvm.assume", &[val]);
398 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
399 self.call_intrinsic("llvm.expect.i1", &[cond, self.const_bool(expected)])
402 fn type_test(&mut self, pointer: Self::Value, typeid: Self::Value) -> Self::Value {
403 // Test the called operand using llvm.type.test intrinsic. The LowerTypeTests link-time
404 // optimization pass replaces calls to this intrinsic with code to test type membership.
405 let i8p_ty = self.type_i8p();
406 let bitcast = self.bitcast(pointer, i8p_ty);
407 self.call_intrinsic("llvm.type.test", &[bitcast, typeid])
410 fn type_checked_load(
412 llvtable: &'ll Value,
413 vtable_byte_offset: u64,
416 let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
417 self.call_intrinsic("llvm.type.checked.load", &[llvtable, vtable_byte_offset, typeid])
420 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
421 self.call_intrinsic("llvm.va_start", &[va_list])
424 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
425 self.call_intrinsic("llvm.va_end", &[va_list])
429 fn try_intrinsic<'ll>(
430 bx: &mut Builder<'_, 'll, '_>,
431 try_func: &'ll Value,
433 catch_func: &'ll Value,
436 if bx.sess().panic_strategy() == PanicStrategy::Abort {
437 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
438 bx.call(try_func_ty, try_func, &[data], None);
439 // Return 0 unconditionally from the intrinsic call;
440 // we can never unwind.
441 let ret_align = bx.tcx().data_layout.i32_align.abi;
442 bx.store(bx.const_i32(0), dest, ret_align);
443 } else if wants_msvc_seh(bx.sess()) {
444 codegen_msvc_try(bx, try_func, data, catch_func, dest);
445 } else if bx.sess().target.os == "emscripten" {
446 codegen_emcc_try(bx, try_func, data, catch_func, dest);
448 codegen_gnu_try(bx, try_func, data, catch_func, dest);
452 // MSVC's definition of the `rust_try` function.
454 // This implementation uses the new exception handling instructions in LLVM
455 // which have support in LLVM for SEH on MSVC targets. Although these
456 // instructions are meant to work for all targets, as of the time of this
457 // writing, however, LLVM does not recommend the usage of these new instructions
458 // as the old ones are still more optimized.
459 fn codegen_msvc_try<'ll>(
460 bx: &mut Builder<'_, 'll, '_>,
461 try_func: &'ll Value,
463 catch_func: &'ll Value,
466 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
467 bx.set_personality_fn(bx.eh_personality());
469 let normal = bx.append_sibling_block("normal");
470 let catchswitch = bx.append_sibling_block("catchswitch");
471 let catchpad_rust = bx.append_sibling_block("catchpad_rust");
472 let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
473 let caught = bx.append_sibling_block("caught");
475 let try_func = llvm::get_param(bx.llfn(), 0);
476 let data = llvm::get_param(bx.llfn(), 1);
477 let catch_func = llvm::get_param(bx.llfn(), 2);
479 // We're generating an IR snippet that looks like:
481 // declare i32 @rust_try(%try_func, %data, %catch_func) {
482 // %slot = alloca i8*
483 // invoke %try_func(%data) to label %normal unwind label %catchswitch
489 // %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
492 // %tok = catchpad within %cs [%type_descriptor, 8, %slot]
494 // call %catch_func(%data, %ptr)
495 // catchret from %tok to label %caught
498 // %tok = catchpad within %cs [null, 64, null]
499 // call %catch_func(%data, null)
500 // catchret from %tok to label %caught
506 // This structure follows the basic usage of throw/try/catch in LLVM.
507 // For example, compile this C++ snippet to see what LLVM generates:
509 // struct rust_panic {
510 // rust_panic(const rust_panic&);
517 // void (*try_func)(void*),
519 // void (*catch_func)(void*, void*) noexcept
524 // } catch(rust_panic& a) {
525 // catch_func(data, &a);
528 // catch_func(data, NULL);
533 // More information can be found in libstd's seh.rs implementation.
534 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
535 let slot = bx.alloca(bx.type_i8p(), ptr_align);
536 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
537 bx.invoke(try_func_ty, try_func, &[data], normal, catchswitch, None);
539 bx.switch_to_block(normal);
540 bx.ret(bx.const_i32(0));
542 bx.switch_to_block(catchswitch);
543 let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
545 // We can't use the TypeDescriptor defined in libpanic_unwind because it
546 // might be in another DLL and the SEH encoding only supports specifying
547 // a TypeDescriptor from the current module.
549 // However this isn't an issue since the MSVC runtime uses string
550 // comparison on the type name to match TypeDescriptors rather than
553 // So instead we generate a new TypeDescriptor in each module that uses
554 // `try` and let the linker merge duplicate definitions in the same
557 // When modifying, make sure that the type_name string exactly matches
558 // the one used in src/libpanic_unwind/seh.rs.
559 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
560 let type_name = bx.const_bytes(b"rust_panic\0");
562 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
563 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
565 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
566 llvm::SetUniqueComdat(bx.llmod, tydesc);
567 llvm::LLVMSetInitializer(tydesc, type_info);
570 // The flag value of 8 indicates that we are catching the exception by
571 // reference instead of by value. We can't use catch by value because
572 // that requires copying the exception object, which we don't support
573 // since our exception object effectively contains a Box.
575 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
576 bx.switch_to_block(catchpad_rust);
577 let flags = bx.const_i32(8);
578 let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
579 let ptr = bx.load(bx.type_i8p(), slot, ptr_align);
580 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
581 bx.call(catch_ty, catch_func, &[data, ptr], Some(&funclet));
582 bx.catch_ret(&funclet, caught);
584 // The flag value of 64 indicates a "catch-all".
585 bx.switch_to_block(catchpad_foreign);
586 let flags = bx.const_i32(64);
587 let null = bx.const_null(bx.type_i8p());
588 let funclet = bx.catch_pad(cs, &[null, flags, null]);
589 bx.call(catch_ty, catch_func, &[data, null], Some(&funclet));
590 bx.catch_ret(&funclet, caught);
592 bx.switch_to_block(caught);
593 bx.ret(bx.const_i32(1));
596 // Note that no invoke is used here because by definition this function
597 // can't panic (that's what it's catching).
598 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
599 let i32_align = bx.tcx().data_layout.i32_align.abi;
600 bx.store(ret, dest, i32_align);
603 // Definition of the standard `try` function for Rust using the GNU-like model
604 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
607 // This codegen is a little surprising because we always call a shim
608 // function instead of inlining the call to `invoke` manually here. This is done
609 // because in LLVM we're only allowed to have one personality per function
610 // definition. The call to the `try` intrinsic is being inlined into the
611 // function calling it, and that function may already have other personality
612 // functions in play. By calling a shim we're guaranteed that our shim will have
613 // the right personality function.
614 fn codegen_gnu_try<'ll>(
615 bx: &mut Builder<'_, 'll, '_>,
616 try_func: &'ll Value,
618 catch_func: &'ll Value,
621 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
622 // Codegens the shims described above:
625 // invoke %try_func(%data) normal %normal unwind %catch
631 // (%ptr, _) = landingpad
632 // call %catch_func(%data, %ptr)
634 let then = bx.append_sibling_block("then");
635 let catch = bx.append_sibling_block("catch");
637 let try_func = llvm::get_param(bx.llfn(), 0);
638 let data = llvm::get_param(bx.llfn(), 1);
639 let catch_func = llvm::get_param(bx.llfn(), 2);
640 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
641 bx.invoke(try_func_ty, try_func, &[data], then, catch, None);
643 bx.switch_to_block(then);
644 bx.ret(bx.const_i32(0));
646 // Type indicator for the exception being thrown.
648 // The first value in this tuple is a pointer to the exception object
649 // being thrown. The second value is a "selector" indicating which of
650 // the landing pad clauses the exception's type had been matched to.
651 // rust_try ignores the selector.
652 bx.switch_to_block(catch);
653 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
654 let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
655 let tydesc = bx.const_null(bx.type_i8p());
656 bx.add_clause(vals, tydesc);
657 let ptr = bx.extract_value(vals, 0);
658 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
659 bx.call(catch_ty, catch_func, &[data, ptr], None);
660 bx.ret(bx.const_i32(1));
663 // Note that no invoke is used here because by definition this function
664 // can't panic (that's what it's catching).
665 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
666 let i32_align = bx.tcx().data_layout.i32_align.abi;
667 bx.store(ret, dest, i32_align);
670 // Variant of codegen_gnu_try used for emscripten where Rust panics are
671 // implemented using C++ exceptions. Here we use exceptions of a specific type
672 // (`struct rust_panic`) to represent Rust panics.
673 fn codegen_emcc_try<'ll>(
674 bx: &mut Builder<'_, 'll, '_>,
675 try_func: &'ll Value,
677 catch_func: &'ll Value,
680 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
681 // Codegens the shims described above:
684 // invoke %try_func(%data) normal %normal unwind %catch
690 // (%ptr, %selector) = landingpad
691 // %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
692 // %is_rust_panic = %selector == %rust_typeid
693 // %catch_data = alloca { i8*, i8 }
694 // %catch_data[0] = %ptr
695 // %catch_data[1] = %is_rust_panic
696 // call %catch_func(%data, %catch_data)
698 let then = bx.append_sibling_block("then");
699 let catch = bx.append_sibling_block("catch");
701 let try_func = llvm::get_param(bx.llfn(), 0);
702 let data = llvm::get_param(bx.llfn(), 1);
703 let catch_func = llvm::get_param(bx.llfn(), 2);
704 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
705 bx.invoke(try_func_ty, try_func, &[data], then, catch, None);
707 bx.switch_to_block(then);
708 bx.ret(bx.const_i32(0));
710 // Type indicator for the exception being thrown.
712 // The first value in this tuple is a pointer to the exception object
713 // being thrown. The second value is a "selector" indicating which of
714 // the landing pad clauses the exception's type had been matched to.
715 bx.switch_to_block(catch);
716 let tydesc = bx.eh_catch_typeinfo();
717 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
718 let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
719 bx.add_clause(vals, tydesc);
720 bx.add_clause(vals, bx.const_null(bx.type_i8p()));
721 let ptr = bx.extract_value(vals, 0);
722 let selector = bx.extract_value(vals, 1);
724 // Check if the typeid we got is the one for a Rust panic.
725 let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[tydesc]);
726 let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
727 let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
729 // We need to pass two values to catch_func (ptr and is_rust_panic), so
730 // create an alloca and pass a pointer to that.
731 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
732 let i8_align = bx.tcx().data_layout.i8_align.abi;
733 let catch_data_type = bx.type_struct(&[bx.type_i8p(), bx.type_bool()], false);
734 let catch_data = bx.alloca(catch_data_type, ptr_align);
736 bx.inbounds_gep(catch_data_type, catch_data, &[bx.const_usize(0), bx.const_usize(0)]);
737 bx.store(ptr, catch_data_0, ptr_align);
739 bx.inbounds_gep(catch_data_type, catch_data, &[bx.const_usize(0), bx.const_usize(1)]);
740 bx.store(is_rust_panic, catch_data_1, i8_align);
741 let catch_data = bx.bitcast(catch_data, bx.type_i8p());
743 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
744 bx.call(catch_ty, catch_func, &[data, catch_data], None);
745 bx.ret(bx.const_i32(1));
748 // Note that no invoke is used here because by definition this function
749 // can't panic (that's what it's catching).
750 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
751 let i32_align = bx.tcx().data_layout.i32_align.abi;
752 bx.store(ret, dest, i32_align);
755 // Helper function to give a Block to a closure to codegen a shim function.
756 // This is currently primarily used for the `try` intrinsic functions above.
757 fn gen_fn<'ll, 'tcx>(
758 cx: &CodegenCx<'ll, 'tcx>,
760 rust_fn_sig: ty::PolyFnSig<'tcx>,
761 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
762 ) -> (&'ll Type, &'ll Value) {
763 let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
764 let llty = fn_abi.llvm_type(cx);
765 let llfn = cx.declare_fn(name, fn_abi);
766 cx.set_frame_pointer_type(llfn);
767 cx.apply_target_cpu_attr(llfn);
768 // FIXME(eddyb) find a nicer way to do this.
769 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
770 let llbb = Builder::append_block(cx, llfn, "entry-block");
771 let bx = Builder::build(cx, llbb);
776 // Helper function used to get a handle to the `__rust_try` function used to
779 // This function is only generated once and is then cached.
780 fn get_rust_try_fn<'ll, 'tcx>(
781 cx: &CodegenCx<'ll, 'tcx>,
782 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
783 ) -> (&'ll Type, &'ll Value) {
784 if let Some(llfn) = cx.rust_try_fn.get() {
788 // Define the type up front for the signature of the rust_try function.
790 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
791 // `unsafe fn(*mut i8) -> ()`
792 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
796 hir::Unsafety::Unsafe,
799 // `unsafe fn(*mut i8, *mut i8) -> ()`
800 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
801 [i8p, i8p].iter().cloned(),
804 hir::Unsafety::Unsafe,
807 // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
808 let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
809 [try_fn_ty, i8p, catch_fn_ty].into_iter(),
812 hir::Unsafety::Unsafe,
815 let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
816 cx.rust_try_fn.set(Some(rust_try));
820 fn generic_simd_intrinsic<'ll, 'tcx>(
821 bx: &mut Builder<'_, 'll, 'tcx>,
824 args: &[OperandRef<'tcx, &'ll Value>],
828 ) -> Result<&'ll Value, ()> {
829 // macros for error handling:
830 #[allow(unused_macro_rules)]
831 macro_rules! emit_error {
835 ($msg: tt, $($fmt: tt)*) => {
836 span_invalid_monomorphization_error(
838 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
843 macro_rules! return_error {
846 emit_error!($($fmt)*);
852 macro_rules! require {
853 ($cond: expr, $($fmt: tt)*) => {
855 return_error!($($fmt)*);
860 macro_rules! require_simd {
861 ($ty: expr, $position: expr) => {
862 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
868 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), callee_ty.fn_sig(tcx));
869 let arg_tys = sig.inputs();
871 if name == sym::simd_select_bitmask {
872 require_simd!(arg_tys[1], "argument");
873 let (len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
875 let expected_int_bits = (len.max(8) - 1).next_power_of_two();
876 let expected_bytes = len / 8 + ((len % 8 > 0) as u64);
878 let mask_ty = arg_tys[0];
879 let mask = match mask_ty.kind() {
880 ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
881 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
883 if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
884 && len.try_eval_usize(bx.tcx, ty::ParamEnv::reveal_all())
885 == Some(expected_bytes) =>
887 let place = PlaceRef::alloca(bx, args[0].layout);
888 args[0].val.store(bx, place);
889 let int_ty = bx.type_ix(expected_bytes * 8);
890 let ptr = bx.pointercast(place.llval, bx.cx.type_ptr_to(int_ty));
891 bx.load(int_ty, ptr, Align::ONE)
894 "invalid bitmask `{}`, expected `u{}` or `[u8; {}]`",
901 let i1 = bx.type_i1();
902 let im = bx.type_ix(len);
903 let i1xn = bx.type_vector(i1, len);
904 let m_im = bx.trunc(mask, im);
905 let m_i1s = bx.bitcast(m_im, i1xn);
906 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
909 // every intrinsic below takes a SIMD vector as its first argument
910 require_simd!(arg_tys[0], "input");
911 let in_ty = arg_tys[0];
913 let comparison = match name {
914 sym::simd_eq => Some(hir::BinOpKind::Eq),
915 sym::simd_ne => Some(hir::BinOpKind::Ne),
916 sym::simd_lt => Some(hir::BinOpKind::Lt),
917 sym::simd_le => Some(hir::BinOpKind::Le),
918 sym::simd_gt => Some(hir::BinOpKind::Gt),
919 sym::simd_ge => Some(hir::BinOpKind::Ge),
923 let (in_len, in_elem) = arg_tys[0].simd_size_and_type(bx.tcx());
924 if let Some(cmp_op) = comparison {
925 require_simd!(ret_ty, "return");
927 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
930 "expected return type with length {} (same as input type `{}`), \
931 found `{}` with length {}",
938 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
939 "expected return type with integer elements, found `{}` with non-integer `{}`",
944 return Ok(compare_simd_types(
954 if let Some(stripped) = name.as_str().strip_prefix("simd_shuffle") {
955 // If this intrinsic is the older "simd_shuffleN" form, simply parse the integer.
956 // If there is no suffix, use the index array length.
957 let n: u64 = if stripped.is_empty() {
958 // Make sure this is actually an array, since typeck only checks the length-suffixed
959 // version of this intrinsic.
960 match args[2].layout.ty.kind() {
961 ty::Array(ty, len) if matches!(ty.kind(), ty::Uint(ty::UintTy::U32)) => {
962 len.try_eval_usize(bx.cx.tcx, ty::ParamEnv::reveal_all()).unwrap_or_else(|| {
963 span_bug!(span, "could not evaluate shuffle index array length")
967 "simd_shuffle index must be an array of `u32`, got `{}`",
972 stripped.parse().unwrap_or_else(|_| {
973 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
977 require_simd!(ret_ty, "return");
978 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
981 "expected return type of length {}, found `{}` with length {}",
988 "expected return element type `{}` (element of input `{}`), \
989 found `{}` with element type `{}`",
996 let total_len = u128::from(in_len) * 2;
998 let vector = args[2].immediate();
1000 let indices: Option<Vec<_>> = (0..n)
1003 let val = bx.const_get_elt(vector, i as u64);
1004 match bx.const_to_opt_u128(val, true) {
1006 emit_error!("shuffle index #{} is not a constant", arg_idx);
1009 Some(idx) if idx >= total_len => {
1011 "shuffle index #{} is out of bounds (limit {})",
1017 Some(idx) => Some(bx.const_i32(idx as i32)),
1021 let Some(indices) = indices else {
1022 return Ok(bx.const_null(llret_ty));
1025 return Ok(bx.shuffle_vector(
1026 args[0].immediate(),
1027 args[1].immediate(),
1028 bx.const_vector(&indices),
1032 if name == sym::simd_insert {
1034 in_elem == arg_tys[2],
1035 "expected inserted type `{}` (element of input `{}`), found `{}`",
1040 return Ok(bx.insert_element(
1041 args[0].immediate(),
1042 args[2].immediate(),
1043 args[1].immediate(),
1046 if name == sym::simd_extract {
1049 "expected return type `{}` (element of input `{}`), found `{}`",
1054 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1057 if name == sym::simd_select {
1058 let m_elem_ty = in_elem;
1060 require_simd!(arg_tys[1], "argument");
1061 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1064 "mismatched lengths: mask length `{}` != other vector length `{}`",
1068 match m_elem_ty.kind() {
1070 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1072 // truncate the mask to a vector of i1s
1073 let i1 = bx.type_i1();
1074 let i1xn = bx.type_vector(i1, m_len as u64);
1075 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1076 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1079 if name == sym::simd_bitmask {
1080 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1081 // vector mask and returns the most significant bit (MSB) of each lane in the form
1083 // * an unsigned integer
1084 // * an array of `u8`
1085 // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
1087 // The bit order of the result depends on the byte endianness, LSB-first for little
1088 // endian and MSB-first for big endian.
1089 let expected_int_bits = in_len.max(8);
1090 let expected_bytes = expected_int_bits / 8 + ((expected_int_bits % 8 > 0) as u64);
1092 // Integer vector <i{in_bitwidth} x in_len>:
1093 let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
1095 args[0].immediate(),
1096 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1099 args[0].immediate(),
1100 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1103 "vector argument `{}`'s element type `{}`, expected integer element type",
1109 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1112 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1115 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1116 // Truncate vector to an <i1 x N>
1117 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1118 // Bitcast <i1 x N> to iN:
1119 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1121 match ret_ty.kind() {
1122 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
1123 // Zero-extend iN to the bitmask type:
1124 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1126 ty::Array(elem, len)
1127 if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1128 && len.try_eval_usize(bx.tcx, ty::ParamEnv::reveal_all())
1129 == Some(expected_bytes) =>
1131 // Zero-extend iN to the array length:
1132 let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
1134 // Convert the integer to a byte array
1135 let ptr = bx.alloca(bx.type_ix(expected_bytes * 8), Align::ONE);
1136 bx.store(ze, ptr, Align::ONE);
1137 let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
1138 let ptr = bx.pointercast(ptr, bx.cx.type_ptr_to(array_ty));
1139 return Ok(bx.load(array_ty, ptr, Align::ONE));
1142 "cannot return `{}`, expected `u{}` or `[u8; {}]`",
1150 fn simd_simple_float_intrinsic<'ll, 'tcx>(
1155 bx: &mut Builder<'_, 'll, 'tcx>,
1157 args: &[OperandRef<'tcx, &'ll Value>],
1158 ) -> Result<&'ll Value, ()> {
1159 #[allow(unused_macro_rules)]
1160 macro_rules! emit_error {
1164 ($msg: tt, $($fmt: tt)*) => {
1165 span_invalid_monomorphization_error(
1167 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1171 macro_rules! return_error {
1174 emit_error!($($fmt)*);
1180 let (elem_ty_str, elem_ty) = if let ty::Float(f) = in_elem.kind() {
1181 let elem_ty = bx.cx.type_float_from_ty(*f);
1182 match f.bit_width() {
1183 32 => ("f32", elem_ty),
1184 64 => ("f64", elem_ty),
1187 "unsupported element type `{}` of floating-point vector `{}`",
1194 return_error!("`{}` is not a floating-point type", in_ty);
1197 let vec_ty = bx.type_vector(elem_ty, in_len);
1199 let (intr_name, fn_ty) = match name {
1200 sym::simd_ceil => ("ceil", bx.type_func(&[vec_ty], vec_ty)),
1201 sym::simd_fabs => ("fabs", bx.type_func(&[vec_ty], vec_ty)),
1202 sym::simd_fcos => ("cos", bx.type_func(&[vec_ty], vec_ty)),
1203 sym::simd_fexp2 => ("exp2", bx.type_func(&[vec_ty], vec_ty)),
1204 sym::simd_fexp => ("exp", bx.type_func(&[vec_ty], vec_ty)),
1205 sym::simd_flog10 => ("log10", bx.type_func(&[vec_ty], vec_ty)),
1206 sym::simd_flog2 => ("log2", bx.type_func(&[vec_ty], vec_ty)),
1207 sym::simd_flog => ("log", bx.type_func(&[vec_ty], vec_ty)),
1208 sym::simd_floor => ("floor", bx.type_func(&[vec_ty], vec_ty)),
1209 sym::simd_fma => ("fma", bx.type_func(&[vec_ty, vec_ty, vec_ty], vec_ty)),
1210 sym::simd_fpowi => ("powi", bx.type_func(&[vec_ty, bx.type_i32()], vec_ty)),
1211 sym::simd_fpow => ("pow", bx.type_func(&[vec_ty, vec_ty], vec_ty)),
1212 sym::simd_fsin => ("sin", bx.type_func(&[vec_ty], vec_ty)),
1213 sym::simd_fsqrt => ("sqrt", bx.type_func(&[vec_ty], vec_ty)),
1214 sym::simd_round => ("round", bx.type_func(&[vec_ty], vec_ty)),
1215 sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
1216 _ => return_error!("unrecognized intrinsic `{}`", name),
1218 let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str);
1219 let f = bx.declare_cfn(llvm_name, llvm::UnnamedAddr::No, fn_ty);
1221 bx.call(fn_ty, f, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1244 return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1248 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1249 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1254 bx: &Builder<'_, '_, '_>,
1256 let p0s: String = "p0".repeat(no_pointers);
1257 match *elem_ty.kind() {
1258 ty::Int(v) => format!(
1262 // Normalize to prevent crash if v: IntTy::Isize
1263 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1265 ty::Uint(v) => format!(
1269 // Normalize to prevent crash if v: UIntTy::Usize
1270 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1272 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1273 _ => unreachable!(),
1277 fn llvm_vector_ty<'ll>(
1278 cx: &CodegenCx<'ll, '_>,
1281 mut no_pointers: usize,
1283 // FIXME: use cx.layout_of(ty).llvm_type() ?
1284 let mut elem_ty = match *elem_ty.kind() {
1285 ty::Int(v) => cx.type_int_from_ty(v),
1286 ty::Uint(v) => cx.type_uint_from_ty(v),
1287 ty::Float(v) => cx.type_float_from_ty(v),
1288 _ => unreachable!(),
1290 while no_pointers > 0 {
1291 elem_ty = cx.type_ptr_to(elem_ty);
1294 cx.type_vector(elem_ty, vec_len)
1297 if name == sym::simd_gather {
1298 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1299 // mask: <N x i{M}>) -> <N x T>
1300 // * N: number of elements in the input vectors
1301 // * T: type of the element to load
1302 // * M: any integer width is supported, will be truncated to i1
1304 // All types must be simd vector types
1305 require_simd!(in_ty, "first");
1306 require_simd!(arg_tys[1], "second");
1307 require_simd!(arg_tys[2], "third");
1308 require_simd!(ret_ty, "return");
1310 // Of the same length:
1311 let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1312 let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1315 "expected {} argument with length {} (same as input type `{}`), \
1316 found `{}` with length {}",
1325 "expected {} argument with length {} (same as input type `{}`), \
1326 found `{}` with length {}",
1334 // The return type must match the first argument type
1335 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1337 // This counts how many pointers
1338 fn ptr_count(t: Ty<'_>) -> usize {
1340 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1346 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1348 ty::RawPtr(p) => non_ptr(p.ty),
1353 // The second argument must be a simd vector with an element type that's a pointer
1354 // to the element type of the first argument
1355 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1356 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1357 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1358 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(element_ty1), non_ptr(element_ty1)),
1362 "expected element type `{}` of second argument `{}` \
1363 to be a pointer to the element type `{}` of the first \
1364 argument `{}`, found `{}` != `*_ {}`",
1375 assert!(pointer_count > 0);
1376 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1377 assert_eq!(underlying_ty, non_ptr(element_ty0));
1379 // The element type of the third argument must be a signed integer type of any width:
1380 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1381 match element_ty2.kind() {
1386 "expected element type `{}` of third argument `{}` \
1387 to be a signed integer type",
1394 // Alignment of T, must be a constant integer value:
1395 let alignment_ty = bx.type_i32();
1396 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1398 // Truncate the mask vector to a vector of i1s:
1399 let (mask, mask_ty) = {
1400 let i1 = bx.type_i1();
1401 let i1xn = bx.type_vector(i1, in_len);
1402 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1405 // Type of the vector of pointers:
1406 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1407 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1409 // Type of the vector of elements:
1410 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1411 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1413 let llvm_intrinsic =
1414 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1415 let fn_ty = bx.type_func(
1416 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1419 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1421 bx.call(fn_ty, f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1425 if name == sym::simd_scatter {
1426 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1427 // mask: <N x i{M}>) -> ()
1428 // * N: number of elements in the input vectors
1429 // * T: type of the element to load
1430 // * M: any integer width is supported, will be truncated to i1
1432 // All types must be simd vector types
1433 require_simd!(in_ty, "first");
1434 require_simd!(arg_tys[1], "second");
1435 require_simd!(arg_tys[2], "third");
1437 // Of the same length:
1438 let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1439 let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1441 in_len == element_len1,
1442 "expected {} argument with length {} (same as input type `{}`), \
1443 found `{}` with length {}",
1451 in_len == element_len2,
1452 "expected {} argument with length {} (same as input type `{}`), \
1453 found `{}` with length {}",
1461 // This counts how many pointers
1462 fn ptr_count(t: Ty<'_>) -> usize {
1464 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1470 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1472 ty::RawPtr(p) => non_ptr(p.ty),
1477 // The second argument must be a simd vector with an element type that's a pointer
1478 // to the element type of the first argument
1479 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1480 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1481 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1482 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1483 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1484 (ptr_count(element_ty1), non_ptr(element_ty1))
1489 "expected element type `{}` of second argument `{}` \
1490 to be a pointer to the element type `{}` of the first \
1491 argument `{}`, found `{}` != `*mut {}`",
1502 assert!(pointer_count > 0);
1503 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1504 assert_eq!(underlying_ty, non_ptr(element_ty0));
1506 // The element type of the third argument must be a signed integer type of any width:
1507 match element_ty2.kind() {
1512 "expected element type `{}` of third argument `{}` \
1513 be a signed integer type",
1520 // Alignment of T, must be a constant integer value:
1521 let alignment_ty = bx.type_i32();
1522 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1524 // Truncate the mask vector to a vector of i1s:
1525 let (mask, mask_ty) = {
1526 let i1 = bx.type_i1();
1527 let i1xn = bx.type_vector(i1, in_len);
1528 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1531 let ret_t = bx.type_void();
1533 // Type of the vector of pointers:
1534 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1535 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1537 // Type of the vector of elements:
1538 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1539 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1541 let llvm_intrinsic =
1542 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1544 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t);
1545 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1547 bx.call(fn_ty, f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1551 macro_rules! arith_red {
1552 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1553 $identity:expr) => {
1554 if name == sym::$name {
1557 "expected return type `{}` (element of input `{}`), found `{}`",
1562 return match in_elem.kind() {
1563 ty::Int(_) | ty::Uint(_) => {
1564 let r = bx.$integer_reduce(args[0].immediate());
1566 // if overflow occurs, the result is the
1567 // mathematical result modulo 2^n:
1568 Ok(bx.$op(args[1].immediate(), r))
1570 Ok(bx.$integer_reduce(args[0].immediate()))
1574 let acc = if $ordered {
1575 // ordered arithmetic reductions take an accumulator
1578 // unordered arithmetic reductions use the identity accumulator
1579 match f.bit_width() {
1580 32 => bx.const_real(bx.type_f32(), $identity),
1581 64 => bx.const_real(bx.type_f64(), $identity),
1584 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1593 Ok(bx.$float_reduce(acc, args[0].immediate()))
1596 "unsupported {} from `{}` with element `{}` to `{}`",
1607 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1608 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1610 simd_reduce_add_unordered: vector_reduce_add,
1611 vector_reduce_fadd_fast,
1617 simd_reduce_mul_unordered: vector_reduce_mul,
1618 vector_reduce_fmul_fast,
1624 macro_rules! minmax_red {
1625 ($name:ident: $int_red:ident, $float_red:ident) => {
1626 if name == sym::$name {
1629 "expected return type `{}` (element of input `{}`), found `{}`",
1634 return match in_elem.kind() {
1635 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1636 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1637 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1639 "unsupported {} from `{}` with element `{}` to `{}`",
1650 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1651 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1653 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1654 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1656 macro_rules! bitwise_red {
1657 ($name:ident : $red:ident, $boolean:expr) => {
1658 if name == sym::$name {
1659 let input = if !$boolean {
1662 "expected return type `{}` (element of input `{}`), found `{}`",
1669 match in_elem.kind() {
1670 ty::Int(_) | ty::Uint(_) => {}
1672 "unsupported {} from `{}` with element `{}` to `{}`",
1680 // boolean reductions operate on vectors of i1s:
1681 let i1 = bx.type_i1();
1682 let i1xn = bx.type_vector(i1, in_len as u64);
1683 bx.trunc(args[0].immediate(), i1xn)
1685 return match in_elem.kind() {
1686 ty::Int(_) | ty::Uint(_) => {
1687 let r = bx.$red(input);
1688 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1691 "unsupported {} from `{}` with element `{}` to `{}`",
1702 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
1703 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
1704 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
1705 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
1706 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
1708 if name == sym::simd_cast_ptr {
1709 require_simd!(ret_ty, "return");
1710 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1713 "expected return type with length {} (same as input type `{}`), \
1714 found `{}` with length {}",
1721 match in_elem.kind() {
1723 let (metadata, check_sized) = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
1724 bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty)
1726 assert!(!check_sized); // we are in codegen, so we shouldn't see these types
1727 require!(metadata.is_unit(), "cannot cast fat pointer `{}`", in_elem)
1729 _ => return_error!("expected pointer, got `{}`", in_elem),
1731 match out_elem.kind() {
1733 let (metadata, check_sized) = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
1734 bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty)
1736 assert!(!check_sized); // we are in codegen, so we shouldn't see these types
1737 require!(metadata.is_unit(), "cannot cast to fat pointer `{}`", out_elem)
1739 _ => return_error!("expected pointer, got `{}`", out_elem),
1742 if in_elem == out_elem {
1743 return Ok(args[0].immediate());
1745 return Ok(bx.pointercast(args[0].immediate(), llret_ty));
1749 if name == sym::simd_expose_addr {
1750 require_simd!(ret_ty, "return");
1751 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1754 "expected return type with length {} (same as input type `{}`), \
1755 found `{}` with length {}",
1762 match in_elem.kind() {
1764 _ => return_error!("expected pointer, got `{}`", in_elem),
1766 match out_elem.kind() {
1767 ty::Uint(ty::UintTy::Usize) => {}
1768 _ => return_error!("expected `usize`, got `{}`", out_elem),
1771 return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
1774 if name == sym::simd_from_exposed_addr {
1775 require_simd!(ret_ty, "return");
1776 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1779 "expected return type with length {} (same as input type `{}`), \
1780 found `{}` with length {}",
1787 match in_elem.kind() {
1788 ty::Uint(ty::UintTy::Usize) => {}
1789 _ => return_error!("expected `usize`, got `{}`", in_elem),
1791 match out_elem.kind() {
1793 _ => return_error!("expected pointer, got `{}`", out_elem),
1796 return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
1799 if name == sym::simd_cast || name == sym::simd_as {
1800 require_simd!(ret_ty, "return");
1801 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1804 "expected return type with length {} (same as input type `{}`), \
1805 found `{}` with length {}",
1811 // casting cares about nominal type, not just structural type
1812 if in_elem == out_elem {
1813 return Ok(args[0].immediate());
1818 Int(/* is signed? */ bool),
1822 let (in_style, in_width) = match in_elem.kind() {
1823 // vectors of pointer-sized integers should've been
1824 // disallowed before here, so this unwrap is safe.
1827 i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1831 u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1833 ty::Float(f) => (Style::Float, f.bit_width()),
1834 _ => (Style::Unsupported, 0),
1836 let (out_style, out_width) = match out_elem.kind() {
1839 i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1843 u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1845 ty::Float(f) => (Style::Float, f.bit_width()),
1846 _ => (Style::Unsupported, 0),
1849 match (in_style, out_style) {
1850 (Style::Int(in_is_signed), Style::Int(_)) => {
1851 return Ok(match in_width.cmp(&out_width) {
1852 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1853 Ordering::Equal => args[0].immediate(),
1856 bx.sext(args[0].immediate(), llret_ty)
1858 bx.zext(args[0].immediate(), llret_ty)
1863 (Style::Int(in_is_signed), Style::Float) => {
1864 return Ok(if in_is_signed {
1865 bx.sitofp(args[0].immediate(), llret_ty)
1867 bx.uitofp(args[0].immediate(), llret_ty)
1870 (Style::Float, Style::Int(out_is_signed)) => {
1871 return Ok(match (out_is_signed, name == sym::simd_as) {
1872 (false, false) => bx.fptoui(args[0].immediate(), llret_ty),
1873 (true, false) => bx.fptosi(args[0].immediate(), llret_ty),
1874 (_, true) => bx.cast_float_to_int(out_is_signed, args[0].immediate(), llret_ty),
1877 (Style::Float, Style::Float) => {
1878 return Ok(match in_width.cmp(&out_width) {
1879 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1880 Ordering::Equal => args[0].immediate(),
1881 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1884 _ => { /* Unsupported. Fallthrough. */ }
1888 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1895 macro_rules! arith_binary {
1896 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1897 $(if name == sym::$name {
1898 match in_elem.kind() {
1899 $($(ty::$p(_))|* => {
1900 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1905 "unsupported operation on `{}` with element `{}`",
1912 simd_add: Uint, Int => add, Float => fadd;
1913 simd_sub: Uint, Int => sub, Float => fsub;
1914 simd_mul: Uint, Int => mul, Float => fmul;
1915 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1916 simd_rem: Uint => urem, Int => srem, Float => frem;
1917 simd_shl: Uint, Int => shl;
1918 simd_shr: Uint => lshr, Int => ashr;
1919 simd_and: Uint, Int => and;
1920 simd_or: Uint, Int => or;
1921 simd_xor: Uint, Int => xor;
1922 simd_fmax: Float => maxnum;
1923 simd_fmin: Float => minnum;
1926 macro_rules! arith_unary {
1927 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1928 $(if name == sym::$name {
1929 match in_elem.kind() {
1930 $($(ty::$p(_))|* => {
1931 return Ok(bx.$call(args[0].immediate()))
1936 "unsupported operation on `{}` with element `{}`",
1943 simd_neg: Int => neg, Float => fneg;
1946 if name == sym::simd_arith_offset {
1947 // This also checks that the first operand is a ptr type.
1948 let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
1949 span_bug!(span, "must be called with a vector of pointer types as first argument")
1951 let layout = bx.layout_of(pointee.ty);
1952 let ptrs = args[0].immediate();
1953 // The second argument must be a ptr-sized integer.
1954 // (We don't care about the signedness, this is wrapping anyway.)
1955 let (_offsets_len, offsets_elem) = arg_tys[1].simd_size_and_type(bx.tcx());
1956 if !matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
1959 "must be called with a vector of pointer-sized integers as second argument"
1962 let offsets = args[1].immediate();
1964 return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
1967 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
1968 let lhs = args[0].immediate();
1969 let rhs = args[1].immediate();
1970 let is_add = name == sym::simd_saturating_add;
1971 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1972 let (signed, elem_width, elem_ty) = match *in_elem.kind() {
1973 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
1974 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
1977 "expected element type `{}` of vector type `{}` \
1978 to be a signed or unsigned integer type",
1979 arg_tys[0].simd_size_and_type(bx.tcx()).1,
1984 let llvm_intrinsic = &format!(
1985 "llvm.{}{}.sat.v{}i{}",
1986 if signed { 's' } else { 'u' },
1987 if is_add { "add" } else { "sub" },
1991 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1993 let fn_ty = bx.type_func(&[vec_ty, vec_ty], vec_ty);
1994 let f = bx.declare_cfn(llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1995 let v = bx.call(fn_ty, f, &[lhs, rhs], None);
1999 span_bug!(span, "unknown SIMD intrinsic");
2002 // Returns the width of an int Ty, and if it's signed or not
2003 // Returns None if the type is not an integer
2004 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2006 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2009 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), true))
2012 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), false))