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