Skip to main content

rustc_codegen_llvm/
intrinsic.rs

1use std::cmp::Ordering;
2use std::ffi::c_uint;
3use std::{assert_matches, iter, ptr};
4
5use rustc_abi::{
6    AddressSpace, Align, BackendRepr, CVariadicStatus, Float, HasDataLayout, NumScalableVectors,
7    Primitive, Size,
8};
9use rustc_attr_ir::find_attr;
10use rustc_codegen_ssa::RetagInfo;
11use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
12use rustc_codegen_ssa::common::IntPredicate;
13use rustc_codegen_ssa::diagnostics::{ExpectedPointerMutability, InvalidMonomorphization};
14use rustc_codegen_ssa::mir::IntrinsicResult;
15use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
16use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
17use rustc_codegen_ssa::traits::*;
18use rustc_hir as hir;
19use rustc_hir::def_id::LOCAL_CRATE;
20use rustc_lint_defs::builtin::DEPRECATED_LLVM_INTRINSIC;
21use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAlloc, alloc_range};
22use rustc_middle::mir::{self, BinOp};
23use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf};
24use rustc_middle::ty::offload_meta::OffloadMetadata;
25use rustc_middle::ty::{self, GenericArgs, Instance, SimdAlign, Ty, TyCtxt};
26use rustc_session::diagnostics::feature_err;
27use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug, sym};
28use rustc_structures::CrateType;
29use rustc_symbol_mangling::{
30    mangle_internal_symbol, mangle_offload_export, symbol_name_for_instance_in_crate,
31};
32use rustc_target::callconv::PassMode;
33use rustc_target::spec::Arch;
34use tracing::debug;
35
36use crate::abi::FnAbiLlvmExt;
37use crate::builder::Builder;
38use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
39use crate::builder::gpu_offload::{self, OffloadKernelDims, declare_omp_get_num_devices};
40use crate::context::CodegenCx;
41use crate::declare::declare_raw_fn;
42use crate::diagnostics::{
43    AutoDiffWithoutEnable, AutoDiffWithoutLto, IntrinsicSignatureMismatch, IntrinsicWrongArch,
44    OffloadWithoutEnable, OffloadWithoutFatLTO, UnknownIntrinsic,
45};
46use crate::intrinsic::ty::typetree::fnc_typetrees;
47use crate::llvm::{self, Attribute, AttributePlace, Metadata, Type, TypeKind, Value};
48use crate::type_of::LayoutLlvmExt;
49use crate::va_arg::emit_va_arg;
50
51fn call_simple_intrinsic<'ll, 'tcx>(
52    bx: &mut Builder<'_, 'll, 'tcx>,
53    name: Symbol,
54    args: &[OperandRef<'tcx, Value<'ll>>],
55) -> Option<Value<'ll>> {
56    let llvm_version = crate::llvm_util::get_version();
57    // minimum/maximum were broken for f64/f128 before
58    // <https://github.com/llvm/llvm-project/commit/56385af687c3a7a1f67716fb3f819336789a8cab>.
59    // We use the fallback body there.
60    let fixed_minmax = llvm_version >= (23, 0, 0);
61
62    let (base_name, type_params): (&'static str, &[Type<'ll>]) = match name {
63        sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]),
64        sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]),
65        sym::minimumf64 if fixed_minmax => ("llvm.minimum", &[bx.type_f64()]),
66        sym::minimumf128 if fixed_minmax => ("llvm.minimum", &[bx.type_f128()]),
67
68        sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]),
69        sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]),
70        sym::maximumf64 if fixed_minmax => ("llvm.maximum", &[bx.type_f64()]),
71        sym::maximumf128 if fixed_minmax => ("llvm.maximum", &[bx.type_f128()]),
72
73        sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]),
74        sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]),
75        sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]),
76        sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]),
77
78        _ => return None,
79    };
80    Some(bx.call_intrinsic(
81        base_name,
82        type_params,
83        &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
84    ))
85}
86
87impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> {
88    fn black_box(&mut self, result: PlaceRef<'tcx, Value<'ll>>, span: Span) {
89        let result_val_span = [result.val.llval];
90        // We need to "use" the argument in some way LLVM can't introspect, and on
91        // targets that support it we can typically leverage inline assembly to do
92        // this. LLVM's interpretation of inline assembly is that it's, well, a black
93        // box. This isn't the greatest implementation since it probably deoptimizes
94        // more than we want, but it's so far good enough.
95        //
96        // For zero-sized types, the location pointed to by the result may be
97        // uninitialized. Do not "use" the result in this case; instead just clobber
98        // the memory.
99        let (constraint, inputs): (&str, &[_]) = if result.layout.is_zst() {
100            ("~{memory}", &[])
101        } else {
102            ("r,~{memory}", &result_val_span)
103        };
104        crate::asm::inline_asm_call(
105            self,
106            "",
107            constraint,
108            inputs,
109            self.type_void(),
110            &[],
111            true,
112            false,
113            llvm::AsmDialect::Att,
114            &[span],
115            false,
116            None,
117            None,
118        )
119        .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("failed to generate inline asm call for `black_box`"),
    Location::caller())bug!("failed to generate inline asm call for `black_box`"));
120    }
121}
122
123impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
124    fn codegen_intrinsic_call(
125        &mut self,
126        instance: ty::Instance<'tcx>,
127        args: &[OperandRef<'tcx, Value<'ll>>],
128        result_layout: ty::layout::TyAndLayout<'tcx>,
129        result_place: Option<PlaceValue<Value<'ll>>>,
130        span: Span,
131    ) -> IntrinsicResult<'tcx, Value<'ll>> {
132        let tcx = self.tcx;
133        let llvm_version = crate::llvm_util::get_version();
134
135        let name = tcx.item_name(instance.def_id());
136        let fn_args = instance.args;
137
138        let simple = call_simple_intrinsic(self, name, args);
139        let llval = match name {
140            _ if simple.is_some() => simple.unwrap(),
141            sym::minimum_number_nsz_f16
142            | sym::minimum_number_nsz_f32
143            | sym::minimum_number_nsz_f64
144            | sym::minimum_number_nsz_f128
145            | sym::maximum_number_nsz_f16
146            | sym::maximum_number_nsz_f32
147            | sym::maximum_number_nsz_f64
148            | sym::maximum_number_nsz_f128 => {
149                let intrinsic_name = if name.as_str().starts_with("min") {
150                    "llvm.minimumnum"
151                } else {
152                    "llvm.maximumnum"
153                };
154                let call = self.call_intrinsic(
155                    intrinsic_name,
156                    &[args[0].layout.immediate_llvm_type(self.cx)],
157                    &[args[0].immediate(), args[1].immediate()],
158                );
159                // `nsz` on minimumnum/maximumnum is special: its only effect is to make
160                // signed-zero ordering non-deterministic.
161                unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
162                call
163            }
164            sym::ptr_mask => {
165                let ptr = args[0].immediate();
166                self.call_intrinsic(
167                    "llvm.ptrmask",
168                    &[self.val_ty(ptr), self.type_isize()],
169                    &[ptr, args[1].immediate()],
170                )
171            }
172            sym::autodiff => {
173                return codegen_autodiff(self, instance, args, result_layout, result_place);
174            }
175            sym::offload => {
176                if tcx.sess.opts.unstable_opts.offload.is_empty() {
177                    let _ = tcx.dcx().emit_err(OffloadWithoutEnable);
178                }
179
180                if tcx.sess.lto() != rustc_session::config::Lto::Fat {
181                    let _ = tcx.dcx().emit_err(OffloadWithoutFatLTO);
182                }
183
184                codegen_offload(self, tcx, instance, args);
185                // offload *has* a return type, but somehow works without mentioning the place
186                return IntrinsicResult::WroteIntoPlace;
187            }
188            sym::offload_get_num_devices => {
189                let (fn_decl, fn_ty) = declare_omp_get_num_devices(self.cx);
190
191                let llval =
192                    self.call(fn_ty, None, None, fn_decl, ReturnSlot::Direct, &[], None, None);
193
194                return IntrinsicResult::Operand(OperandValue::Immediate(llval));
195            }
196            sym::is_val_statically_known => {
197                if let OperandValue::Immediate(imm) = args[0].val {
198                    self.call_intrinsic(
199                        "llvm.is.constant",
200                        &[args[0].layout.immediate_llvm_type(self.cx)],
201                        &[imm],
202                    )
203                } else {
204                    self.const_bool(false)
205                }
206            }
207            sym::select_unpredictable => {
208                let cond = args[0].immediate();
209                {
    match (&args[1].layout, &args[2].layout) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(args[1].layout, args[2].layout);
210                let select = |bx: &mut Self, true_val, false_val| {
211                    let result = bx.select(cond, true_val, false_val);
212                    bx.set_unpredictable(result);
213                    result
214                };
215                match (args[1].val, args[2].val) {
216                    (OperandValue::Ref(true_val), OperandValue::Ref(false_val)) => {
217                        if !true_val.llextra.is_none() {
    ::core::panicking::panic("assertion failed: true_val.llextra.is_none()")
};assert!(true_val.llextra.is_none());
218                        if !false_val.llextra.is_none() {
    ::core::panicking::panic("assertion failed: false_val.llextra.is_none()")
};assert!(false_val.llextra.is_none());
219                        {
    match (&true_val.align, &false_val.align) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(true_val.align, false_val.align);
220                        let ptr = select(self, true_val.llval, false_val.llval);
221                        let selected =
222                            OperandValue::Ref(PlaceValue::new_sized(ptr, true_val.align));
223                        let result = PlaceRef { val: result_place.unwrap(), layout: result_layout };
224                        selected.store(self, result);
225                        return IntrinsicResult::WroteIntoPlace;
226                    }
227                    (OperandValue::Immediate(_), OperandValue::Immediate(_))
228                    | (OperandValue::Pair(_, _), OperandValue::Pair(_, _)) => {
229                        let true_val = args[1].immediate_or_packed_pair(self);
230                        let false_val = args[2].immediate_or_packed_pair(self);
231                        select(self, true_val, false_val)
232                    }
233                    (OperandValue::ZeroSized, OperandValue::ZeroSized) => {
234                        return IntrinsicResult::Operand(OperandValue::ZeroSized);
235                    }
236                    _ => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("Incompatible OperandValue for select_unpredictable"),
    Location::caller())span_bug!(span, "Incompatible OperandValue for select_unpredictable"),
237                }
238            }
239            sym::catch_unwind => catch_unwind_intrinsic(
240                self,
241                args[0].immediate(),
242                args[1].immediate(),
243                args[2].immediate(),
244            ),
245            sym::breakpoint | sym::resumable_breakpoint => {
246                self.call_intrinsic("llvm.debugtrap", &[], &[])
247            }
248            sym::va_arg => {
249                let target = &self.cx.tcx.sess.target;
250                let stability = target.supports_c_variadic_definitions();
251                if let CVariadicStatus::Unstable { feature } = stability
252                    && !self.tcx.features().enabled(feature)
253                {
254                    let msg = "C-variadic function definitions on this target are unstable";
255                    feature_err(self.sess(), feature, span, msg).emit();
256                }
257
258                let BackendRepr::Scalar(scalar) = result_layout.backend_repr else {
259                    ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support non-scalar types"),
    Location::caller())bug!("the va_arg intrinsic does not support non-scalar types")
260                };
261
262                // We reject types that would never be passed as varargs in C because
263                // they get promoted to a larger type, specifically integers smaller than
264                // c_int and float type smaller than c_double.
265                match scalar.primitive() {
266                    Primitive::Pointer(_) => {
267                        // Pointers are always OK.
268                    }
269                    Primitive::Int(..) => {
270                        let int_width = self.cx().size_of(result_layout.ty).bits();
271                        let target_c_int_width = self.cx().sess().target.options.c_int_width;
272                        if int_width < u64::from(target_c_int_width) {
273                            // Smaller integer types are automatically promototed and `va_arg`
274                            // should not be called on them.
275                            ::rustc_span::macros::bug_impl(None,
    format_args!("va_arg got i{0} but needs at least c_int (an i{1})",
        int_width, target_c_int_width), Location::caller());bug!(
276                                "va_arg got i{} but needs at least c_int (an i{})",
277                                int_width,
278                                target_c_int_width
279                            );
280                        }
281                    }
282                    Primitive::Float(Float::F16) => {
283                        ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support `f16`"),
    Location::caller())bug!("the va_arg intrinsic does not support `f16`")
284                    }
285                    Primitive::Float(Float::F16B) => {
286                        ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support `f16b`"),
    Location::caller())bug!("the va_arg intrinsic does not support `f16b`")
287                    }
288                    Primitive::Float(Float::F32) => {
289                        // c_double is actually f32 on avr.
290                        if self.cx().sess().target.arch != Arch::Avr {
291                            ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support `f32` on this target"),
    Location::caller())bug!("the va_arg intrinsic does not support `f32` on this target")
292                        }
293                    }
294                    Primitive::Float(Float::F64) => {
295                        // 64-bit floats are always OK.
296                    }
297                    Primitive::Float(Float::F128) => {
298                        // Supported on some targets, especially where long double is IEEE f128.
299                    }
300                    Primitive::Float(Float::PpcF128) => {
301                        // Supported on powerpc and powerpc64 targets.
302                    }
303                    Primitive::Float(Float::X87F80) => {
304                        // FIXME(x87_f80) we should support this.
305                        ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not currently support `x87_f80`"),
    Location::caller())bug!("the va_arg intrinsic does not currently support `x87_f80`")
306                    }
307                }
308
309                emit_va_arg(self, args[0], result_layout)
310            }
311
312            sym::volatile_load | sym::unaligned_volatile_load => {
313                // Note that we cannot just load the `llvm_type` because we should never load non-scalars.
314                // Trying to do so blows up horribly in some cases -- for example loading a
315                // `MaybeUninint<&dyn Trait>` would load as `{ [i64x2] }` which gives assertions later
316                // (if we're lucky) from things not being pointers that ought to be.
317                let ptr = args[0].immediate();
318                let abi_align = result_layout.align;
319                let ptr_align = if name == sym::volatile_load { abi_align } else { Align::ONE };
320                let need_black_box = llvm_version < (23, 0, 0);
321                if result_layout.is_zst() {
322                    return IntrinsicResult::Operand(OperandValue::ZeroSized);
323                } else if let BackendRepr::Scalar(scalar) = result_layout.backend_repr
324                    && !need_black_box
325                {
326                    let load = self.volatile_load(self.type_from_scalar(scalar), ptr, ptr_align);
327                    self.to_immediate_scalar(load, scalar)
328                } else {
329                    // One day Rust will probably want to define how we split up a volatile load
330                    // of something that's *not* just an ordinary scalar, but for now we can just
331                    // use an LLVM integer type of the correct width and let it split it however.
332                    let llty = self.type_ix(result_layout.size.bits());
333                    let temp = if let Some(result_place) = result_place {
334                        PlaceRef { val: result_place, layout: result_layout }
335                    } else {
336                        PlaceRef::alloca(self, result_layout)
337                    };
338                    let llval = self.volatile_load(llty, ptr, ptr_align);
339                    self.store(llval, temp.val.llval, abi_align);
340                    if need_black_box {
341                        // LLVM up until v22 considers volatile reads `willreturn` and hence can
342                        // move UB from further down up across this read. To prevent that, insert an
343                        // inline asm block that, as far as LLVM is concerned, might not terminate,
344                        // and hence should prevent such reordering.
345                        self.black_box(temp, span);
346                    }
347                    return if result_place.is_none() {
348                        IntrinsicResult::Operand(self.load_operand(temp).val)
349                    } else {
350                        IntrinsicResult::WroteIntoPlace
351                    };
352                }
353            }
354            sym::prefetch_read_data
355            | sym::prefetch_write_data
356            | sym::prefetch_read_instruction
357            | sym::prefetch_write_instruction => {
358                let (rw, cache_type) = match name {
359                    sym::prefetch_read_data => (0, 1),
360                    sym::prefetch_write_data => (1, 1),
361                    sym::prefetch_read_instruction => (0, 0),
362                    sym::prefetch_write_instruction => (1, 0),
363                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
364                };
365                let ptr = args[0].immediate();
366                let locality = fn_args.const_at(1).to_leaf().to_i32();
367                self.call_intrinsic(
368                    "llvm.prefetch.p0",
369                    &[self.val_ty(ptr)],
370                    &[
371                        ptr,
372                        self.const_i32(rw),
373                        self.const_i32(locality),
374                        self.const_i32(cache_type),
375                    ],
376                );
377                return IntrinsicResult::Operand(OperandValue::ZeroSized);
378            }
379            sym::carrying_mul_add => {
380                let (size, signed) = fn_args.type_at(0).int_size_and_signed(self.tcx);
381
382                let wide_llty = self.type_ix(size.bits() * 2);
383                let args = args.as_array().unwrap();
384                let [a, b, c, d] = args.map(|a| self.intcast(a.immediate(), wide_llty, signed));
385
386                let wide = if signed {
387                    let prod = self.unchecked_smul(a, b);
388                    let acc = self.unchecked_sadd(prod, c);
389                    self.unchecked_sadd(acc, d)
390                } else {
391                    let prod = self.unchecked_umul(a, b);
392                    let acc = self.unchecked_uadd(prod, c);
393                    self.unchecked_uadd(acc, d)
394                };
395
396                let narrow_llty = self.type_ix(size.bits());
397                let low = self.trunc(wide, narrow_llty);
398                let bits_const = self.const_uint(wide_llty, size.bits());
399                // No need for ashr when signed; LLVM changes it to lshr anyway.
400                let high = self.lshr(wide, bits_const);
401                // FIXME: could be `trunc nuw`, even for signed.
402                let high = self.trunc(high, narrow_llty);
403
404                let pair_llty = self.type_struct(&[narrow_llty, narrow_llty]);
405                let pair = self.const_poison(pair_llty);
406                let pair = self.insert_value(pair, low, 0);
407                let pair = self.insert_value(pair, high, 1);
408                pair
409            }
410
411            sym::ctlz
412            | sym::ctlz_nonzero
413            | sym::cttz
414            | sym::cttz_nonzero
415            | sym::ctpop
416            | sym::bswap
417            | sym::bitreverse
418            | sym::carryless_mul
419            | sym::integer_max
420            | sym::integer_min
421            | sym::saturating_add
422            | sym::saturating_sub
423            | sym::unchecked_funnel_shl
424            | sym::unchecked_funnel_shr => {
425                let ty = args[0].layout.ty;
426                if !ty.is_integral() {
427                    let err = tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
428                        span,
429                        name,
430                        ty,
431                    });
432                    return IntrinsicResult::Err(err);
433                }
434                let (size, signed) = ty.int_size_and_signed(self.tcx);
435                let width = size.bits();
436                let llty = self.type_ix(width);
437                match name {
438                    sym::ctlz | sym::ctlz_nonzero | sym::cttz | sym::cttz_nonzero => {
439                        let y =
440                            self.const_bool(name == sym::ctlz_nonzero || name == sym::cttz_nonzero);
441                        let llvm_name = if name == sym::ctlz || name == sym::ctlz_nonzero {
442                            "llvm.ctlz"
443                        } else {
444                            "llvm.cttz"
445                        };
446                        let ret =
447                            self.call_intrinsic(llvm_name, &[llty], &[args[0].immediate(), y]);
448                        self.intcast(ret, result_layout.llvm_type(self), false)
449                    }
450                    sym::ctpop => self.ctpop(args[0].immediate()),
451                    sym::bswap => {
452                        if width == 8 {
453                            args[0].immediate() // byte swap a u8/i8 is just a no-op
454                        } else {
455                            self.call_intrinsic("llvm.bswap", &[llty], &[args[0].immediate()])
456                        }
457                    }
458                    sym::bitreverse => {
459                        self.call_intrinsic("llvm.bitreverse", &[llty], &[args[0].immediate()])
460                    }
461                    sym::carryless_mul => {
462                        let lhs = args[0].immediate();
463                        let rhs = args[1].immediate();
464                        self.call_intrinsic("llvm.clmul", &[llty], &[lhs, rhs])
465                    }
466                    sym::integer_min | sym::integer_max => {
467                        let lhs = args[0].immediate();
468                        let rhs = args[1].immediate();
469                        let llvm_name = match (name, signed) {
470                            (sym::integer_max, false) => "llvm.umax",
471                            (sym::integer_max, true) => "llvm.smax",
472                            (sym::integer_min, false) => "llvm.umin",
473                            (sym::integer_min, true) => "llvm.smin",
474                            _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
475                        };
476                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
477                    }
478                    sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
479                        let is_left = name == sym::unchecked_funnel_shl;
480                        let lhs = args[0].immediate();
481                        let rhs = args[1].immediate();
482                        let raw_shift = args[2].immediate();
483                        let llvm_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.fsh{0}",
                if is_left { 'l' } else { 'r' }))
    })format!("llvm.fsh{}", if is_left { 'l' } else { 'r' });
484
485                        // llvm expects shift to be the same type as the values, but rust
486                        // always uses `u32`.
487                        let raw_shift = self.intcast(raw_shift, self.val_ty(lhs), false);
488
489                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs, raw_shift])
490                    }
491                    sym::saturating_add | sym::saturating_sub => {
492                        let is_add = name == sym::saturating_add;
493                        let lhs = args[0].immediate();
494                        let rhs = args[1].immediate();
495                        let llvm_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.sat",
                if signed { 's' } else { 'u' },
                if is_add { "add" } else { "sub" }))
    })format!(
496                            "llvm.{}{}.sat",
497                            if signed { 's' } else { 'u' },
498                            if is_add { "add" } else { "sub" },
499                        );
500                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
501                    }
502                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
503                }
504            }
505
506            sym::fabs
507            | sym::sqrt
508            | sym::powf
509            | sym::fma
510            | sym::fmuladd
511            | sym::floor
512            | sym::ceil
513            | sym::trunc
514            | sym::round
515            | sym::round_ties_even
516            | sym::exp
517            | sym::exp2
518            | sym::log
519            | sym::log10
520            | sym::log2
521            | sym::sin
522            | sym::cos
523            | sym::powi => {
524                let ty = args[0].layout.ty;
525                let ty::Float(f) = ty.kind() else {
526                    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("the `{0}` intrinsic requires a floating-point argument, got {1:?}",
        name, ty), Location::caller());span_bug!(
527                        span,
528                        "the `{}` intrinsic requires a floating-point argument, got {:?}",
529                        name,
530                        ty
531                    );
532                };
533                let llty = self.type_float_from_ty(*f);
534                let llvm_name = match name {
535                    sym::fabs => "llvm.fabs",
536                    sym::sqrt => "llvm.sqrt",
537                    sym::powf => "llvm.pow",
538                    sym::fma => "llvm.fma",
539                    sym::fmuladd => "llvm.fmuladd",
540                    sym::floor => "llvm.floor",
541                    sym::ceil => "llvm.ceil",
542                    sym::trunc => "llvm.trunc",
543                    sym::round => "llvm.round",
544                    // We could use any of `rint`, `nearbyint`, or `roundeven`
545                    // for this -- they are all identical in semantics when
546                    // assuming the default FP environment.
547                    // `rint` is what we used for $forever.
548                    sym::round_ties_even => "llvm.rint",
549                    sym::exp => "llvm.exp",
550                    sym::exp2 => "llvm.exp2",
551                    sym::log => "llvm.log",
552                    sym::log10 => "llvm.log10",
553                    sym::log2 => "llvm.log2",
554                    sym::sin => "llvm.sin",
555                    sym::cos => "llvm.cos",
556                    sym::powi => "llvm.powi",
557
558                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
559                };
560
561                let params: &[Type<'ll>] = match name {
562                    sym::powi => &[llty, self.type_i32()],
563                    _ => &[llty],
564                };
565
566                self.call_intrinsic(
567                    llvm_name,
568                    params,
569                    &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
570                )
571            }
572
573            sym::raw_eq => {
574                use BackendRepr::*;
575                let tp_ty = fn_args.type_at(0);
576                let layout = self.layout_of(tp_ty).layout;
577                let use_integer_compare = match layout.backend_repr() {
578                    Scalar(_) | ScalarPair { a: _, b: _, b_offset: _ } => true,
579                    SimdVector { .. } => false,
580                    SimdScalableVector { .. } => {
581                        let err = tcx.dcx().emit_err(InvalidMonomorphization::NonScalableType {
582                            span,
583                            name: sym::raw_eq,
584                            ty: tp_ty,
585                        });
586                        return IntrinsicResult::Err(err);
587                    }
588                    Memory { .. } => {
589                        // For rusty ABIs, small aggregates are actually passed
590                        // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
591                        // so we re-use that same threshold here.
592                        layout.size() <= self.data_layout().pointer_size() * 2
593                    }
594                };
595
596                let a = args[0].immediate();
597                let b = args[1].immediate();
598                if layout.size().bytes() == 0 {
599                    self.const_bool(true)
600                } else if use_integer_compare {
601                    let integer_ty = self.type_ix(layout.size().bits());
602                    let a_val = self.load(integer_ty, a, layout.align());
603                    let b_val = self.load(integer_ty, b, layout.align());
604                    self.icmp(IntPredicate::IntEQ, a_val, b_val)
605                } else {
606                    let n = self.const_usize(layout.size().bytes());
607                    let cmp = self.call_intrinsic("memcmp", &[], &[a, b, n]);
608                    self.icmp(IntPredicate::IntEQ, cmp, self.const_int(self.type_int(), 0))
609                }
610            }
611
612            sym::compare_bytes => {
613                // Here we assume that the `memcmp` provided by the target is a NOP for size 0.
614                let cmp = self.call_intrinsic(
615                    "memcmp",
616                    &[],
617                    &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
618                );
619                // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`.
620                self.sext(cmp, self.type_ix(32))
621            }
622
623            sym::black_box => {
624                // This `unwrap` is justified by `intrinsic_call_expects_place_always` declaring
625                // this intrinsic as always needing a return place.
626                let result = PlaceRef { val: result_place.unwrap(), layout: result_layout };
627                args[0].val.store(self, result);
628                self.black_box(result, span);
629
630                // We have copied the value to `result` already.
631                return IntrinsicResult::WroteIntoPlace;
632            }
633
634            sym::gpu_launch_sized_workgroup_mem => {
635                // Generate an anonymous global per call, with these properties:
636                // 1. The global is in the address space for workgroup memory
637                // 2. It is an `external` global
638                // 3. It is correctly aligned for the pointee `T`
639                // All instances of extern addrspace(gpu_workgroup) globals are merged in the LLVM backend.
640                // The name is irrelevant.
641                // See https://docs.nvidia.com/cuda/cuda-c-programming-guide/#shared
642                let name = if llvm_version < (23, 0, 0) && tcx.sess.target.arch == Arch::Nvptx64 {
643                    // The auto-assigned name for extern shared globals in the nvptx backend does
644                    // not compile in ptxas. Workaround this issue by assigning a name.
645                    // Fixed in LLVM 23.
646                    "gpu_launch_sized_workgroup_mem"
647                } else {
648                    ""
649                };
650                let global = self.declare_global_in_addrspace(
651                    name,
652                    self.type_array(self.type_i8(), 0),
653                    AddressSpace::GPU_WORKGROUP,
654                );
655                let ty::RawPtr(inner_ty, _) = result_layout.ty.kind() else { ::core::panicking::unreachable_default_msg()unreachable!() };
656                // The alignment of the global is used to specify the *minimum* alignment that
657                // must be obeyed by the GPU runtime.
658                // When multiple of these global variables are used by a kernel, the maximum alignment is taken.
659                // See https://github.com/llvm/llvm-project/blob/a271d07488a85ce677674bbe8101b10efff58c95/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp#L821
660                let alignment = self.align_of(*inner_ty).bytes() as u32;
661                unsafe {
662                    // FIXME Workaround the above issue by taking maximum alignment if the global existed
663                    if tcx.sess.target.arch == Arch::Nvptx64 {
664                        if alignment > llvm::LLVMGetAlignment(global) {
665                            llvm::LLVMSetAlignment(global, alignment);
666                        }
667                    } else {
668                        llvm::LLVMSetAlignment(global, alignment);
669                    }
670                }
671                self.cx().const_pointercast(global, self.type_ptr())
672            }
673
674            sym::amdgpu_dispatch_ptr => {
675                let val = self.call_intrinsic("llvm.amdgcn.dispatch.ptr", &[], &[]);
676                // Relying on `LLVMBuildPointerCast` to produce an addrspacecast
677                self.pointercast(val, self.type_ptr())
678            }
679
680            sym::sve_tuple_create2 => {
681                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
682                    self.layout_of(fn_args.type_at(0)).backend_repr,
683                    BackendRepr::SimdScalableVector {
684                        number_of_vectors: NumScalableVectors(1),
685                        ..
686                    }
687                );
688                let tuple_ty = self.layout_of(fn_args.type_at(1));
689                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
690                    tuple_ty.backend_repr,
691                    BackendRepr::SimdScalableVector {
692                        number_of_vectors: NumScalableVectors(2),
693                        ..
694                    }
695                );
696                let ret = self.const_poison(self.backend_type(tuple_ty));
697                let ret = self.insert_value(ret, args[0].immediate(), 0);
698                self.insert_value(ret, args[1].immediate(), 1)
699            }
700
701            sym::sve_tuple_create3 => {
702                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
703                    self.layout_of(fn_args.type_at(0)).backend_repr,
704                    BackendRepr::SimdScalableVector {
705                        number_of_vectors: NumScalableVectors(1),
706                        ..
707                    }
708                );
709                let tuple_ty = self.layout_of(fn_args.type_at(1));
710                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(3), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(3), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
711                    tuple_ty.backend_repr,
712                    BackendRepr::SimdScalableVector {
713                        number_of_vectors: NumScalableVectors(3),
714                        ..
715                    }
716                );
717                let ret = self.const_poison(self.backend_type(tuple_ty));
718                let ret = self.insert_value(ret, args[0].immediate(), 0);
719                let ret = self.insert_value(ret, args[1].immediate(), 1);
720                self.insert_value(ret, args[2].immediate(), 2)
721            }
722
723            sym::sve_tuple_create4 => {
724                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
725                    self.layout_of(fn_args.type_at(0)).backend_repr,
726                    BackendRepr::SimdScalableVector {
727                        number_of_vectors: NumScalableVectors(1),
728                        ..
729                    }
730                );
731                let tuple_ty = self.layout_of(fn_args.type_at(1));
732                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(4), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(4), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
733                    tuple_ty.backend_repr,
734                    BackendRepr::SimdScalableVector {
735                        number_of_vectors: NumScalableVectors(4),
736                        ..
737                    }
738                );
739                let ret = self.const_poison(self.backend_type(tuple_ty));
740                let ret = self.insert_value(ret, args[0].immediate(), 0);
741                let ret = self.insert_value(ret, args[1].immediate(), 1);
742                let ret = self.insert_value(ret, args[2].immediate(), 2);
743                self.insert_value(ret, args[3].immediate(), 3)
744            }
745
746            sym::sve_tuple_get => {
747                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2..=8), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2..=8), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
748                    self.layout_of(fn_args.type_at(0)).backend_repr,
749                    BackendRepr::SimdScalableVector {
750                        number_of_vectors: NumScalableVectors(2..=8),
751                        ..
752                    }
753                );
754                {
    match self.layout_of(fn_args.type_at(1)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
755                    self.layout_of(fn_args.type_at(1)).backend_repr,
756                    BackendRepr::SimdScalableVector {
757                        number_of_vectors: NumScalableVectors(1),
758                        ..
759                    }
760                );
761                self.extract_value(
762                    args[0].immediate(),
763                    fn_args.const_at(2).to_leaf().to_i32() as u64,
764                )
765            }
766
767            sym::sve_tuple_set => {
768                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2..=8), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2..=8), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
769                    self.layout_of(fn_args.type_at(0)).backend_repr,
770                    BackendRepr::SimdScalableVector {
771                        number_of_vectors: NumScalableVectors(2..=8),
772                        ..
773                    }
774                );
775                {
    match self.layout_of(fn_args.type_at(1)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
776                    self.layout_of(fn_args.type_at(1)).backend_repr,
777                    BackendRepr::SimdScalableVector {
778                        number_of_vectors: NumScalableVectors(1),
779                        ..
780                    }
781                );
782                self.insert_value(
783                    args[0].immediate(),
784                    args[1].immediate(),
785                    fn_args.const_at(2).to_leaf().to_i32() as u64,
786                )
787            }
788
789            _ if name.as_str().starts_with("simd_") => {
790                // Unpack non-power-of-2 #[repr(packed, simd)] arguments.
791                // This gives them the expected layout of a regular #[repr(simd)] vector.
792                let mut loaded_args = Vec::new();
793                for arg in args {
794                    loaded_args.push(
795                        // #[repr(packed, simd)] vectors are passed like arrays (as references,
796                        // with reduced alignment and no padding) rather than as immediates.
797                        // We can use a vector load to fix the layout and turn the argument
798                        // into an immediate.
799                        if arg.layout.ty.is_simd()
800                            && let OperandValue::Ref(place) = arg.val
801                        {
802                            let (size, elem_ty) = arg.layout.ty.simd_size_and_type(self.tcx());
803                            let elem_ll_ty = match elem_ty.kind() {
804                                ty::Float(f) => self.type_float_from_ty(*f),
805                                ty::Int(i) => self.type_int_from_ty(*i),
806                                ty::Uint(u) => self.type_uint_from_ty(*u),
807                                ty::RawPtr(_, _) => self.type_ptr(),
808                                _ => ::core::panicking::unreachable_default_msg()unreachable!(),
809                            };
810                            let loaded =
811                                self.load_from_place(self.type_vector(elem_ll_ty, size), place);
812                            OperandRef::from_immediate_or_packed_pair(self, loaded, arg.layout)
813                        } else {
814                            *arg
815                        },
816                    );
817                }
818
819                let llret_ty = if result_layout.ty.is_simd()
820                    && let BackendRepr::Memory { .. } = result_layout.backend_repr
821                {
822                    let (size, elem_ty) = result_layout.ty.simd_size_and_type(self.tcx());
823                    let elem_ll_ty = match elem_ty.kind() {
824                        ty::Float(f) => self.type_float_from_ty(*f),
825                        ty::Int(i) => self.type_int_from_ty(*i),
826                        ty::Uint(u) => self.type_uint_from_ty(*u),
827                        ty::RawPtr(_, _) => self.type_ptr(),
828                        _ => ::core::panicking::unreachable_default_msg()unreachable!(),
829                    };
830                    self.type_vector(elem_ll_ty, size)
831                } else {
832                    result_layout.llvm_type(self)
833                };
834
835                match generic_simd_intrinsic(
836                    self,
837                    name,
838                    fn_args,
839                    &loaded_args,
840                    result_layout.ty,
841                    llret_ty,
842                    span,
843                ) {
844                    Ok(llval) => llval,
845                    // If there was an error, just skip this invocation... we'll abort compilation
846                    // anyway, but we can keep codegen'ing to find more errors.
847                    Err(err) => return IntrinsicResult::Err(err),
848                }
849            }
850
851            sym::return_address => {
852                match self.sess().target.arch {
853                    // Expand this list as needed
854                    Arch::Wasm32 | Arch::Wasm64 => {
855                        let ty = self.type_ptr();
856                        self.const_null(ty)
857                    }
858                    _ => {
859                        let ty = self.type_ix(32);
860                        let val = self.const_int(ty, 0);
861
862                        let type_params: &[Type<'ll>] =
863                            if llvm_version < (23, 0, 0) { &[] } else { &[self.type_ptr()] };
864
865                        self.call_intrinsic("llvm.returnaddress", type_params, &[val])
866                    }
867                }
868            }
869
870            sym::codeview_annotation => {
871                if self.sess().target.uses_pdb_debuginfo() {
872                    codegen_codeview_annotation(self, instance, span);
873                }
874                return IntrinsicResult::Operand(OperandValue::ZeroSized);
875            }
876
877            _ => {
878                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/intrinsic.rs:878",
                        "rustc_codegen_llvm::intrinsic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/intrinsic.rs"),
                        ::tracing_core::__macro_support::Option::Some(878u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::intrinsic"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unknown intrinsic \'{0}\' -- falling back to default body",
                                                    name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("unknown intrinsic '{}' -- falling back to default body", name);
879                // Call the fallback body instead of generating the intrinsic code
880                let fallback = ty::Instance::new_raw(instance.def_id(), instance.args);
881                return IntrinsicResult::Fallback(fallback);
882            }
883        };
884
885        if let BackendRepr::Memory { .. } = result_layout.backend_repr {
886            // We have an llvm immediate, but that's not what cg_ssa expects,
887            // so write it into the place (that always exists for memory)
888            if !result_layout.is_zst() {
889                self.store_to_place(llval, result_place.unwrap());
890            }
891            IntrinsicResult::WroteIntoPlace
892        } else {
893            IntrinsicResult::Operand(
894                OperandRef::from_immediate_or_packed_pair(self, llval, result_layout).val,
895            )
896        }
897    }
898
899    fn codegen_llvm_intrinsic_call(
900        &mut self,
901        instance: ty::Instance<'tcx>,
902        args: &[OperandRef<'tcx, Self::Value>],
903        _is_cleanup: bool,
904    ) -> Self::Value {
905        let tcx = self.tcx();
906
907        let fn_ty = instance.ty(tcx, self.typing_env());
908        let fn_sig = match *fn_ty.kind() {
909            ty::FnDef(def_id, args) => tcx.instantiate_bound_regions_with_erased(
910                tcx.fn_sig(def_id).instantiate(tcx, args.no_bound_vars().unwrap()).skip_norm_wip(),
911            ),
912            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
913        };
914        if !!fn_sig.c_variadic() {
    ::core::panicking::panic("assertion failed: !fn_sig.c_variadic()")
};assert!(!fn_sig.c_variadic());
915
916        let ret_layout = self.layout_of(fn_sig.output());
917        let llreturn_ty = if ret_layout.is_zst() {
918            self.type_void()
919        } else {
920            ret_layout.immediate_llvm_type(self)
921        };
922
923        let mut llargument_tys = Vec::with_capacity(fn_sig.inputs().len());
924        for &arg in fn_sig.inputs() {
925            let arg_layout = self.layout_of(arg);
926            if arg_layout.is_zst() {
927                continue;
928            }
929            llargument_tys.push(arg_layout.immediate_llvm_type(self));
930        }
931
932        let fn_ptr = if let Some(&llfn) = self.intrinsic_instances.borrow().get(&instance) {
933            llfn
934        } else {
935            let sym = tcx.symbol_name(instance).name;
936
937            let llfn = if let Some(llfn) = self.get_declared_value(sym) {
938                llfn
939            } else {
940                intrinsic_fn(self, sym, llreturn_ty, llargument_tys, instance)
941            };
942
943            self.intrinsic_instances.borrow_mut().insert(instance, llfn);
944
945            llfn
946        };
947        let fn_ty = self.get_type_of_global(fn_ptr);
948
949        let mut llargs = args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>();
950
951        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/intrinsic.rs:951",
                        "rustc_codegen_llvm::intrinsic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/intrinsic.rs"),
                        ::tracing_core::__macro_support::Option::Some(951u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::intrinsic"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("call intrinsic {0:?} with args ({1:?})",
                                                    instance, llargs) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call intrinsic {:?} with args ({:?})", instance, llargs);
952
953        for (dest_ty, arg) in iter::zip(self.func_params_types(fn_ty), &mut llargs) {
954            let src_ty = self.val_ty(*arg);
955            if !can_autocast(self, src_ty, dest_ty) {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot match `{0:?}` (expected) with {1:?} (found) in `{2:?}",
                dest_ty, src_ty, fn_ptr));
    }
};assert!(
956                can_autocast(self, src_ty, dest_ty),
957                "Cannot match `{dest_ty:?}` (expected) with {src_ty:?} (found) in `{fn_ptr:?}"
958            );
959
960            *arg = autocast(self, *arg, src_ty, dest_ty);
961        }
962
963        let llret = unsafe {
964            llvm::LLVMBuildCallWithOperandBundles(
965                self.llbuilder(),
966                fn_ty,
967                fn_ptr,
968                llargs.as_ptr(),
969                llargs.len() as c_uint,
970                ptr::dangling(),
971                0,
972                c"".as_ptr(),
973            )
974        };
975
976        let src_ty = self.val_ty(llret);
977        let dest_ty = llreturn_ty;
978        if !can_autocast(self, dest_ty, src_ty) {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot match `{0:?}` (expected) with `{1:?}` (found) in `{2:?}`",
                src_ty, dest_ty, fn_ptr));
    }
};assert!(
979            can_autocast(self, dest_ty, src_ty),
980            "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`"
981        );
982
983        autocast(self, llret, src_ty, dest_ty)
984    }
985
986    fn abort_immediate(&mut self) {
987        self.call_intrinsic("llvm.trap", &[], &[]);
988    }
989
990    fn assume(&mut self, val: Self::Value) {
991        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
992            self.call_intrinsic("llvm.assume", &[], &[val]);
993        }
994    }
995
996    fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
997        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
998            self.call_intrinsic(
999                "llvm.expect",
1000                &[self.type_i1()],
1001                &[cond, self.const_bool(expected)],
1002            )
1003        } else {
1004            cond
1005        }
1006    }
1007
1008    fn ctpop(&mut self, val: Self::Value) -> Self::Value {
1009        let ret = self.call_intrinsic("llvm.ctpop", &[self.val_ty(val)], &[val]);
1010        self.intcast(ret, self.type_i32(), false)
1011    }
1012
1013    fn type_checked_load(
1014        &mut self,
1015        llvtable: Value<'ll>,
1016        vtable_byte_offset: u64,
1017        typeid: &[u8],
1018    ) -> Self::Value {
1019        let typeid = self.create_metadata(typeid);
1020        let typeid = self.get_metadata_value(typeid);
1021        let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
1022        let type_checked_load = self.call_intrinsic(
1023            "llvm.type.checked.load",
1024            &[],
1025            &[llvtable, vtable_byte_offset, typeid],
1026        );
1027        self.extract_value(type_checked_load, 0)
1028    }
1029
1030    fn va_start(&mut self, va_list: Value<'ll>) {
1031        self.call_intrinsic("llvm.va_start", &[self.val_ty(va_list)], &[va_list]);
1032    }
1033
1034    fn retag_reg(&mut self, ptr: Self::Value, info: &RetagInfo<Self::Value>) -> Self::Value {
1035        codegen_retag_inner(self, "__rust_retag_reg", ptr, info)
1036    }
1037
1038    fn retag_mem(&mut self, ptr: Self::Value, info: &RetagInfo<Self::Value>) {
1039        codegen_retag_inner(self, "__rust_retag_mem", ptr, info);
1040    }
1041}
1042
1043fn llvm_arch_for(rust_arch: &Arch) -> Option<&'static str> {
1044    Some(match rust_arch {
1045        Arch::AArch64 | Arch::Arm64EC => "aarch64",
1046        Arch::AmdGpu => "amdgcn",
1047        Arch::Arm => "arm",
1048        Arch::Bpf => "bpf",
1049        Arch::Hexagon => "hexagon",
1050        Arch::LoongArch32 | Arch::LoongArch64 => "loongarch",
1051        Arch::Mips | Arch::Mips32r6 | Arch::Mips64 | Arch::Mips64r6 => "mips",
1052        Arch::Nvptx64 => "nvvm",
1053        Arch::PowerPC | Arch::PowerPC64 => "ppc",
1054        Arch::RiscV32 | Arch::RiscV64 => "riscv",
1055        Arch::S390x => "s390",
1056        Arch::SpirV => "spv",
1057        Arch::Wasm32 | Arch::Wasm64 => "wasm",
1058        Arch::X86 | Arch::X86_64 => "x86",
1059        _ => return None, // fallback for unknown archs
1060    })
1061}
1062
1063fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: Type<'ll>, llvm_ty: Type<'ll>) -> bool {
1064    if rust_ty == llvm_ty {
1065        return true;
1066    }
1067
1068    match cx.type_kind(llvm_ty) {
1069        // Some LLVM intrinsics return **non-packed** structs, but they can't be mimicked from Rust
1070        // due to auto field-alignment in non-packed structs (packed structs are represented in LLVM
1071        // as, well, packed structs, so they won't match with those either)
1072        TypeKind::Struct if cx.type_kind(rust_ty) == TypeKind::Struct => {
1073            let rust_element_tys = cx.struct_element_types(rust_ty);
1074            let llvm_element_tys = cx.struct_element_types(llvm_ty);
1075
1076            if rust_element_tys.len() != llvm_element_tys.len() {
1077                return false;
1078            }
1079
1080            iter::zip(rust_element_tys, llvm_element_tys).all(
1081                |(rust_element_ty, llvm_element_ty)| {
1082                    can_autocast(cx, rust_element_ty, llvm_element_ty)
1083                },
1084            )
1085        }
1086        _ if let Some((llvm_element_ty, element_count)) =
1087            cx.vector_element_type_and_length(llvm_ty) =>
1088        {
1089            if llvm_element_ty == cx.type_bf16() {
1090                rust_ty == cx.type_vector(cx.type_i16(), element_count)
1091            } else if llvm_element_ty == cx.type_i1() {
1092                let int_width = element_count.next_power_of_two().max(8);
1093                rust_ty == cx.type_ix(int_width)
1094            } else {
1095                false
1096            }
1097        }
1098        TypeKind::BFloat => rust_ty == cx.type_i16(),
1099        TypeKind::X86_AMX
1100            if let Some((element_ty, element_count)) =
1101                cx.vector_element_type_and_length(rust_ty) =>
1102        {
1103            let element_size_bits = if let Some(float) = cx.float_type(element_ty) {
1104                float.size().bits()
1105            } else if let Some(bits) = cx.int_width(element_ty) {
1106                bits
1107            } else if cx.type_kind(element_ty) == TypeKind::Pointer {
1108                cx.data_layout().pointer_size().bits()
1109            } else {
1110                ::rustc_span::macros::bug_impl(None,
    format_args!("Vector element type `{0:?}` not one of integer, float or pointer",
        element_ty), Location::caller())bug!("Vector element type `{element_ty:?}` not one of integer, float or pointer")
1111            };
1112
1113            element_size_bits * element_count == 8192
1114        }
1115        _ => false,
1116    }
1117}
1118
1119fn autocast<'ll>(
1120    bx: &mut Builder<'_, 'll, '_>,
1121    val: Value<'ll>,
1122    src_ty: Type<'ll>,
1123    dest_ty: Type<'ll>,
1124) -> Value<'ll> {
1125    if src_ty == dest_ty {
1126        return val;
1127    }
1128    match (bx.type_kind(src_ty), bx.type_kind(dest_ty)) {
1129        // re-pack structs
1130        (TypeKind::Struct, TypeKind::Struct) => {
1131            let mut ret = bx.const_poison(dest_ty);
1132            for (idx, (src_element_ty, dest_element_ty)) in
1133                iter::zip(bx.struct_element_types(src_ty), bx.struct_element_types(dest_ty))
1134                    .enumerate()
1135            {
1136                let elt = bx.extract_value(val, idx as u64);
1137                let casted_elt = autocast(bx, elt, src_element_ty, dest_element_ty);
1138                ret = bx.insert_value(ret, casted_elt, idx as u64);
1139            }
1140            ret
1141        }
1142        // cast from the i1xN vector type to the primitive type
1143        (TypeKind::Vector, TypeKind::Integer)
1144            if let Some((elem, vector_length)) = bx.vector_element_type_and_length(src_ty)
1145                && elem == bx.type_i1() =>
1146        {
1147            let int_width = vector_length.next_power_of_two().max(8);
1148
1149            let val = if vector_length == int_width {
1150                val
1151            } else {
1152                // zero-extends vector
1153                let shuffle_indices = match vector_length {
1154                    0 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("zero length vectors are not allowed")));
}unreachable!("zero length vectors are not allowed"),
1155                    1 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 1, 1, 1, 1, 1, 1]))vec![0, 1, 1, 1, 1, 1, 1, 1],
1156                    2 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 2, 2, 2, 2, 2, 2]))vec![0, 1, 2, 2, 2, 2, 2, 2],
1157                    3 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 2, 3, 3, 3, 3, 3]))vec![0, 1, 2, 3, 3, 3, 3, 3],
1158                    4.. => (0..int_width as i32).collect(),
1159                };
1160                let shuffle_mask =
1161                    shuffle_indices.into_iter().map(|i| bx.const_i32(i)).collect::<Vec<_>>();
1162                bx.shuffle_vector(val, bx.const_null(src_ty), bx.const_vector(&shuffle_mask))
1163            };
1164            bx.bitcast(val, dest_ty)
1165        }
1166        // cast from the primitive type to the i1xN vector type
1167        (TypeKind::Integer, TypeKind::Vector)
1168            if let Some((elem, vector_length)) = bx.vector_element_type_and_length(dest_ty)
1169                && elem == bx.type_i1() =>
1170        {
1171            let int_width = vector_length.next_power_of_two().max(8);
1172
1173            let intermediate_ty = bx.type_vector(bx.type_i1(), int_width);
1174            let intermediate = bx.bitcast(val, intermediate_ty);
1175
1176            if vector_length == int_width {
1177                intermediate
1178            } else {
1179                let shuffle_mask: Vec<_> =
1180                    (0..vector_length).map(|i| bx.const_i32(i as i32)).collect();
1181                bx.shuffle_vector(
1182                    intermediate,
1183                    bx.const_poison(intermediate_ty),
1184                    bx.const_vector(&shuffle_mask),
1185                )
1186            }
1187        }
1188        (TypeKind::Vector, TypeKind::X86_AMX) => {
1189            bx.call_intrinsic("llvm.x86.cast.vector.to.tile", &[src_ty], &[val])
1190        }
1191        (TypeKind::X86_AMX, TypeKind::Vector) => {
1192            bx.call_intrinsic("llvm.x86.cast.tile.to.vector", &[dest_ty], &[val])
1193        }
1194        _ => bx.bitcast(val, dest_ty), // for `bf16(xN)` <-> `u16(xN)`
1195    }
1196}
1197
1198fn intrinsic_fn<'ll, 'tcx>(
1199    bx: &Builder<'_, 'll, 'tcx>,
1200    name: &str,
1201    rust_return_ty: Type<'ll>,
1202    rust_argument_tys: Vec<Type<'ll>>,
1203    instance: ty::Instance<'tcx>,
1204) -> Value<'ll> {
1205    let tcx = bx.tcx;
1206
1207    let rust_fn_ty = bx.type_func(&rust_argument_tys, rust_return_ty);
1208
1209    let intrinsic = llvm::Intrinsic::lookup(name.as_bytes());
1210
1211    if let Some(intrinsic) = intrinsic
1212        && intrinsic.is_target_specific()
1213    {
1214        let (llvm_arch, _) = name[5..].split_once('.').unwrap();
1215        let rust_arch = &tcx.sess.target.arch;
1216
1217        if let Some(correct_llvm_arch) = llvm_arch_for(rust_arch)
1218            && llvm_arch != correct_llvm_arch
1219        {
1220            tcx.dcx().emit_fatal(IntrinsicWrongArch {
1221                name,
1222                target_arch: rust_arch.desc(),
1223                span: tcx.def_span(instance.def_id()),
1224            });
1225        }
1226    }
1227
1228    if let Some(intrinsic) = intrinsic
1229        && !intrinsic.is_overloaded()
1230    {
1231        // FIXME: also do this for overloaded intrinsics
1232        let llfn = intrinsic.get_declaration(bx.llmod, &[]);
1233        let llvm_fn_ty = bx.get_type_of_global(llfn);
1234
1235        let llvm_return_ty = bx.get_return_type(llvm_fn_ty);
1236        let llvm_argument_tys = bx.func_params_types(llvm_fn_ty);
1237        let llvm_is_variadic = bx.func_is_variadic(llvm_fn_ty);
1238
1239        let is_correct_signature = !llvm_is_variadic
1240            && rust_argument_tys.len() == llvm_argument_tys.len()
1241            && iter::once((rust_return_ty, llvm_return_ty))
1242                .chain(iter::zip(rust_argument_tys, llvm_argument_tys))
1243                .all(|(rust_ty, llvm_ty)| can_autocast(bx, rust_ty, llvm_ty));
1244
1245        if !is_correct_signature {
1246            tcx.dcx().emit_fatal(IntrinsicSignatureMismatch {
1247                name,
1248                llvm_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", llvm_fn_ty))
    })format!("{llvm_fn_ty:?}"),
1249                rust_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", rust_fn_ty))
    })format!("{rust_fn_ty:?}"),
1250                span: tcx.def_span(instance.def_id()),
1251            });
1252        }
1253
1254        return llfn;
1255    }
1256
1257    // Function addresses in Rust are never significant, allowing functions to be merged.
1258    let llfn = declare_raw_fn(
1259        bx,
1260        name,
1261        llvm::CCallConv,
1262        llvm::UnnamedAddr::Global,
1263        llvm::Visibility::Default,
1264        rust_fn_ty,
1265    );
1266
1267    if intrinsic.is_none() {
1268        let mut new_llfn = None;
1269        let can_upgrade = unsafe { llvm::LLVMRustUpgradeIntrinsicFunction(llfn, &mut new_llfn) };
1270
1271        if !can_upgrade {
1272            // This is either plain wrong, or this can be caused by incompatible LLVM versions
1273            tcx.dcx().emit_fatal(UnknownIntrinsic { name, span: tcx.def_span(instance.def_id()) });
1274        } else if let Some(def_id) = instance.def_id().as_local() {
1275            // we can emit diagnostics only for local crates
1276            let hir_id = tcx.local_def_id_to_hir_id(def_id);
1277
1278            // not all intrinsics are upgraded to some other intrinsics, most are upgraded to instruction sequences
1279            let msg = if let Some(new_llfn) = new_llfn {
1280                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{1}`, `{0}` can be used instead",
                str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap(),
                name))
    })format!(
1281                    "using deprecated intrinsic `{name}`, `{}` can be used instead",
1282                    str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap()
1283                )
1284            } else {
1285                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{0}`",
                name))
    })format!("using deprecated intrinsic `{name}`")
1286            };
1287
1288            tcx.emit_node_lint(
1289                DEPRECATED_LLVM_INTRINSIC,
1290                hir_id,
1291                rustc_errors::DiagDecorator(|d| {
1292                    d.primary_message(msg).span(tcx.hir_span(hir_id));
1293                }),
1294            );
1295        }
1296    }
1297
1298    llfn
1299}
1300
1301fn catch_unwind_intrinsic<'ll, 'tcx>(
1302    bx: &mut Builder<'_, 'll, 'tcx>,
1303    try_func: Value<'ll>,
1304    data: Value<'ll>,
1305    catch_func: Value<'ll>,
1306) -> Value<'ll> {
1307    if !bx.sess().panic_strategy().unwinds() {
1308        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1309        bx.call(try_func_ty, None, None, try_func, ReturnSlot::Direct, &[data], None, None);
1310        // Return 0 unconditionally from the intrinsic call;
1311        // we can never unwind.
1312        bx.const_bool(false)
1313    } else if wants_msvc_seh(&bx.sess().target) {
1314        codegen_msvc_try(bx, try_func, data, catch_func)
1315    } else if wants_wasm_eh(&bx.sess().target) {
1316        codegen_wasm_try(bx, try_func, data, catch_func)
1317    } else {
1318        codegen_gnu_try(bx, try_func, data, catch_func)
1319    }
1320}
1321
1322// MSVC's definition of the `rust_try` function.
1323//
1324// This implementation uses the new exception handling instructions in LLVM
1325// which have support in LLVM for SEH on MSVC targets. Although these
1326// instructions are meant to work for all targets, as of the time of this
1327// writing, however, LLVM does not recommend the usage of these new instructions
1328// as the old ones are still more optimized.
1329fn codegen_msvc_try<'ll, 'tcx>(
1330    bx: &mut Builder<'_, 'll, 'tcx>,
1331    try_func: Value<'ll>,
1332    data: Value<'ll>,
1333    catch_func: Value<'ll>,
1334) -> Value<'ll> {
1335    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1336        bx.set_personality_fn(bx.eh_personality());
1337
1338        let normal = bx.append_sibling_block("normal");
1339        let catchswitch = bx.append_sibling_block("catchswitch");
1340        let catchpad_rust = bx.append_sibling_block("catchpad_rust");
1341        let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
1342        let caught = bx.append_sibling_block("caught");
1343
1344        let try_func = llvm::get_param(bx.llfn(), 0);
1345        let data = llvm::get_param(bx.llfn(), 1);
1346        let catch_func = llvm::get_param(bx.llfn(), 2);
1347
1348        // We're generating an IR snippet that looks like:
1349        //
1350        //   declare bool @rust_try(%try_func, %data, %catch_func) {
1351        //      %slot = alloca i8*
1352        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1353        //
1354        //   normal:
1355        //      ret i1 false
1356        //
1357        //   catchswitch:
1358        //      %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
1359        //
1360        //   catchpad_rust:
1361        //      %tok = catchpad within %cs [%type_descriptor, 8, %slot]
1362        //      %ptr = load %slot
1363        //      call %catch_func(%data, %ptr)
1364        //      catchret from %tok to label %caught
1365        //
1366        //   catchpad_foreign:
1367        //      %tok = catchpad within %cs [null, 64, null]
1368        //      call %catch_func(%data, null)
1369        //      catchret from %tok to label %caught
1370        //
1371        //   caught:
1372        //      ret i1 true
1373        //   }
1374        //
1375        // This structure follows the basic usage of throw/try/catch in LLVM.
1376        // For example, compile this C++ snippet to see what LLVM generates:
1377        //
1378        //      struct rust_panic {
1379        //          rust_panic(const rust_panic&);
1380        //          ~rust_panic();
1381        //
1382        //          void* x[2];
1383        //      };
1384        //
1385        //      int __rust_try(
1386        //          void (*try_func)(void*),
1387        //          void *data,
1388        //          void (*catch_func)(void*, void*) noexcept
1389        //      ) {
1390        //          try {
1391        //              try_func(data);
1392        //              return 0;
1393        //          } catch(rust_panic& a) {
1394        //              catch_func(data, &a);
1395        //              return 1;
1396        //          } catch(...) {
1397        //              catch_func(data, NULL);
1398        //              return 1;
1399        //          }
1400        //      }
1401        //
1402        // More information can be found in libstd's seh.rs implementation.
1403        let ptr_size = bx.tcx().data_layout.pointer_size();
1404        let ptr_align = bx.tcx().data_layout.pointer_align();
1405        let slot = bx.alloca(ptr_size, ptr_align);
1406        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1407        bx.invoke(
1408            try_func_ty,
1409            None,
1410            None,
1411            try_func,
1412            ReturnSlot::Direct,
1413            &[data],
1414            normal,
1415            catchswitch,
1416            None,
1417            None,
1418        );
1419
1420        bx.switch_to_block(normal);
1421        bx.ret(bx.const_bool(false));
1422
1423        bx.switch_to_block(catchswitch);
1424        let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
1425
1426        // We can't use the TypeDescriptor defined in libpanic_unwind because it
1427        // might be in another DLL and the SEH encoding only supports specifying
1428        // a TypeDescriptor from the current module.
1429        //
1430        // However this isn't an issue since the MSVC runtime uses string
1431        // comparison on the type name to match TypeDescriptors rather than
1432        // pointer equality.
1433        //
1434        // So instead we generate a new TypeDescriptor in each module that uses
1435        // `try` and let the linker merge duplicate definitions in the same
1436        // module.
1437        //
1438        // When modifying, make sure that the type_name string exactly matches
1439        // the one used in library/panic_unwind/src/seh.rs.
1440        let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_ptr());
1441        let type_name = bx.const_bytes(b"rust_panic\0");
1442        let type_info =
1443            bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false);
1444        let tydesc = bx.declare_global(
1445            &mangle_internal_symbol(bx.tcx, "__rust_panic_type_info"),
1446            bx.val_ty(type_info),
1447        );
1448
1449        llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1450        if bx.cx.tcx.sess.target.supports_comdat() {
1451            llvm::SetUniqueComdat(bx.llmod, tydesc);
1452        }
1453        llvm::set_initializer(tydesc, type_info);
1454
1455        // The flag value of 8 indicates that we are catching the exception by
1456        // reference instead of by value. We can't use catch by value because
1457        // that requires copying the exception object, which we don't support
1458        // since our exception object effectively contains a Box.
1459        //
1460        // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1461        bx.switch_to_block(catchpad_rust);
1462        let flags = bx.const_i32(8);
1463        let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
1464        let ptr = bx.load(bx.type_ptr(), slot, ptr_align);
1465        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1466        bx.call(
1467            catch_ty,
1468            None,
1469            None,
1470            catch_func,
1471            ReturnSlot::Direct,
1472            &[data, ptr],
1473            Some(&funclet),
1474            None,
1475        );
1476        bx.catch_ret(&funclet, caught);
1477
1478        // The flag value of 64 indicates a "catch-all".
1479        bx.switch_to_block(catchpad_foreign);
1480        let flags = bx.const_i32(64);
1481        let null = bx.const_null(bx.type_ptr());
1482        let funclet = bx.catch_pad(cs, &[null, flags, null]);
1483        bx.call(
1484            catch_ty,
1485            None,
1486            None,
1487            catch_func,
1488            ReturnSlot::Direct,
1489            &[data, null],
1490            Some(&funclet),
1491            None,
1492        );
1493        bx.catch_ret(&funclet, caught);
1494
1495        bx.switch_to_block(caught);
1496        bx.ret(bx.const_bool(true));
1497    });
1498
1499    // Note that no invoke is used here because by definition this function
1500    // can't panic (that's what it's catching).
1501    bx.call(llty, None, None, llfn, ReturnSlot::Direct, &[try_func, data, catch_func], None, None)
1502}
1503
1504// WASM's definition of the `rust_try` function.
1505fn codegen_wasm_try<'ll, 'tcx>(
1506    bx: &mut Builder<'_, 'll, 'tcx>,
1507    try_func: Value<'ll>,
1508    data: Value<'ll>,
1509    catch_func: Value<'ll>,
1510) -> Value<'ll> {
1511    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1512        bx.set_personality_fn(bx.eh_personality());
1513
1514        let normal = bx.append_sibling_block("normal");
1515        let catchswitch = bx.append_sibling_block("catchswitch");
1516        let catchpad = bx.append_sibling_block("catchpad");
1517        let caught = bx.append_sibling_block("caught");
1518
1519        let try_func = llvm::get_param(bx.llfn(), 0);
1520        let data = llvm::get_param(bx.llfn(), 1);
1521        let catch_func = llvm::get_param(bx.llfn(), 2);
1522
1523        // We're generating an IR snippet that looks like:
1524        //
1525        //   declare i1 @rust_try(%try_func, %data, %catch_func) {
1526        //      %slot = alloca i8*
1527        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1528        //
1529        //   normal:
1530        //      ret i1 false
1531        //
1532        //   catchswitch:
1533        //      %cs = catchswitch within none [%catchpad] unwind to caller
1534        //
1535        //   catchpad:
1536        //      %tok = catchpad within %cs [null]
1537        //      %ptr = call @llvm.wasm.get.exception(token %tok)
1538        //      %sel = call @llvm.wasm.get.ehselector(token %tok)
1539        //      call %catch_func(%data, %ptr)
1540        //      catchret from %tok to label %caught
1541        //
1542        //   caught:
1543        //      ret i1 true
1544        //   }
1545        //
1546        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1547        bx.invoke(
1548            try_func_ty,
1549            None,
1550            None,
1551            try_func,
1552            ReturnSlot::Direct,
1553            &[data],
1554            normal,
1555            catchswitch,
1556            None,
1557            None,
1558        );
1559
1560        bx.switch_to_block(normal);
1561        bx.ret(bx.const_bool(false));
1562
1563        bx.switch_to_block(catchswitch);
1564        let cs = bx.catch_switch(None, None, &[catchpad]);
1565
1566        bx.switch_to_block(catchpad);
1567        let null = bx.const_null(bx.type_ptr());
1568        let funclet = bx.catch_pad(cs, &[null]);
1569
1570        let ptr = bx.call_intrinsic("llvm.wasm.get.exception", &[], &[funclet.cleanuppad()]);
1571        let _sel = bx.call_intrinsic("llvm.wasm.get.ehselector", &[], &[funclet.cleanuppad()]);
1572
1573        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1574        bx.call(
1575            catch_ty,
1576            None,
1577            None,
1578            catch_func,
1579            ReturnSlot::Direct,
1580            &[data, ptr],
1581            Some(&funclet),
1582            None,
1583        );
1584        bx.catch_ret(&funclet, caught);
1585
1586        bx.switch_to_block(caught);
1587        bx.ret(bx.const_bool(true));
1588    });
1589
1590    // Note that no invoke is used here because by definition this function
1591    // can't panic (that's what it's catching).
1592    bx.call(llty, None, None, llfn, ReturnSlot::Direct, &[try_func, data, catch_func], None, None)
1593}
1594
1595// Definition of the standard `try` function for Rust using the GNU-like model
1596// of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1597// instructions).
1598//
1599// This codegen is a little surprising because we always call a shim
1600// function instead of inlining the call to `invoke` manually here. This is done
1601// because in LLVM we're only allowed to have one personality per function
1602// definition. The call to the `try` intrinsic is being inlined into the
1603// function calling it, and that function may already have other personality
1604// functions in play. By calling a shim we're guaranteed that our shim will have
1605// the right personality function.
1606fn codegen_gnu_try<'ll, 'tcx>(
1607    bx: &mut Builder<'_, 'll, 'tcx>,
1608    try_func: Value<'ll>,
1609    data: Value<'ll>,
1610    catch_func: Value<'ll>,
1611) -> Value<'ll> {
1612    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1613        // Codegens the shims described above:
1614        //
1615        //   bx:
1616        //      invoke %try_func(%data) normal %normal unwind %catch
1617        //
1618        //   normal:
1619        //      ret 0
1620        //
1621        //   catch:
1622        //      (%ptr, _) = landingpad
1623        //      call %catch_func(%data, %ptr)
1624        //      ret 1
1625        let then = bx.append_sibling_block("then");
1626        let catch = bx.append_sibling_block("catch");
1627
1628        let try_func = llvm::get_param(bx.llfn(), 0);
1629        let data = llvm::get_param(bx.llfn(), 1);
1630        let catch_func = llvm::get_param(bx.llfn(), 2);
1631        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1632        bx.invoke(
1633            try_func_ty,
1634            None,
1635            None,
1636            try_func,
1637            ReturnSlot::Direct,
1638            &[data],
1639            then,
1640            catch,
1641            None,
1642            None,
1643        );
1644
1645        bx.switch_to_block(then);
1646        bx.ret(bx.const_bool(false));
1647
1648        // Type indicator for the exception being thrown.
1649        //
1650        // The first value in this tuple is a pointer to the exception object
1651        // being thrown. The second value is a "selector" indicating which of
1652        // the landing pad clauses the exception's type had been matched to.
1653        // rust_try ignores the selector.
1654        bx.switch_to_block(catch);
1655        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()]);
1656        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
1657        let tydesc = bx.const_null(bx.type_ptr());
1658        bx.add_clause(vals, tydesc);
1659        let ptr = bx.extract_value(vals, 0);
1660        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1661        bx.call(catch_ty, None, None, catch_func, ReturnSlot::Direct, &[data, ptr], None, None);
1662        bx.ret(bx.const_bool(true));
1663    });
1664
1665    // Note that no invoke is used here because by definition this function
1666    // can't panic (that's what it's catching).
1667    bx.call(llty, None, None, llfn, ReturnSlot::Direct, &[try_func, data, catch_func], None, None)
1668}
1669
1670// Helper function to give a Block to a closure to codegen a shim function.
1671// This is currently primarily used for the `try` intrinsic functions above.
1672fn gen_fn<'a, 'll, 'tcx>(
1673    cx: &'a CodegenCx<'ll, 'tcx>,
1674    name: &str,
1675    rust_fn_sig: ty::PolyFnSig<'tcx>,
1676    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1677) -> (Type<'ll>, Value<'ll>) {
1678    let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1679    let llty = fn_abi.llvm_type(cx);
1680    let llfn = cx.declare_fn(name, fn_abi, None);
1681    cx.set_frame_pointer_type(llfn);
1682    cx.apply_target_cpu_attr(llfn);
1683    cx.apply_default_optimisation_attrs(llfn);
1684    // FIXME(eddyb) find a nicer way to do this.
1685    llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage);
1686    let llbb = Builder::append_block(cx, llfn, "entry-block");
1687    let bx = Builder::build(cx, llbb);
1688    codegen(bx);
1689    (llty, llfn)
1690}
1691
1692// Helper function used to get a handle to the `__rust_try` function used to
1693// catch exceptions.
1694//
1695// This function is only generated once and is then cached.
1696fn get_rust_try_fn<'a, 'll, 'tcx>(
1697    cx: &'a CodegenCx<'ll, 'tcx>,
1698    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1699) -> (Type<'ll>, Value<'ll>) {
1700    if let Some(llfn) = cx.rust_try_fn.get() {
1701        return llfn;
1702    }
1703
1704    // Define the type up front for the signature of the rust_try function.
1705    let tcx = cx.tcx;
1706    let i8p = Ty::new_mut_ptr(tcx, tcx.types.i8);
1707    // `unsafe fn(*mut Data) -> ()`
1708    let try_fn_ty = Ty::new_fn_ptr(
1709        tcx,
1710        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p], tcx.types.unit, hir::Safety::Unsafe)),
1711    );
1712    // `unsafe fn(*mut Data, *mut i8) -> ()`
1713    let catch_fn_ty = Ty::new_fn_ptr(
1714        tcx,
1715        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p, i8p], tcx.types.unit, hir::Safety::Unsafe)),
1716    );
1717    // `unsafe fn(unsafe fn(*mut Data) -> (), *mut Data, unsafe fn(*mut Data, *mut i8) -> ()) -> bool`
1718    let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig_rust_abi(
1719        [try_fn_ty, i8p, catch_fn_ty],
1720        tcx.types.bool,
1721        hir::Safety::Unsafe,
1722    ));
1723    let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
1724
1725    if cx.sess().pointer_authentication() {
1726        let cfg = cx.sess().pointer_auth_config.as_ref().unwrap();
1727        let attrs: Vec<&Attribute> =
1728            cfg.fn_attrs().into_iter().map(|name| llvm::CreateAttrString(cx.llcx, name)).collect();
1729
1730        let (_ty, rust_try_fn) = rust_try;
1731        crate::attributes::apply_to_llfn(rust_try_fn, AttributePlace::Function, &attrs);
1732    }
1733
1734    cx.rust_try_fn.set(Some(rust_try));
1735    rust_try
1736}
1737
1738fn codegen_retag_inner<'ll, 'tcx>(
1739    bx: &mut Builder<'_, 'll, 'tcx>,
1740    name: &'static str,
1741    ptr: Value<'ll>,
1742    info: &RetagInfo<Value<'ll>>,
1743) -> Value<'ll> {
1744    let size = bx.const_usize(info.size.bytes());
1745    let perms = bx.const_u8(info.flags.bits());
1746
1747    bx.call_intrinsic(
1748        name,
1749        // Retag intrinsics have special handling within `CodegenCx::declare_intrinsic`
1750        // to ensure that each form has the correct return type.
1751        &[bx.type_ptr(), bx.val_ty(size), bx.type_i8(), bx.type_ptr(), bx.type_ptr()],
1752        &[ptr, size, perms, info.im_layout, info.pin_layout],
1753    )
1754}
1755
1756fn codegen_autodiff<'ll, 'tcx>(
1757    bx: &mut Builder<'_, 'll, 'tcx>,
1758    instance: ty::Instance<'tcx>,
1759    args: &[OperandRef<'tcx, Value<'ll>>],
1760    result_layout: ty::layout::TyAndLayout<'tcx>,
1761    result_place: Option<PlaceValue<Value<'ll>>>,
1762) -> IntrinsicResult<'tcx, Value<'ll>> {
1763    let tcx = bx.tcx;
1764    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
1765        let _ = tcx.dcx().emit_err(AutoDiffWithoutEnable);
1766    }
1767
1768    let ct = tcx.crate_types();
1769    let lto = tcx.sess.lto();
1770    if ct.len() == 1 && ct.contains(&CrateType::Executable) {
1771        if lto != rustc_session::config::Lto::Fat {
1772            let _ = tcx.dcx().emit_err(AutoDiffWithoutLto);
1773        }
1774    } else {
1775        if lto != rustc_session::config::Lto::Fat && !tcx.sess.opts.cg.linker_plugin_lto.enabled() {
1776            let _ = tcx.dcx().emit_err(AutoDiffWithoutLto);
1777        }
1778    }
1779
1780    let fn_args = instance.args;
1781    let callee_ty = instance.ty(tcx, bx.typing_env());
1782
1783    let sig = callee_ty.fn_sig(tcx).skip_binder();
1784
1785    let ret_ty = sig.output();
1786    let llret_ty = bx.layout_of(ret_ty).llvm_type(bx);
1787
1788    let source_fn_ptr_ty = fn_args.into_type_list(tcx)[0];
1789    let fn_to_diff = args[0].immediate();
1790
1791    let (diff_id, diff_args) = match fn_args.into_type_list(tcx)[1].kind() {
1792        ty::FnDef(def_id, diff_args) => (def_id, diff_args.no_bound_vars().unwrap()),
1793        _ => ::rustc_span::macros::bug_impl(None, format_args!("invalid args"),
    Location::caller())bug!("invalid args"),
1794    };
1795
1796    let fn_diff = match Instance::try_resolve(tcx, bx.cx.typing_env(), *diff_id, diff_args) {
1797        Ok(Some(instance)) => instance,
1798        Ok(None) => ::rustc_span::macros::bug_impl(None,
    format_args!("could not resolve ({0:?}, {1:?}) to a specific autodiff instance",
        diff_id, diff_args), Location::caller())bug!(
1799            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1800            diff_id,
1801            diff_args
1802        ),
1803        Err(err) => {
1804            // An error has already been emitted
1805            return IntrinsicResult::Err(err);
1806        }
1807    };
1808
1809    let val_arr = get_args_from_tuple(bx, args[2], fn_diff);
1810    let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff, LOCAL_CRATE);
1811
1812    let Some(Some(mut diff_attrs)) =
1813        {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(fn_diff.def_id(), &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcAutodiff(attr)) => {
                        break 'done Some(attr.clone());
                    }
                    ::rustc_attr_ir::Attribute::Tool(..) |
                        ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, fn_diff.def_id(), RustcAutodiff(attr) => attr.clone())
1814    else {
1815        ::rustc_span::macros::bug_impl(None,
    format_args!("could not find autodiff attrs"), Location::caller())bug!("could not find autodiff attrs")
1816    };
1817
1818    adjust_activity_to_abi(
1819        tcx,
1820        source_fn_ptr_ty,
1821        bx.cx.typing_env(),
1822        &mut diff_attrs.input_activity,
1823    );
1824
1825    let fnc_tree = fnc_typetrees(tcx, source_fn_ptr_ty);
1826
1827    // Build body
1828    generate_enzyme_call(
1829        bx,
1830        fn_to_diff,
1831        &diff_symbol,
1832        llret_ty,
1833        &val_arr,
1834        &diff_attrs,
1835        result_layout,
1836        result_place,
1837        fnc_tree,
1838    )
1839}
1840
1841// Generates the LLVM code to offload a Rust function to a target device (e.g., GPU).
1842// For each kernel call, it generates the necessary globals (including metadata such as
1843// size and pass mode), manages memory mapping to and from the device, handles all
1844// data transfers, and launches the kernel on the target device.
1845fn codegen_offload<'ll, 'tcx>(
1846    bx: &mut Builder<'_, 'll, 'tcx>,
1847    tcx: TyCtxt<'tcx>,
1848    instance: ty::Instance<'tcx>,
1849    args: &[OperandRef<'tcx, Value<'ll>>],
1850) {
1851    let cx = bx.cx;
1852    let fn_args = instance.args;
1853
1854    let (target_id, target_args) = match fn_args.into_type_list(tcx)[0].kind() {
1855        ty::FnDef(def_id, params) => (def_id, params.no_bound_vars().unwrap()),
1856        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("invalid offload intrinsic arg"), Location::caller())bug!("invalid offload intrinsic arg"),
1857    };
1858
1859    let fn_target = match Instance::try_resolve(tcx, cx.typing_env(), *target_id, target_args) {
1860        Ok(Some(instance)) => instance,
1861        Ok(None) => ::rustc_span::macros::bug_impl(None,
    format_args!("could not resolve ({0:?}, {1:?}) to a specific offload instance",
        target_id, target_args), Location::caller())bug!(
1862            "could not resolve ({:?}, {:?}) to a specific offload instance",
1863            target_id,
1864            target_args
1865        ),
1866        Err(_) => {
1867            // An error has already been emitted
1868            return;
1869        }
1870    };
1871
1872    let offload_dims = OffloadKernelDims::from_operands(bx, &args[1], &args[2]);
1873    let dyn_cache = match args[3].val {
1874        OperandValue::Immediate(val) => val,
1875        _ => { ::core::panicking::panic_fmt(format_args!("unparsable")); }panic!("unparsable"),
1876    };
1877    let device_id = match args[4].val {
1878        OperandValue::Immediate(val) => val,
1879        _ => { ::core::panicking::panic_fmt(format_args!("unparsable")); }panic!("unparsable"),
1880    };
1881    let args = get_args_from_tuple(bx, args[5], fn_target);
1882    let target_symbol = mangle_offload_export(tcx, fn_target);
1883
1884    let sig = tcx.fn_sig(fn_target.def_id()).instantiate(tcx, fn_target.args).skip_norm_wip();
1885    let sig = tcx.instantiate_bound_regions_with_erased(sig);
1886    let inputs = sig.inputs();
1887
1888    let fn_abi = cx.fn_abi_of_instance(fn_target, ty::List::empty());
1889
1890    let mut metadata = Vec::new();
1891    let mut types = Vec::new();
1892
1893    for (i, arg_abi) in fn_abi.args.iter().enumerate() {
1894        let ty = inputs[i];
1895        let decomposed = OffloadMetadata::handle_abi(cx, tcx, ty, arg_abi);
1896
1897        for (meta, entry_ty) in decomposed {
1898            metadata.push(meta);
1899            types.push(bx.cx.layout_of(entry_ty).llvm_type(bx.cx));
1900        }
1901    }
1902
1903    let offload_globals_ref = cx.offload_globals.borrow();
1904    let offload_globals = match offload_globals_ref.as_ref() {
1905        Some(globals) => globals,
1906        None => {
1907            // Offload is not initialized, cannot continue
1908            return;
1909        }
1910    };
1911    let offload_data =
1912        gpu_offload::gen_define_handling(cx, &metadata, target_symbol, offload_globals);
1913    gpu_offload::gen_call_handling(
1914        bx,
1915        &offload_data,
1916        &args,
1917        &types,
1918        &metadata,
1919        offload_globals,
1920        &offload_dims,
1921        dyn_cache,
1922        device_id,
1923    );
1924}
1925
1926fn get_args_from_tuple<'ll, 'tcx>(
1927    bx: &mut Builder<'_, 'll, 'tcx>,
1928    tuple_op: OperandRef<'tcx, Value<'ll>>,
1929    fn_instance: Instance<'tcx>,
1930) -> Vec<Value<'ll>> {
1931    let cx = bx.cx;
1932    let fn_abi = cx.fn_abi_of_instance(fn_instance, ty::List::empty());
1933
1934    match tuple_op.val {
1935        OperandValue::Immediate(val) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [val]))vec![val],
1936        OperandValue::Pair(v1, v2) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v1, v2]))vec![v1, v2],
1937        OperandValue::Ref(ptr) => {
1938            let tuple_place = PlaceRef { val: ptr, layout: tuple_op.layout };
1939
1940            let mut result = Vec::with_capacity(fn_abi.args.len());
1941            let mut tuple_index = 0;
1942
1943            for arg in &fn_abi.args {
1944                match arg.mode {
1945                    PassMode::Ignore => {}
1946                    PassMode::Direct(_) | PassMode::Cast { .. } => {
1947                        let field = tuple_place.project_field(bx, tuple_index);
1948                        let llvm_ty = field.layout.llvm_type(bx.cx);
1949                        let val = bx.load(llvm_ty, field.val.llval, field.val.align);
1950                        result.push(val);
1951                        tuple_index += 1;
1952                    }
1953                    PassMode::Pair(_, _) => {
1954                        let field = tuple_place.project_field(bx, tuple_index);
1955                        let llvm_ty = field.layout.llvm_type(bx.cx);
1956                        let pair_val = bx.load(llvm_ty, field.val.llval, field.val.align);
1957                        result.push(bx.extract_value(pair_val, 0));
1958                        result.push(bx.extract_value(pair_val, 1));
1959                        tuple_index += 1;
1960                    }
1961                    PassMode::Indirect { .. } => {
1962                        let field = tuple_place.project_field(bx, tuple_index);
1963                        result.push(field.val.llval);
1964                        tuple_index += 1;
1965                    }
1966                    PassMode::IndirectUnsized { .. } => {
1967                        ::rustc_span::macros::bug_impl(None,
    format_args!("autodiff/offload args must not be unsized"),
    Location::caller());bug!("autodiff/offload args must not be unsized");
1968                    }
1969                }
1970            }
1971
1972            result
1973        }
1974
1975        OperandValue::ZeroSized => ::alloc::vec::Vec::new()vec![],
1976    }
1977}
1978
1979fn generic_simd_intrinsic<'ll, 'tcx>(
1980    bx: &mut Builder<'_, 'll, 'tcx>,
1981    name: Symbol,
1982    fn_args: GenericArgs<'tcx>,
1983    args: &[OperandRef<'tcx, Value<'ll>>],
1984    ret_ty: Ty<'tcx>,
1985    llret_ty: Type<'ll>,
1986    span: Span,
1987) -> Result<Value<'ll>, ErrorGuaranteed> {
1988    macro_rules! return_error {
1989        ($diag: expr) => {{
1990            let err = bx.sess().dcx().emit_err($diag);
1991            return Err(err);
1992        }};
1993    }
1994
1995    macro_rules! require {
1996        ($cond: expr, $diag: expr) => {
1997            if !$cond {
1998                return_error!($diag);
1999            }
2000        };
2001    }
2002
2003    macro_rules! require_simd {
2004        ($ty: expr, $variant:ident) => {{
2005            require!($ty.is_simd(), InvalidMonomorphization::$variant { span, name, ty: $ty });
2006            $ty.simd_size_and_type(bx.tcx())
2007        }};
2008    }
2009
2010    macro_rules! require_simd_or_scalable {
2011        ($ty: expr, $variant:ident) => {{
2012            require!(
2013                $ty.is_simd() || $ty.is_scalable_vector(),
2014                InvalidMonomorphization::$variant { span, name, ty: $ty }
2015            );
2016            if $ty.is_simd() {
2017                let (len, ty) = $ty.simd_size_and_type(bx.tcx());
2018                (len, ty, None)
2019            } else {
2020                let (count, ty, num_vecs) =
2021                    $ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
2022                (count as u64, ty, Some(num_vecs))
2023            }
2024        }};
2025    }
2026
2027    /// Returns the bitwidth of the `$ty` argument if it is an `Int` or `Uint` type.
2028    macro_rules! require_int_or_uint_ty {
2029        ($ty: expr, $diag: expr) => {
2030            match $ty {
2031                ty::Int(i) => {
2032                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2033                }
2034                ty::Uint(i) => {
2035                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2036                }
2037                _ => {
2038                    return_error!($diag);
2039                }
2040            }
2041        };
2042    }
2043
2044    /// Converts a vector mask, where each element has a bit width equal to the data elements it is used with,
2045    /// down to an i1 based mask that can be used by llvm intrinsics.
2046    ///
2047    /// The rust simd semantics are that each element should either consist of all ones or all zeroes,
2048    /// but this information is not available to llvm. Truncating the vector effectively uses the lowest bit,
2049    /// but codegen for several targets is better if we consider the highest bit by shifting.
2050    ///
2051    /// For x86 SSE/AVX targets this is beneficial since most instructions with mask parameters only consider the highest bit.
2052    /// So even though on llvm level we have an additional shift, in the final assembly there is no shift or truncate and
2053    /// instead the mask can be used as is.
2054    ///
2055    /// For aarch64 and other targets there is a benefit because a mask from the sign bit can be more
2056    /// efficiently converted to an all ones / all zeroes mask by comparing whether each element is negative.
2057    fn vector_mask_to_bitmask<'a, 'll, 'tcx>(
2058        bx: &mut Builder<'a, 'll, 'tcx>,
2059        i_xn: Value<'ll>,
2060        in_elem_bitwidth: u64,
2061        in_len: u64,
2062    ) -> Value<'ll> {
2063        // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
2064        let shift_idx = bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
2065        let shift_indices = ::alloc::vec::from_elem_global(shift_idx, in_len as _)vec![shift_idx; in_len as _];
2066        let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
2067        // Truncate vector to an <i1 x N>
2068        bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len))
2069    }
2070
2071    // Sanity-check: all vector arguments must be immediates.
2072    if truecfg!(debug_assertions) {
2073        for arg in args {
2074            if arg.layout.ty.is_simd() {
2075                {
    match arg.val {
        OperandValue::Immediate(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "OperandValue::Immediate(_)", ::core::option::Option::None);
        }
    }
};assert_matches!(arg.val, OperandValue::Immediate(_));
2076            }
2077        }
2078    }
2079
2080    if name == sym::simd_select_bitmask {
2081        let (len, _) = {
    if !args[1].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdArgument {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdArgument);
2082
2083        let expected_int_bits = len.max(8).next_power_of_two();
2084        let expected_bytes = len.div_ceil(8);
2085
2086        let mask_ty = args[0].layout.ty;
2087        let mask = match mask_ty.kind() {
2088            ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2089            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2090            ty::Array(elem, len)
2091                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2092                    && len
2093                        .try_to_target_usize(bx.tcx)
2094                        .expect("expected monomorphic const in codegen")
2095                        == expected_bytes =>
2096            {
2097                let place = PlaceRef::alloca(bx, args[0].layout);
2098                args[0].val.store(bx, place);
2099                let int_ty = bx.type_ix(expected_bytes * 8);
2100                bx.load(int_ty, place.val.llval, Align::ONE)
2101            }
2102            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::InvalidBitmask {
                span,
                name,
                mask_ty,
                expected_int_bits,
                expected_bytes,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::InvalidBitmask {
2103                span,
2104                name,
2105                mask_ty,
2106                expected_int_bits,
2107                expected_bytes
2108            }),
2109        };
2110
2111        let i1 = bx.type_i1();
2112        let im = bx.type_ix(len);
2113        let i1xn = bx.type_vector(i1, len);
2114        let m_im = bx.trunc(mask, im);
2115        let m_i1s = bx.bitcast(m_im, i1xn);
2116        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2117    }
2118
2119    if name == sym::simd_splat {
2120        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2121
2122        if !(args[0].layout.ty == out_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedVectorElementType {
                    span,
                    name,
                    expected_element: out_ty,
                    vector_type: ret_ty,
                });
        return Err(err);
    };
};require!(
2123            args[0].layout.ty == out_ty,
2124            InvalidMonomorphization::ExpectedVectorElementType {
2125                span,
2126                name,
2127                expected_element: out_ty,
2128                vector_type: ret_ty,
2129            }
2130        );
2131
2132        // `insertelement <N x elem> poison, elem %x, i32 0`
2133        let poison_vec = bx.const_poison(llret_ty);
2134        let idx0 = bx.const_i32(0);
2135        let v0 = bx.insert_element(poison_vec, args[0].immediate(), idx0);
2136
2137        // `shufflevector <N x elem> v0, <N x elem> poison, <N x i32> zeroinitializer`
2138        // The masks is all zeros, so this splats lane 0 (which has our element in it).
2139        let mask_ty = bx.type_vector(bx.type_i32(), out_len);
2140        let splat = bx.shuffle_vector(v0, poison_vec, bx.const_null(mask_ty));
2141
2142        return Ok(splat);
2143    }
2144
2145    let supports_scalable = #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_cast | sym::simd_select => true,
    _ => false,
}matches!(name, sym::simd_cast | sym::simd_select);
2146
2147    // Every intrinsic below takes a SIMD vector as its first argument. Some intrinsics also accept
2148    // scalable vectors. `require_simd_or_scalable` is used regardless as it'll do the right thing
2149    // for non-scalable vectors, and an additional check to prohibit scalable vectors for those
2150    // intrinsics that do not support them is added.
2151    if !supports_scalable {
2152        let _ = {
    if !args[0].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdInput {
                        span,
                        name,
                        ty: args[0].layout.ty,
                    });
            return Err(err);
        };
    };
    args[0].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[0].layout.ty, SimdInput);
2153    }
2154    let (in_len, in_elem, in_num_vecs) = {
    if !(args[0].layout.ty.is_simd() ||
                args[0].layout.ty.is_scalable_vector()) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdInput {
                        span,
                        name,
                        ty: args[0].layout.ty,
                    });
            return Err(err);
        };
    };
    if args[0].layout.ty.is_simd() {
        let (len, ty) = args[0].layout.ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            args[0].layout.ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(args[0].layout.ty, SimdInput);
2155    let in_ty = args[0].layout.ty;
2156
2157    let comparison = match name {
2158        sym::simd_eq => Some(BinOp::Eq),
2159        sym::simd_ne => Some(BinOp::Ne),
2160        sym::simd_lt => Some(BinOp::Lt),
2161        sym::simd_le => Some(BinOp::Le),
2162        sym::simd_gt => Some(BinOp::Gt),
2163        sym::simd_ge => Some(BinOp::Ge),
2164        _ => None,
2165    };
2166
2167    if let Some(cmp_op) = comparison {
2168        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2169
2170        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2171            in_len == out_len,
2172            InvalidMonomorphization::ReturnLengthInputType {
2173                span,
2174                name,
2175                in_len,
2176                in_ty,
2177                ret_ty,
2178                out_len
2179            }
2180        );
2181        if !bx.vector_element_type(llret_ty).is_some_and(|elem|
                bx.int_width(elem).is_some()) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnIntegerType {
                    span,
                    name,
                    ret_ty,
                    out_ty,
                });
        return Err(err);
    };
};require!(
2182            bx.vector_element_type(llret_ty).is_some_and(|elem| bx.int_width(elem).is_some()),
2183            InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty }
2184        );
2185
2186        return Ok(compare_simd_types(
2187            bx,
2188            args[0].immediate(),
2189            args[1].immediate(),
2190            in_elem,
2191            llret_ty,
2192            cmp_op,
2193        ));
2194    }
2195
2196    if name == sym::simd_shuffle_const_generic {
2197        let idx = fn_args[2].expect_const().to_branch();
2198        let n = idx.len() as u64;
2199
2200        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2201        if !(out_len == n) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLength {
                    span,
                    name,
                    in_len: n,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2202            out_len == n,
2203            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2204        );
2205        if !(in_elem == out_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnElement {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                    out_ty,
                });
        return Err(err);
    };
};require!(
2206            in_elem == out_ty,
2207            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2208        );
2209
2210        let total_len = in_len * 2;
2211
2212        let indices: Option<Vec<_>> = idx
2213            .iter()
2214            .enumerate()
2215            .map(|(arg_idx, val)| {
2216                let idx = val.to_leaf().to_i32();
2217                if idx >= i32::try_from(total_len).unwrap() {
2218                    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
2219                        span,
2220                        name,
2221                        arg_idx: arg_idx as u64,
2222                        total_len: total_len.into(),
2223                    });
2224                    None
2225                } else {
2226                    Some(bx.const_i32(idx))
2227                }
2228            })
2229            .collect();
2230        let Some(indices) = indices else {
2231            return Ok(bx.const_null(llret_ty));
2232        };
2233
2234        return Ok(bx.shuffle_vector(
2235            args[0].immediate(),
2236            args[1].immediate(),
2237            bx.const_vector(&indices),
2238        ));
2239    }
2240
2241    if name == sym::simd_shuffle {
2242        // Make sure this is actually a SIMD vector.
2243        let idx_ty = args[2].layout.ty;
2244        let n: u64 = if idx_ty.is_simd()
2245            && #[allow(non_exhaustive_omitted_patterns)] match idx_ty.simd_size_and_type(bx.cx.tcx).1.kind()
    {
    ty::Uint(ty::UintTy::U32) => true,
    _ => false,
}matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
2246        {
2247            idx_ty.simd_size_and_type(bx.cx.tcx).0
2248        } else {
2249            {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdShuffle {
                span,
                name,
                ty: idx_ty,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
2250        };
2251
2252        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2253        if !(out_len == n) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLength {
                    span,
                    name,
                    in_len: n,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2254            out_len == n,
2255            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2256        );
2257        if !(in_elem == out_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnElement {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                    out_ty,
                });
        return Err(err);
    };
};require!(
2258            in_elem == out_ty,
2259            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2260        );
2261
2262        let total_len = u128::from(in_len) * 2;
2263
2264        // Check that the indices are in-bounds.
2265        let indices = args[2].immediate();
2266        for i in 0..n {
2267            let val = bx.const_get_elt(indices, i);
2268            let idx = bx
2269                .const_to_opt_u128(val, true)
2270                .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("typeck should have already ensured that these are const"),
    Location::caller())bug!("typeck should have already ensured that these are const"));
2271            if idx >= total_len {
2272                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: i,
                total_len,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2273                    span,
2274                    name,
2275                    arg_idx: i,
2276                    total_len,
2277                });
2278            }
2279        }
2280
2281        return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
2282    }
2283
2284    if name == sym::simd_insert || name == sym::simd_insert_dyn {
2285        if !(in_elem == args[2].layout.ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::InsertedType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    out_ty: args[2].layout.ty,
                });
        return Err(err);
    };
};require!(
2286            in_elem == args[2].layout.ty,
2287            InvalidMonomorphization::InsertedType {
2288                span,
2289                name,
2290                in_elem,
2291                in_ty,
2292                out_ty: args[2].layout.ty
2293            }
2294        );
2295
2296        let index_imm = if name == sym::simd_insert {
2297            let idx = bx
2298                .const_to_opt_u128(args[1].immediate(), false)
2299                .expect("typeck should have ensure that this is a const");
2300            if idx >= in_len.into() {
2301                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: 1,
                total_len: in_len.into(),
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2302                    span,
2303                    name,
2304                    arg_idx: 1,
2305                    total_len: in_len.into(),
2306                });
2307            }
2308            bx.const_i32(idx as i32)
2309        } else {
2310            args[1].immediate()
2311        };
2312
2313        return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), index_imm));
2314    }
2315    if name == sym::simd_extract || name == sym::simd_extract_dyn {
2316        if !(ret_ty == in_elem) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2317            ret_ty == in_elem,
2318            InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2319        );
2320        let index_imm = if name == sym::simd_extract {
2321            let idx = bx
2322                .const_to_opt_u128(args[1].immediate(), false)
2323                .expect("typeck should have ensure that this is a const");
2324            if idx >= in_len.into() {
2325                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: 1,
                total_len: in_len.into(),
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2326                    span,
2327                    name,
2328                    arg_idx: 1,
2329                    total_len: in_len.into(),
2330                });
2331            }
2332            bx.const_i32(idx as i32)
2333        } else {
2334            args[1].immediate()
2335        };
2336
2337        return Ok(bx.extract_element(args[0].immediate(), index_imm));
2338    }
2339
2340    if name == sym::simd_select {
2341        let m_elem_ty = in_elem;
2342        let m_len = in_len;
2343        let (v_len, _, _) = {
    if !(args[1].layout.ty.is_simd() ||
                args[1].layout.ty.is_scalable_vector()) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdArgument {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    if args[1].layout.ty.is_simd() {
        let (len, ty) = args[1].layout.ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            args[1].layout.ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(args[1].layout.ty, SimdArgument);
2344        if !(m_len == v_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::MismatchedLengths {
                    span,
                    name,
                    m_len,
                    v_len,
                });
        return Err(err);
    };
};require!(
2345            m_len == v_len,
2346            InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len }
2347        );
2348
2349        let m_i1s = if args[1].layout.ty.is_scalable_vector() {
2350            match m_elem_ty.kind() {
2351                ty::Bool => {}
2352                _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                span,
                name,
                ty: m_elem_ty,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::MaskWrongElementType {
2353                    span,
2354                    name,
2355                    ty: m_elem_ty
2356                }),
2357            };
2358            let i1 = bx.type_i1();
2359            let i1xn = bx.type_scalable_vector(i1, m_len);
2360            bx.trunc(args[0].immediate(), i1xn)
2361        } else {
2362            let in_elem_bitwidth = match m_elem_ty.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: m_elem_ty,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2363                m_elem_ty.kind(),
2364                InvalidMonomorphization::MaskWrongElementType { span, name, ty: m_elem_ty }
2365            );
2366            vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len)
2367        };
2368
2369        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2370    }
2371
2372    if name == sym::simd_bitmask {
2373        // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a vector mask and
2374        // returns one bit for each lane (which must all be `0` or `!0`) in the form of either:
2375        // * an unsigned integer
2376        // * an array of `u8`
2377        // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
2378        //
2379        // The bit order of the result depends on the byte endianness, LSB-first for little
2380        // endian and MSB-first for big endian.
2381        let expected_int_bits = in_len.max(8).next_power_of_two();
2382        let expected_bytes = in_len.div_ceil(8);
2383
2384        // Integer vector <i{in_bitwidth} x in_len>:
2385        let in_elem_bitwidth = match in_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: in_elem,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2386            in_elem.kind(),
2387            InvalidMonomorphization::MaskWrongElementType { span, name, ty: in_elem }
2388        );
2389
2390        let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len);
2391        // Bitcast <i1 x N> to iN:
2392        let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
2393
2394        match ret_ty.kind() {
2395            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
2396                // Zero-extend iN to the bitmask type:
2397                return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
2398            }
2399            ty::Array(elem, len)
2400                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2401                    && len
2402                        .try_to_target_usize(bx.tcx)
2403                        .expect("expected monomorphic const in codegen")
2404                        == expected_bytes =>
2405            {
2406                // Zero-extend iN to the array length:
2407                let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
2408
2409                // Convert the integer to a byte array
2410                let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE);
2411                bx.store(ze, ptr, Align::ONE);
2412                let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
2413                return Ok(bx.load(array_ty, ptr, Align::ONE));
2414            }
2415            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::CannotReturn {
                span,
                name,
                ret_ty,
                expected_int_bits,
                expected_bytes,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::CannotReturn {
2416                span,
2417                name,
2418                ret_ty,
2419                expected_int_bits,
2420                expected_bytes
2421            }),
2422        }
2423    }
2424
2425    fn simd_simple_float_intrinsic<'ll, 'tcx>(
2426        name: Symbol,
2427        in_elem: Ty<'_>,
2428        in_ty: Ty<'_>,
2429        in_len: u64,
2430        bx: &mut Builder<'_, 'll, 'tcx>,
2431        span: Span,
2432        args: &[OperandRef<'tcx, Value<'ll>>],
2433    ) -> Result<Value<'ll>, ErrorGuaranteed> {
2434        macro_rules! return_error {
2435            ($diag: expr) => {{
2436                let err = bx.sess().dcx().emit_err($diag);
2437                return Err(err);
2438            }};
2439        }
2440
2441        let ty::Float(f) = in_elem.kind() else {
2442            {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
                span,
                name,
                ty: in_ty,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty });
2443        };
2444        let elem_ty = bx.cx.type_float_from_ty(*f);
2445
2446        let vec_ty = bx.type_vector(elem_ty, in_len);
2447
2448        let intr_name = match name {
2449            sym::simd_ceil => "llvm.ceil",
2450            sym::simd_fabs => "llvm.fabs",
2451            sym::simd_fcos => "llvm.cos",
2452            sym::simd_fexp2 => "llvm.exp2",
2453            sym::simd_fexp => "llvm.exp",
2454            sym::simd_flog10 => "llvm.log10",
2455            sym::simd_flog2 => "llvm.log2",
2456            sym::simd_flog => "llvm.log",
2457            sym::simd_floor => "llvm.floor",
2458            sym::simd_fma => "llvm.fma",
2459            sym::simd_relaxed_fma => "llvm.fmuladd",
2460            sym::simd_fsin => "llvm.sin",
2461            sym::simd_fsqrt => "llvm.sqrt",
2462            sym::simd_round => "llvm.round",
2463            sym::simd_round_ties_even => "llvm.rint",
2464            sym::simd_trunc => "llvm.trunc",
2465            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnrecognizedIntrinsic {
                span,
                name,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
2466        };
2467        Ok(bx.call_intrinsic(
2468            intr_name,
2469            &[vec_ty],
2470            &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
2471        ))
2472    }
2473
2474    if #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_ceil | sym::simd_fabs | sym::simd_fcos | sym::simd_fexp2 |
        sym::simd_fexp | sym::simd_flog10 | sym::simd_flog2 | sym::simd_flog |
        sym::simd_floor | sym::simd_fma | sym::simd_fsin | sym::simd_fsqrt |
        sym::simd_relaxed_fma | sym::simd_round | sym::simd_round_ties_even |
        sym::simd_trunc => true,
    _ => false,
}std::matches!(
2475        name,
2476        sym::simd_ceil
2477            | sym::simd_fabs
2478            | sym::simd_fcos
2479            | sym::simd_fexp2
2480            | sym::simd_fexp
2481            | sym::simd_flog10
2482            | sym::simd_flog2
2483            | sym::simd_flog
2484            | sym::simd_floor
2485            | sym::simd_fma
2486            | sym::simd_fsin
2487            | sym::simd_fsqrt
2488            | sym::simd_relaxed_fma
2489            | sym::simd_round
2490            | sym::simd_round_ties_even
2491            | sym::simd_trunc
2492    ) {
2493        return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
2494    }
2495
2496    fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) -> Type<'ll> {
2497        let elem_ty = match *elem_ty.kind() {
2498            ty::Int(v) => cx.type_int_from_ty(v),
2499            ty::Uint(v) => cx.type_uint_from_ty(v),
2500            ty::Float(v) => cx.type_float_from_ty(v),
2501            ty::RawPtr(_, _) => cx.type_ptr(),
2502            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2503        };
2504        cx.type_vector(elem_ty, vec_len)
2505    }
2506
2507    if name == sym::simd_gather {
2508        // simd_gather(values: <N x T>, pointers: <N x *_ T>,
2509        //             mask: <N x i{M}>) -> <N x T>
2510        // * N: number of elements in the input vectors
2511        // * T: type of the element to load
2512        // * M: any integer width is supported, will be truncated to i1
2513
2514        // All types must be simd vector types
2515
2516        // The second argument must be a simd vector with an element type that's a pointer
2517        // to the element type of the first argument
2518        let (_, element_ty0) = {
    if !in_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdFirst {
                        span,
                        name,
                        ty: in_ty,
                    });
            return Err(err);
        };
    };
    in_ty.simd_size_and_type(bx.tcx())
}require_simd!(in_ty, SimdFirst);
2519        let (out_len, element_ty1) = {
    if !args[1].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdSecond {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdSecond);
2520        // The element type of the third argument must be a signed integer type of any width:
2521        let (out_len2, element_ty2) = {
    if !args[2].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: args[2].layout.ty,
                    });
            return Err(err);
        };
    };
    args[2].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[2].layout.ty, SimdThird);
2522        {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
};require_simd!(ret_ty, SimdReturn);
2523
2524        // Of the same length:
2525        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::SecondArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[1].layout.ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2526            in_len == out_len,
2527            InvalidMonomorphization::SecondArgumentLength {
2528                span,
2529                name,
2530                in_len,
2531                in_ty,
2532                arg_ty: args[1].layout.ty,
2533                out_len
2534            }
2535        );
2536        if !(in_len == out_len2) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[2].layout.ty,
                    out_len: out_len2,
                });
        return Err(err);
    };
};require!(
2537            in_len == out_len2,
2538            InvalidMonomorphization::ThirdArgumentLength {
2539                span,
2540                name,
2541                in_len,
2542                in_ty,
2543                arg_ty: args[2].layout.ty,
2544                out_len: out_len2
2545            }
2546        );
2547
2548        // The return type must match the first argument type
2549        if !(ret_ty == in_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                    span,
                    name,
                    in_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2550            ret_ty == in_ty,
2551            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty }
2552        );
2553
2554        if !#[allow(non_exhaustive_omitted_patterns)] match *element_ty1.kind() {
            ty::RawPtr(p_ty, _) if
                p_ty == in_elem && p_ty.kind() == element_ty0.kind() => true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: element_ty1,
                    second_arg: args[1].layout.ty,
                    in_elem,
                    in_ty,
                    mutability: ExpectedPointerMutability::Not,
                });
        return Err(err);
    };
};require!(
2555            matches!(
2556                *element_ty1.kind(),
2557                ty::RawPtr(p_ty, _) if p_ty == in_elem && p_ty.kind() == element_ty0.kind()
2558            ),
2559            InvalidMonomorphization::ExpectedElementType {
2560                span,
2561                name,
2562                expected_element: element_ty1,
2563                second_arg: args[1].layout.ty,
2564                in_elem,
2565                in_ty,
2566                mutability: ExpectedPointerMutability::Not,
2567            }
2568        );
2569
2570        let mask_elem_bitwidth = match element_ty2.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: element_ty2,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2571            element_ty2.kind(),
2572            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2573        );
2574
2575        // Alignment of T, must be a constant integer value:
2576        let alignment = bx.align_of(in_elem).bytes();
2577
2578        // Truncate the mask vector to a vector of i1s:
2579        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2580
2581        // Type of the vector of pointers:
2582        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2583
2584        // Type of the vector of elements:
2585        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2586
2587        let call = bx.call_intrinsic(
2588            "llvm.masked.gather",
2589            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2590            &[args[1].immediate(), mask, args[0].immediate()],
2591        );
2592        crate::attributes::apply_to_callsite(
2593            call,
2594            crate::llvm::AttributePlace::Argument(0),
2595            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2596        );
2597        return Ok(call);
2598    }
2599
2600    fn llvm_alignment<'ll, 'tcx>(
2601        bx: &mut Builder<'_, 'll, 'tcx>,
2602        alignment: SimdAlign,
2603        vector_ty: Ty<'tcx>,
2604        element_ty: Ty<'tcx>,
2605    ) -> u64 {
2606        match alignment {
2607            SimdAlign::Unaligned => 1,
2608            SimdAlign::Element => bx.align_of(element_ty).bytes(),
2609            SimdAlign::Vector => bx.align_of(vector_ty).bytes(),
2610        }
2611    }
2612
2613    if name == sym::simd_masked_load {
2614        // simd_masked_load<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *_ T, values: <N x T>) -> <N x T>
2615        // * N: number of elements in the input vectors
2616        // * T: type of the element to load
2617        // * M: any integer width is supported, will be truncated to i1
2618        // Loads contiguous elements from memory behind `pointer`, but only for
2619        // those lanes whose `mask` bit is enabled.
2620        // The memory addresses corresponding to the “off” lanes are not accessed.
2621
2622        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2623
2624        // The element type of the "mask" argument must be a signed integer type of any width
2625        let mask_ty = in_ty;
2626        let (mask_len, mask_elem) = (in_len, in_elem);
2627
2628        // The second argument must be a pointer matching the element type
2629        let pointer_ty = args[1].layout.ty;
2630
2631        // The last argument is a passthrough vector providing values for disabled lanes
2632        let values_ty = args[2].layout.ty;
2633        let (values_len, values_elem) = {
    if !values_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: values_ty,
                    });
            return Err(err);
        };
    };
    values_ty.simd_size_and_type(bx.tcx())
}require_simd!(values_ty, SimdThird);
2634
2635        {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
};require_simd!(ret_ty, SimdReturn);
2636
2637        // Of the same length:
2638        if !(values_len == mask_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len: mask_len,
                    in_ty: mask_ty,
                    arg_ty: values_ty,
                    out_len: values_len,
                });
        return Err(err);
    };
};require!(
2639            values_len == mask_len,
2640            InvalidMonomorphization::ThirdArgumentLength {
2641                span,
2642                name,
2643                in_len: mask_len,
2644                in_ty: mask_ty,
2645                arg_ty: values_ty,
2646                out_len: values_len
2647            }
2648        );
2649
2650        // The return type must match the last argument type
2651        if !(ret_ty == values_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                    span,
                    name,
                    in_ty: values_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2652            ret_ty == values_ty,
2653            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty }
2654        );
2655
2656        if !#[allow(non_exhaustive_omitted_patterns)] match *pointer_ty.kind() {
            ty::RawPtr(p_ty, _) if
                p_ty == values_elem && p_ty.kind() == values_elem.kind() =>
                true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: values_elem,
                    second_arg: pointer_ty,
                    in_elem: values_elem,
                    in_ty: values_ty,
                    mutability: ExpectedPointerMutability::Not,
                });
        return Err(err);
    };
};require!(
2657            matches!(
2658                *pointer_ty.kind(),
2659                ty::RawPtr(p_ty, _) if p_ty == values_elem && p_ty.kind() == values_elem.kind()
2660            ),
2661            InvalidMonomorphization::ExpectedElementType {
2662                span,
2663                name,
2664                expected_element: values_elem,
2665                second_arg: pointer_ty,
2666                in_elem: values_elem,
2667                in_ty: values_ty,
2668                mutability: ExpectedPointerMutability::Not,
2669            }
2670        );
2671
2672        let m_elem_bitwidth = match mask_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: mask_elem,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2673            mask_elem.kind(),
2674            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2675        );
2676
2677        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2678
2679        // Alignment of T, must be a constant integer value:
2680        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2681
2682        let llvm_pointer = bx.type_ptr();
2683
2684        // Type of the vector of elements:
2685        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2686
2687        let call = bx.call_intrinsic(
2688            "llvm.masked.load",
2689            &[llvm_elem_vec_ty, llvm_pointer],
2690            &[args[1].immediate(), mask, args[2].immediate()],
2691        );
2692        crate::attributes::apply_to_callsite(
2693            call,
2694            crate::llvm::AttributePlace::Argument(0),
2695            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2696        );
2697        return Ok(call);
2698    }
2699
2700    if name == sym::simd_masked_store {
2701        // simd_masked_store<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *mut T, values: <N x T>) -> ()
2702        // * N: number of elements in the input vectors
2703        // * T: type of the element to load
2704        // * M: any integer width is supported, will be truncated to i1
2705        // Stores contiguous elements to memory behind `pointer`, but only for
2706        // those lanes whose `mask` bit is enabled.
2707        // The memory addresses corresponding to the “off” lanes are not accessed.
2708
2709        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2710
2711        // The element type of the "mask" argument must be a signed integer type of any width
2712        let mask_ty = in_ty;
2713        let (mask_len, mask_elem) = (in_len, in_elem);
2714
2715        // The second argument must be a pointer matching the element type
2716        let pointer_ty = args[1].layout.ty;
2717
2718        // The last argument specifies the values to store to memory
2719        let values_ty = args[2].layout.ty;
2720        let (values_len, values_elem) = {
    if !values_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: values_ty,
                    });
            return Err(err);
        };
    };
    values_ty.simd_size_and_type(bx.tcx())
}require_simd!(values_ty, SimdThird);
2721
2722        // Of the same length:
2723        if !(values_len == mask_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len: mask_len,
                    in_ty: mask_ty,
                    arg_ty: values_ty,
                    out_len: values_len,
                });
        return Err(err);
    };
};require!(
2724            values_len == mask_len,
2725            InvalidMonomorphization::ThirdArgumentLength {
2726                span,
2727                name,
2728                in_len: mask_len,
2729                in_ty: mask_ty,
2730                arg_ty: values_ty,
2731                out_len: values_len
2732            }
2733        );
2734
2735        // The second argument must be a mutable pointer type matching the element type
2736        if !#[allow(non_exhaustive_omitted_patterns)] match *pointer_ty.kind() {
            ty::RawPtr(p_ty, p_mutbl) if
                p_ty == values_elem && p_ty.kind() == values_elem.kind() &&
                    p_mutbl.is_mut() => true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: values_elem,
                    second_arg: pointer_ty,
                    in_elem: values_elem,
                    in_ty: values_ty,
                    mutability: ExpectedPointerMutability::Mut,
                });
        return Err(err);
    };
};require!(
2737            matches!(
2738                *pointer_ty.kind(),
2739                ty::RawPtr(p_ty, p_mutbl)
2740                    if p_ty == values_elem && p_ty.kind() == values_elem.kind() && p_mutbl.is_mut()
2741            ),
2742            InvalidMonomorphization::ExpectedElementType {
2743                span,
2744                name,
2745                expected_element: values_elem,
2746                second_arg: pointer_ty,
2747                in_elem: values_elem,
2748                in_ty: values_ty,
2749                mutability: ExpectedPointerMutability::Mut,
2750            }
2751        );
2752
2753        let m_elem_bitwidth = match mask_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: mask_elem,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2754            mask_elem.kind(),
2755            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2756        );
2757
2758        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2759
2760        // Alignment of T, must be a constant integer value:
2761        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2762
2763        let llvm_pointer = bx.type_ptr();
2764
2765        // Type of the vector of elements:
2766        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2767
2768        let call = bx.call_intrinsic(
2769            "llvm.masked.store",
2770            &[llvm_elem_vec_ty, llvm_pointer],
2771            &[args[2].immediate(), args[1].immediate(), mask],
2772        );
2773        crate::attributes::apply_to_callsite(
2774            call,
2775            crate::llvm::AttributePlace::Argument(1),
2776            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2777        );
2778        return Ok(call);
2779    }
2780
2781    if name == sym::simd_scatter {
2782        // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
2783        //             mask: <N x i{M}>) -> ()
2784        // * N: number of elements in the input vectors
2785        // * T: type of the element to load
2786        // * M: any integer width is supported, will be truncated to i1
2787
2788        // All types must be simd vector types
2789        // The second argument must be a simd vector with an element type that's a pointer
2790        // to the element type of the first argument
2791        let (_, element_ty0) = {
    if !in_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdFirst {
                        span,
                        name,
                        ty: in_ty,
                    });
            return Err(err);
        };
    };
    in_ty.simd_size_and_type(bx.tcx())
}require_simd!(in_ty, SimdFirst);
2792        let (element_len1, element_ty1) = {
    if !args[1].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdSecond {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdSecond);
2793        let (element_len2, element_ty2) = {
    if !args[2].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: args[2].layout.ty,
                    });
            return Err(err);
        };
    };
    args[2].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[2].layout.ty, SimdThird);
2794
2795        // Of the same length:
2796        if !(in_len == element_len1) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::SecondArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[1].layout.ty,
                    out_len: element_len1,
                });
        return Err(err);
    };
};require!(
2797            in_len == element_len1,
2798            InvalidMonomorphization::SecondArgumentLength {
2799                span,
2800                name,
2801                in_len,
2802                in_ty,
2803                arg_ty: args[1].layout.ty,
2804                out_len: element_len1
2805            }
2806        );
2807        if !(in_len == element_len2) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[2].layout.ty,
                    out_len: element_len2,
                });
        return Err(err);
    };
};require!(
2808            in_len == element_len2,
2809            InvalidMonomorphization::ThirdArgumentLength {
2810                span,
2811                name,
2812                in_len,
2813                in_ty,
2814                arg_ty: args[2].layout.ty,
2815                out_len: element_len2
2816            }
2817        );
2818
2819        if !#[allow(non_exhaustive_omitted_patterns)] match *element_ty1.kind() {
            ty::RawPtr(p_ty, p_mutbl) if
                p_ty == in_elem && p_mutbl.is_mut() &&
                    p_ty.kind() == element_ty0.kind() => true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: element_ty1,
                    second_arg: args[1].layout.ty,
                    in_elem,
                    in_ty,
                    mutability: ExpectedPointerMutability::Mut,
                });
        return Err(err);
    };
};require!(
2820            matches!(
2821                *element_ty1.kind(),
2822                ty::RawPtr(p_ty, p_mutbl)
2823                    if p_ty == in_elem && p_mutbl.is_mut() && p_ty.kind() == element_ty0.kind()
2824            ),
2825            InvalidMonomorphization::ExpectedElementType {
2826                span,
2827                name,
2828                expected_element: element_ty1,
2829                second_arg: args[1].layout.ty,
2830                in_elem,
2831                in_ty,
2832                mutability: ExpectedPointerMutability::Mut,
2833            }
2834        );
2835
2836        // The element type of the third argument must be an integer type of any width:
2837        let mask_elem_bitwidth = match element_ty2.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: element_ty2,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2838            element_ty2.kind(),
2839            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2840        );
2841
2842        // Alignment of T, must be a constant integer value:
2843        let alignment = bx.align_of(in_elem).bytes();
2844
2845        // Truncate the mask vector to a vector of i1s:
2846        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2847
2848        // Type of the vector of pointers:
2849        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2850
2851        // Type of the vector of elements:
2852        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2853
2854        let call = bx.call_intrinsic(
2855            "llvm.masked.scatter",
2856            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2857            &[args[0].immediate(), args[1].immediate(), mask],
2858        );
2859        crate::attributes::apply_to_callsite(
2860            call,
2861            crate::llvm::AttributePlace::Argument(1),
2862            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2863        );
2864        return Ok(call);
2865    }
2866
2867    macro_rules! arith_red {
2868        ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
2869         $identity:expr) => {
2870            if name == sym::$name {
2871                require!(
2872                    ret_ty == in_elem,
2873                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2874                );
2875                return match in_elem.kind() {
2876                    ty::Int(_) | ty::Uint(_) => {
2877                        let r = bx.$integer_reduce(args[0].immediate());
2878                        if $ordered {
2879                            // if overflow occurs, the result is the
2880                            // mathematical result modulo 2^n:
2881                            Ok(bx.$op(args[1].immediate(), r))
2882                        } else {
2883                            Ok(bx.$integer_reduce(args[0].immediate()))
2884                        }
2885                    }
2886                    ty::Float(f) => {
2887                        let acc = if $ordered {
2888                            // ordered arithmetic reductions take an accumulator
2889                            args[1].immediate()
2890                        } else {
2891                            // unordered arithmetic reductions use the identity accumulator
2892                            match f.bit_width() {
2893                                32 => bx.const_real(bx.type_f32(), $identity),
2894                                64 => bx.const_real(bx.type_f64(), $identity),
2895                                v => return_error!(
2896                                    InvalidMonomorphization::UnsupportedSymbolOfSize {
2897                                        span,
2898                                        name,
2899                                        symbol: sym::$name,
2900                                        in_ty,
2901                                        in_elem,
2902                                        size: v,
2903                                        ret_ty
2904                                    }
2905                                ),
2906                            }
2907                        };
2908                        Ok(bx.$float_reduce(acc, args[0].immediate()))
2909                    }
2910                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2911                        span,
2912                        name,
2913                        symbol: sym::$name,
2914                        in_ty,
2915                        in_elem,
2916                        ret_ty
2917                    }),
2918                };
2919            }
2920        };
2921    }
2922
2923    if name == sym::simd_reduce_add_ordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_add(args[0].immediate());
                if true {
                    Ok(bx.add(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_add(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if true {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), -0.0),
                            64 => bx.const_real(bx.type_f64(), -0.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_add_ordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fadd(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_add_ordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, -0.0);
2924    if name == sym::simd_reduce_mul_ordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_mul(args[0].immediate());
                if true {
                    Ok(bx.mul(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_mul(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if true {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), 1.0),
                            64 => bx.const_real(bx.type_f64(), 1.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_mul_ordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fmul(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_mul_ordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
2925    if name == sym::simd_reduce_add_unordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_add(args[0].immediate());
                if false {
                    Ok(bx.add(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_add(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if false {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), -0.0),
                            64 => bx.const_real(bx.type_f64(), -0.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_add_unordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fadd_reassoc(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_add_unordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(
2926        simd_reduce_add_unordered: vector_reduce_add,
2927        vector_reduce_fadd_reassoc,
2928        false,
2929        add,
2930        -0.0
2931    );
2932    if name == sym::simd_reduce_mul_unordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_mul(args[0].immediate());
                if false {
                    Ok(bx.mul(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_mul(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if false {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), 1.0),
                            64 => bx.const_real(bx.type_f64(), 1.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_mul_unordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fmul_reassoc(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_mul_unordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(
2933        simd_reduce_mul_unordered: vector_reduce_mul,
2934        vector_reduce_fmul_reassoc,
2935        false,
2936        mul,
2937        1.0
2938    );
2939
2940    macro_rules! minmax_red {
2941        ($name:ident: $int_red:ident) => {
2942            if name == sym::$name {
2943                require!(
2944                    ret_ty == in_elem,
2945                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2946                );
2947                return match in_elem.kind() {
2948                    ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
2949                    ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
2950                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2951                        span,
2952                        name,
2953                        symbol: sym::$name,
2954                        in_ty,
2955                        in_elem,
2956                        ret_ty
2957                    }),
2958                };
2959            }
2960        };
2961    }
2962
2963    // Currently no support for float due to <https://github.com/llvm/llvm-project/issues/185827>.
2964    if name == sym::simd_reduce_min {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_i) =>
                Ok(bx.vector_reduce_min(args[0].immediate(), true)),
            ty::Uint(_u) =>
                Ok(bx.vector_reduce_min(args[0].immediate(), false)),
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_min,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};minmax_red!(simd_reduce_min: vector_reduce_min);
2965    if name == sym::simd_reduce_max {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_i) =>
                Ok(bx.vector_reduce_max(args[0].immediate(), true)),
            ty::Uint(_u) =>
                Ok(bx.vector_reduce_max(args[0].immediate(), false)),
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_max,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};minmax_red!(simd_reduce_max: vector_reduce_max);
2966
2967    macro_rules! bitwise_red {
2968        ($name:ident : $red:ident, $boolean:expr) => {
2969            if name == sym::$name {
2970                let input = if !$boolean {
2971                    require!(
2972                        ret_ty == in_elem,
2973                        InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2974                    );
2975                    args[0].immediate()
2976                } else {
2977                    let bitwidth = match in_elem.kind() {
2978                        ty::Int(i) => {
2979                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2980                        }
2981                        ty::Uint(i) => {
2982                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2983                        }
2984                        _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2985                            span,
2986                            name,
2987                            symbol: sym::$name,
2988                            in_ty,
2989                            in_elem,
2990                            ret_ty
2991                        }),
2992                    };
2993
2994                    vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth, in_len as _)
2995                };
2996                return match in_elem.kind() {
2997                    ty::Int(_) | ty::Uint(_) => {
2998                        let r = bx.$red(input);
2999                        Ok(r)
3000                    }
3001                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3002                        span,
3003                        name,
3004                        symbol: sym::$name,
3005                        in_ty,
3006                        in_elem,
3007                        ret_ty
3008                    }),
3009                };
3010            }
3011        };
3012    }
3013
3014    if name == sym::simd_reduce_and {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_and,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_and(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_and,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_and: vector_reduce_and, false);
3015    if name == sym::simd_reduce_or {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_or,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_or(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_or,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_or: vector_reduce_or, false);
3016    if name == sym::simd_reduce_xor {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_xor,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_xor(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_xor,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
3017    if name == sym::simd_reduce_all {
    let input =
        if !true {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_all,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_and(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_all,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_all: vector_reduce_and, true);
3018    if name == sym::simd_reduce_any {
    let input =
        if !true {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_any,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_or(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_any,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_any: vector_reduce_or, true);
3019
3020    if name == sym::simd_cast_ptr {
3021        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3022        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3023            in_len == out_len,
3024            InvalidMonomorphization::ReturnLengthInputType {
3025                span,
3026                name,
3027                in_len,
3028                in_ty,
3029                ret_ty,
3030                out_len
3031            }
3032        );
3033
3034        match in_elem.kind() {
3035            ty::RawPtr(p_ty, _) => {
3036                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3037                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
3038                });
3039                if !metadata.is_unit() {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                    span,
                    name,
                    ty: in_elem,
                });
        return Err(err);
    };
};require!(
3040                    metadata.is_unit(),
3041                    InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem }
3042                );
3043            }
3044            _ => {
3045                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
3046            }
3047        }
3048        match out_elem.kind() {
3049            ty::RawPtr(p_ty, _) => {
3050                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3051                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
3052                });
3053                if !metadata.is_unit() {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                    span,
                    name,
                    ty: out_elem,
                });
        return Err(err);
    };
};require!(
3054                    metadata.is_unit(),
3055                    InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem }
3056                );
3057            }
3058            _ => {
3059                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
3060            }
3061        }
3062
3063        return Ok(args[0].immediate());
3064    }
3065
3066    if name == sym::simd_expose_provenance {
3067        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3068        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3069            in_len == out_len,
3070            InvalidMonomorphization::ReturnLengthInputType {
3071                span,
3072                name,
3073                in_len,
3074                in_ty,
3075                ret_ty,
3076                out_len
3077            }
3078        );
3079
3080        match in_elem.kind() {
3081            ty::RawPtr(_, _) => {}
3082            _ => {
3083                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
3084            }
3085        }
3086        match out_elem.kind() {
3087            ty::Uint(ty::UintTy::Usize) => {}
3088            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedUsize {
                span,
                name,
                ty: out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: out_elem }),
3089        }
3090
3091        return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
3092    }
3093
3094    if name == sym::simd_with_exposed_provenance {
3095        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3096        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3097            in_len == out_len,
3098            InvalidMonomorphization::ReturnLengthInputType {
3099                span,
3100                name,
3101                in_len,
3102                in_ty,
3103                ret_ty,
3104                out_len
3105            }
3106        );
3107
3108        match in_elem.kind() {
3109            ty::Uint(ty::UintTy::Usize) => {}
3110            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedUsize {
                span,
                name,
                ty: in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: in_elem }),
3111        }
3112        match out_elem.kind() {
3113            ty::RawPtr(_, _) => {}
3114            _ => {
3115                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
3116            }
3117        }
3118
3119        return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
3120    }
3121
3122    if name == sym::simd_cast || name == sym::simd_as {
3123        let (out_len, out_elem, out_num_vecs) = {
    if !(ret_ty.is_simd() || ret_ty.is_scalable_vector()) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    if ret_ty.is_simd() {
        let (len, ty) = ret_ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            ret_ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(ret_ty, SimdReturn);
3124        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3125            in_len == out_len,
3126            InvalidMonomorphization::ReturnLengthInputType {
3127                span,
3128                name,
3129                in_len,
3130                in_ty,
3131                ret_ty,
3132                out_len
3133            }
3134        );
3135        if !(in_num_vecs == out_num_vecs) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnNumVecsInputType {
                    span,
                    name,
                    in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
                    in_ty,
                    ret_ty,
                    out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1)),
                });
        return Err(err);
    };
};require!(
3136            in_num_vecs == out_num_vecs,
3137            InvalidMonomorphization::ReturnNumVecsInputType {
3138                span,
3139                name,
3140                in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
3141                in_ty,
3142                ret_ty,
3143                out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1))
3144            }
3145        );
3146
3147        // Casting cares about nominal type, not just structural type
3148        if in_elem == out_elem {
3149            return Ok(args[0].immediate());
3150        }
3151
3152        #[derive(#[automatically_derived]impl ::core::marker::Copy for Sign { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Sign {
}
#[automatically_derived]impl ::core::clone::Clone for Sign {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
3153        enum Sign {
3154            Unsigned,
3155            Signed,
3156        }
3157        use Sign::*;
3158
3159        enum Style {
3160            Float,
3161            Int(Sign),
3162            Unsupported,
3163        }
3164
3165        let (in_style, in_width) = match in_elem.kind() {
3166            // vectors of pointer-sized integers should've been
3167            // disallowed before here, so this unwrap is safe.
3168            ty::Int(i) => (
3169                Style::Int(Signed),
3170                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3171            ),
3172            ty::Uint(u) => (
3173                Style::Int(Unsigned),
3174                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3175            ),
3176            ty::Float(f) => (Style::Float, f.bit_width()),
3177            _ => (Style::Unsupported, 0),
3178        };
3179        let (out_style, out_width) = match out_elem.kind() {
3180            ty::Int(i) => (
3181                Style::Int(Signed),
3182                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3183            ),
3184            ty::Uint(u) => (
3185                Style::Int(Unsigned),
3186                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3187            ),
3188            ty::Float(f) => (Style::Float, f.bit_width()),
3189            _ => (Style::Unsupported, 0),
3190        };
3191
3192        match (in_style, out_style) {
3193            (Style::Int(sign), Style::Int(_)) => {
3194                return Ok(match in_width.cmp(&out_width) {
3195                    Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
3196                    Ordering::Equal => args[0].immediate(),
3197                    Ordering::Less => match sign {
3198                        Sign::Signed => bx.sext(args[0].immediate(), llret_ty),
3199                        Sign::Unsigned => bx.zext(args[0].immediate(), llret_ty),
3200                    },
3201                });
3202            }
3203            (Style::Int(Sign::Signed), Style::Float) => {
3204                return Ok(bx.sitofp(args[0].immediate(), llret_ty));
3205            }
3206            (Style::Int(Sign::Unsigned), Style::Float) => {
3207                return Ok(bx.uitofp(args[0].immediate(), llret_ty));
3208            }
3209            (Style::Float, Style::Int(sign)) => {
3210                return Ok(match (sign, name == sym::simd_as) {
3211                    (Sign::Unsigned, false) => bx.fptoui(args[0].immediate(), llret_ty),
3212                    (Sign::Signed, false) => bx.fptosi(args[0].immediate(), llret_ty),
3213                    (_, true) => bx.cast_float_to_int(
3214                        #[allow(non_exhaustive_omitted_patterns)] match sign {
    Sign::Signed => true,
    _ => false,
}matches!(sign, Sign::Signed),
3215                        args[0].immediate(),
3216                        llret_ty,
3217                    ),
3218                });
3219            }
3220            (Style::Float, Style::Float) => {
3221                return Ok(match in_width.cmp(&out_width) {
3222                    Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
3223                    Ordering::Equal => args[0].immediate(),
3224                    Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
3225                });
3226            }
3227            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedCast {
                span,
                name,
                in_ty,
                in_elem,
                ret_ty,
                out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnsupportedCast {
3228                span,
3229                name,
3230                in_ty,
3231                in_elem,
3232                ret_ty,
3233                out_elem
3234            }),
3235        }
3236    }
3237    macro_rules! arith_binary {
3238        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3239            $(if name == sym::$name {
3240                match in_elem.kind() {
3241                    $($(ty::$p(_))|* => {
3242                        return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
3243                    })*
3244                    _ => {},
3245                }
3246                return_error!(
3247                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3248                );
3249            })*
3250        }
3251    }
3252    if name == sym::simd_add {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.add(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fadd(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_sub {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.sub(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fsub(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_mul {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.mul(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fmul(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_div {
    match in_elem.kind() {
        ty::Uint(_) => {
            return Ok(bx.udiv(args[0].immediate(), args[1].immediate()))
        }
        ty::Int(_) => {
            return Ok(bx.sdiv(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fdiv(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_rem {
    match in_elem.kind() {
        ty::Uint(_) => {
            return Ok(bx.urem(args[0].immediate(), args[1].immediate()))
        }
        ty::Int(_) => {
            return Ok(bx.srem(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.frem(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_shl {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.shl(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_shr {
    match in_elem.kind() {
        ty::Uint(_) => {
            return Ok(bx.lshr(args[0].immediate(), args[1].immediate()))
        }
        ty::Int(_) => {
            return Ok(bx.ashr(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_and {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.and(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_or {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.or(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_xor {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.xor(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_maximum_number_nsz {
    match in_elem.kind() {
        ty::Float(_) => {
            return Ok(bx.maximum_number_nsz(args[0].immediate(),
                        args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_minimum_number_nsz {
    match in_elem.kind() {
        ty::Float(_) => {
            return Ok(bx.minimum_number_nsz(args[0].immediate(),
                        args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}arith_binary! {
3253        simd_add: Uint, Int => add, Float => fadd;
3254        simd_sub: Uint, Int => sub, Float => fsub;
3255        simd_mul: Uint, Int => mul, Float => fmul;
3256        simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
3257        simd_rem: Uint => urem, Int => srem, Float => frem;
3258        simd_shl: Uint, Int => shl;
3259        simd_shr: Uint => lshr, Int => ashr;
3260        simd_and: Uint, Int => and;
3261        simd_or: Uint, Int => or;
3262        simd_xor: Uint, Int => xor;
3263        simd_maximum_number_nsz: Float => maximum_number_nsz;
3264        simd_minimum_number_nsz: Float => minimum_number_nsz;
3265
3266    }
3267    macro_rules! arith_unary {
3268        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3269            $(if name == sym::$name {
3270                match in_elem.kind() {
3271                    $($(ty::$p(_))|* => {
3272                        return Ok(bx.$call(args[0].immediate()))
3273                    })*
3274                    _ => {},
3275                }
3276                return_error!(
3277                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3278                );
3279            })*
3280        }
3281    }
3282    if name == sym::simd_neg {
    match in_elem.kind() {
        ty::Int(_) => { return Ok(bx.neg(args[0].immediate())) }
        ty::Float(_) => { return Ok(bx.fneg(args[0].immediate())) }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}arith_unary! {
3283        simd_neg: Int => neg, Float => fneg;
3284    }
3285
3286    // Unary integer intrinsics
3287    if #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctlz | sym::simd_ctpop
        | sym::simd_cttz | sym::simd_carryless_mul | sym::simd_funnel_shl |
        sym::simd_funnel_shr => true,
    _ => false,
}matches!(
3288        name,
3289        sym::simd_bswap
3290            | sym::simd_bitreverse
3291            | sym::simd_ctlz
3292            | sym::simd_ctpop
3293            | sym::simd_cttz
3294            | sym::simd_carryless_mul
3295            | sym::simd_funnel_shl
3296            | sym::simd_funnel_shr
3297    ) {
3298        let vec_ty = bx.cx.type_vector(
3299            match *in_elem.kind() {
3300                ty::Int(i) => bx.cx.type_int_from_ty(i),
3301                ty::Uint(i) => bx.cx.type_uint_from_ty(i),
3302                _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                span,
                name,
                in_ty,
                in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnsupportedOperation {
3303                    span,
3304                    name,
3305                    in_ty,
3306                    in_elem
3307                }),
3308            },
3309            in_len,
3310        );
3311        let llvm_intrinsic = match name {
3312            sym::simd_bswap => "llvm.bswap",
3313            sym::simd_bitreverse => "llvm.bitreverse",
3314            sym::simd_ctlz => "llvm.ctlz",
3315            sym::simd_ctpop => "llvm.ctpop",
3316            sym::simd_cttz => "llvm.cttz",
3317            sym::simd_funnel_shl => "llvm.fshl",
3318            sym::simd_funnel_shr => "llvm.fshr",
3319            sym::simd_carryless_mul => "llvm.clmul",
3320            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
3321        };
3322        let int_size = in_elem.int_size_and_signed(bx.tcx()).0.bits();
3323
3324        return match name {
3325            // byte swap is no-op for i8/u8
3326            sym::simd_bswap if int_size == 8 => Ok(args[0].immediate()),
3327            sym::simd_ctlz | sym::simd_cttz => {
3328                // for the (int, i1 immediate) pair, the second arg adds `(0, true) => poison`
3329                let dont_poison_on_zero = bx.const_int(bx.type_i1(), 0);
3330                Ok(bx.call_intrinsic(
3331                    llvm_intrinsic,
3332                    &[vec_ty],
3333                    &[args[0].immediate(), dont_poison_on_zero],
3334                ))
3335            }
3336            sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctpop => {
3337                // simple unary argument cases
3338                Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[args[0].immediate()]))
3339            }
3340            sym::simd_funnel_shl | sym::simd_funnel_shr => Ok(bx.call_intrinsic(
3341                llvm_intrinsic,
3342                &[vec_ty],
3343                &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
3344            )),
3345            sym::simd_carryless_mul => Ok(bx.call_intrinsic(
3346                llvm_intrinsic,
3347                &[vec_ty],
3348                &[args[0].immediate(), args[1].immediate()],
3349            )),
3350            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
3351        };
3352    }
3353
3354    if name == sym::simd_arith_offset {
3355        // This also checks that the first operand is a ptr type.
3356        let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
3357            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("must be called with a vector of pointer types as first argument"),
    Location::caller())span_bug!(span, "must be called with a vector of pointer types as first argument")
3358        });
3359        let layout = bx.layout_of(pointee);
3360        let ptrs = args[0].immediate();
3361        // The second argument must be a ptr-sized integer.
3362        // (We don't care about the signedness, this is wrapping anyway.)
3363        let (_offsets_len, offsets_elem) = args[1].layout.ty.simd_size_and_type(bx.tcx());
3364        if !#[allow(non_exhaustive_omitted_patterns)] match offsets_elem.kind() {
    ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize) => true,
    _ => false,
}matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
3365            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("must be called with a vector of pointer-sized integers as second argument"),
    Location::caller());span_bug!(
3366                span,
3367                "must be called with a vector of pointer-sized integers as second argument"
3368            );
3369        }
3370        let offsets = args[1].immediate();
3371
3372        return Ok(bx.gep(layout.size, ptrs, offsets));
3373    }
3374
3375    if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
3376        let lhs = args[0].immediate();
3377        let rhs = args[1].immediate();
3378        let is_add = name == sym::simd_saturating_add;
3379        let (signed, elem_ty) = match *in_elem.kind() {
3380            ty::Int(i) => (true, bx.cx.type_int_from_ty(i)),
3381            ty::Uint(i) => (false, bx.cx.type_uint_from_ty(i)),
3382            _ => {
3383                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedVectorElementType {
                span,
                name,
                expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
                vector_type: args[0].layout.ty,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::ExpectedVectorElementType {
3384                    span,
3385                    name,
3386                    expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
3387                    vector_type: args[0].layout.ty
3388                });
3389            }
3390        };
3391        let llvm_intrinsic = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.sat",
                if signed { 's' } else { 'u' },
                if is_add { "add" } else { "sub" }))
    })format!(
3392            "llvm.{}{}.sat",
3393            if signed { 's' } else { 'u' },
3394            if is_add { "add" } else { "sub" },
3395        );
3396        let vec_ty = bx.cx.type_vector(elem_ty, in_len);
3397
3398        return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs]));
3399    }
3400
3401    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("unknown SIMD intrinsic"), Location::caller());span_bug!(span, "unknown SIMD intrinsic");
3402}
3403
3404fn codegen_codeview_annotation<'ll, 'tcx>(
3405    bx: &mut Builder<'_, 'll, 'tcx>,
3406    instance: ty::Instance<'tcx>,
3407    span: Span,
3408) {
3409    // This function lowers the `codeview_annotation` intrinsic,
3410    // which is declared like this:
3411    //
3412    // trait CodeViewAnnotationArgs {
3413    //     const ARGS: &[&str];
3414    // }
3415    //
3416    // fn codeview_annotation<T: CodeViewAnnotationArgs>() {}
3417    //
3418    // It finds the `T: CodeViewAnnotationArgs` trait bound, locates
3419    // `ARGS`, const evaluates it, reads the strings off the resulting
3420    // allocation and lowers them.
3421
3422    const ARGS_CONST_NAME: &str = "`CodeViewAnnotationArgs::ARGS`";
3423
3424    let tcx = bx.tcx();
3425
3426    // Locate `ARGS`
3427    let Some((args_const_def_id, generic_args)) = tcx
3428        .explicit_clauses_of(instance.def_id())
3429        .instantiate_own(tcx, instance.args)
3430        .filter_map(|(clause, _)| clause.skip_norm_wip().as_trait_clause())
3431        .find_map(|trait_clause| {
3432            let trait_ref = trait_clause.skip_binder().trait_ref;
3433            tcx.associated_items(trait_ref.def_id)
3434                .in_definition_order()
3435                .find(|item| {
3436                    item.tag() == ty::AssocTag::Const
3437                        && tcx.item_name(item.def_id).as_str() == "ARGS"
3438                })
3439                .map(|item| (item.def_id, trait_ref.args))
3440        })
3441    else {
3442        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("could not find {0}", ARGS_CONST_NAME), Location::caller());span_bug!(span, "could not find {ARGS_CONST_NAME}");
3443    };
3444
3445    // Const evaluate `ARGS`
3446    let args_const_val = match tcx.const_eval_resolve(
3447        bx.typing_env(),
3448        mir::UnevaluatedConst::new(args_const_def_id, generic_args),
3449        span,
3450    ) {
3451        Ok(val) => val,
3452        Err(ErrorHandled::Reported(..)) => return,
3453        Err(ErrorHandled::TooGeneric(_)) => {
3454            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("{0} is too generic", ARGS_CONST_NAME), Location::caller())span_bug!(span, "{ARGS_CONST_NAME} is too generic")
3455        }
3456    };
3457
3458    // Read the strings
3459    let array_alloc = match args_const_val {
3460        mir::ConstValue::Indirect { alloc_id, offset } => read_slice_pointer(tcx, alloc_id, offset)
3461            .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} slice pointer", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} slice pointer")),
3462        _ => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("unexpected {0} value: {1:?}", ARGS_CONST_NAME,
        args_const_val), Location::caller())span_bug!(span, "unexpected {ARGS_CONST_NAME} value: {args_const_val:?}"),
3463    };
3464
3465    let strings = array_alloc.into_iter().flat_map(|(array_alloc_id, array_offset, array_len)| {
3466        (0..array_len).map(move |index| {
3467            let elem_size = tcx.data_layout.pointer_size().bytes() * 2; // Multiplying by 2 for fat pointers
3468            let elem_offset = array_offset + Size::from_bytes(index * elem_size);
3469
3470            let (string_alloc_id, string_offset, string_len) =
3471                match read_slice_pointer(tcx, array_alloc_id, elem_offset) {
3472                    Ok(Some(slice)) => slice,
3473                    Ok(None) => return &[] as &[u8],
3474                    Err(()) => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} string pointer", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} string pointer"),
3475                };
3476
3477            resolve_alloc(tcx, string_alloc_id)
3478                .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} string allocation", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} string allocation"))
3479                .get_bytes_strip_provenance(
3480                    &tcx,
3481                    alloc_range(string_offset, Size::from_bytes(string_len)),
3482                )
3483                .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} string bytes", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} string bytes"))
3484        })
3485    });
3486
3487    // Lower the strings
3488    let md_strings: Vec<&Metadata> = strings.map(|s| bx.cx.create_metadata(s)).collect();
3489    let md_tuple = bx.cx.md_node_in_context(&md_strings);
3490    let md_value = bx.cx.get_metadata_value(md_tuple);
3491    let (fn_ty, intrinsic_fn) = bx.cx.get_intrinsic("llvm.codeview.annotation".into(), &[]);
3492
3493    bx.call(fn_ty, None, None, intrinsic_fn, ReturnSlot::Direct, &[md_value], None, None);
3494}
3495
3496// Reads the slice pointer stored at `offset` in `alloc_id` and
3497// returns its pointee's allocation ID, relative byte offset
3498// and slice length. Returns `None` for an empty slice.
3499fn read_slice_pointer<'tcx>(
3500    tcx: TyCtxt<'tcx>,
3501    alloc_id: AllocId,
3502    offset: Size,
3503) -> Result<Option<(AllocId, Size, u64)>, ()> {
3504    let alloc = resolve_alloc(tcx, alloc_id)?;
3505    let pointer_size = tcx.data_layout.pointer_size();
3506
3507    let pointer = alloc
3508        .read_scalar(&tcx, alloc_range(offset, pointer_size), true)
3509        .map_err(|_| ())?
3510        .to_pointer(&tcx);
3511
3512    let len = alloc
3513        .read_scalar(&tcx, alloc_range(offset + pointer_size, pointer_size), false)
3514        .map_err(|_| ())?
3515        .to_target_usize(&tcx)
3516        .discard_err()
3517        .ok_or(())?;
3518
3519    if len == 0 {
3520        return Ok(None);
3521    }
3522
3523    let (provenance, offset) =
3524        pointer.into_pointer_or_addr().map_err(|_| ())?.prov_and_relative_offset();
3525
3526    Ok(Some((provenance.alloc_id(), offset, len)))
3527}
3528
3529fn resolve_alloc<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId) -> Result<&'tcx Allocation, ()> {
3530    let alloc = match tcx.global_alloc(alloc_id) {
3531        GlobalAlloc::Memory(alloc) => alloc,
3532        GlobalAlloc::Static(def_id) => tcx.eval_static_initializer(def_id).map_err(|_| ())?,
3533        _ => return Err(()),
3534    }
3535    .inner();
3536
3537    Ok(alloc)
3538}