rustc_codegen_llvm/
intrinsic.rs

1use std::assert_matches::assert_matches;
2use std::cmp::Ordering;
3use std::ffi::c_uint;
4use std::ptr;
5
6use rustc_abi::{
7    Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size, WrappingRange,
8};
9use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
10use rustc_codegen_ssa::codegen_attrs::autodiff_attrs;
11use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
12use rustc_codegen_ssa::errors::{ExpectedPointerMutability, InvalidMonomorphization};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
15use rustc_codegen_ssa::traits::*;
16use rustc_hir::def_id::LOCAL_CRATE;
17use rustc_hir::{self as hir};
18use rustc_middle::mir::BinOp;
19use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf};
20use rustc_middle::ty::offload_meta::OffloadMetadata;
21use rustc_middle::ty::{self, GenericArgsRef, Instance, SimdAlign, Ty, TyCtxt, TypingEnv};
22use rustc_middle::{bug, span_bug};
23use rustc_session::config::CrateType;
24use rustc_span::{Span, Symbol, sym};
25use rustc_symbol_mangling::{mangle_internal_symbol, symbol_name_for_instance_in_crate};
26use rustc_target::callconv::PassMode;
27use rustc_target::spec::Os;
28use tracing::debug;
29
30use crate::abi::FnAbiLlvmExt;
31use crate::builder::Builder;
32use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
33use crate::builder::gpu_offload::{gen_call_handling, gen_define_handling};
34use crate::context::CodegenCx;
35use crate::declare::declare_raw_fn;
36use crate::errors::{
37    AutoDiffWithoutEnable, AutoDiffWithoutLto, OffloadWithoutEnable, OffloadWithoutFatLTO,
38};
39use crate::llvm::{self, Metadata, Type, Value};
40use crate::type_of::LayoutLlvmExt;
41use crate::va_arg::emit_va_arg;
42
43fn call_simple_intrinsic<'ll, 'tcx>(
44    bx: &mut Builder<'_, 'll, 'tcx>,
45    name: Symbol,
46    args: &[OperandRef<'tcx, &'ll Value>],
47) -> Option<&'ll Value> {
48    let (base_name, type_params): (&'static str, &[&'ll Type]) = match name {
49        sym::sqrtf16 => ("llvm.sqrt", &[bx.type_f16()]),
50        sym::sqrtf32 => ("llvm.sqrt", &[bx.type_f32()]),
51        sym::sqrtf64 => ("llvm.sqrt", &[bx.type_f64()]),
52        sym::sqrtf128 => ("llvm.sqrt", &[bx.type_f128()]),
53
54        sym::powif16 => ("llvm.powi", &[bx.type_f16(), bx.type_i32()]),
55        sym::powif32 => ("llvm.powi", &[bx.type_f32(), bx.type_i32()]),
56        sym::powif64 => ("llvm.powi", &[bx.type_f64(), bx.type_i32()]),
57        sym::powif128 => ("llvm.powi", &[bx.type_f128(), bx.type_i32()]),
58
59        sym::sinf16 => ("llvm.sin", &[bx.type_f16()]),
60        sym::sinf32 => ("llvm.sin", &[bx.type_f32()]),
61        sym::sinf64 => ("llvm.sin", &[bx.type_f64()]),
62        sym::sinf128 => ("llvm.sin", &[bx.type_f128()]),
63
64        sym::cosf16 => ("llvm.cos", &[bx.type_f16()]),
65        sym::cosf32 => ("llvm.cos", &[bx.type_f32()]),
66        sym::cosf64 => ("llvm.cos", &[bx.type_f64()]),
67        sym::cosf128 => ("llvm.cos", &[bx.type_f128()]),
68
69        sym::powf16 => ("llvm.pow", &[bx.type_f16()]),
70        sym::powf32 => ("llvm.pow", &[bx.type_f32()]),
71        sym::powf64 => ("llvm.pow", &[bx.type_f64()]),
72        sym::powf128 => ("llvm.pow", &[bx.type_f128()]),
73
74        sym::expf16 => ("llvm.exp", &[bx.type_f16()]),
75        sym::expf32 => ("llvm.exp", &[bx.type_f32()]),
76        sym::expf64 => ("llvm.exp", &[bx.type_f64()]),
77        sym::expf128 => ("llvm.exp", &[bx.type_f128()]),
78
79        sym::exp2f16 => ("llvm.exp2", &[bx.type_f16()]),
80        sym::exp2f32 => ("llvm.exp2", &[bx.type_f32()]),
81        sym::exp2f64 => ("llvm.exp2", &[bx.type_f64()]),
82        sym::exp2f128 => ("llvm.exp2", &[bx.type_f128()]),
83
84        sym::logf16 => ("llvm.log", &[bx.type_f16()]),
85        sym::logf32 => ("llvm.log", &[bx.type_f32()]),
86        sym::logf64 => ("llvm.log", &[bx.type_f64()]),
87        sym::logf128 => ("llvm.log", &[bx.type_f128()]),
88
89        sym::log10f16 => ("llvm.log10", &[bx.type_f16()]),
90        sym::log10f32 => ("llvm.log10", &[bx.type_f32()]),
91        sym::log10f64 => ("llvm.log10", &[bx.type_f64()]),
92        sym::log10f128 => ("llvm.log10", &[bx.type_f128()]),
93
94        sym::log2f16 => ("llvm.log2", &[bx.type_f16()]),
95        sym::log2f32 => ("llvm.log2", &[bx.type_f32()]),
96        sym::log2f64 => ("llvm.log2", &[bx.type_f64()]),
97        sym::log2f128 => ("llvm.log2", &[bx.type_f128()]),
98
99        sym::fmaf16 => ("llvm.fma", &[bx.type_f16()]),
100        sym::fmaf32 => ("llvm.fma", &[bx.type_f32()]),
101        sym::fmaf64 => ("llvm.fma", &[bx.type_f64()]),
102        sym::fmaf128 => ("llvm.fma", &[bx.type_f128()]),
103
104        sym::fmuladdf16 => ("llvm.fmuladd", &[bx.type_f16()]),
105        sym::fmuladdf32 => ("llvm.fmuladd", &[bx.type_f32()]),
106        sym::fmuladdf64 => ("llvm.fmuladd", &[bx.type_f64()]),
107        sym::fmuladdf128 => ("llvm.fmuladd", &[bx.type_f128()]),
108
109        sym::fabsf16 => ("llvm.fabs", &[bx.type_f16()]),
110        sym::fabsf32 => ("llvm.fabs", &[bx.type_f32()]),
111        sym::fabsf64 => ("llvm.fabs", &[bx.type_f64()]),
112        sym::fabsf128 => ("llvm.fabs", &[bx.type_f128()]),
113
114        sym::minnumf16 => ("llvm.minnum", &[bx.type_f16()]),
115        sym::minnumf32 => ("llvm.minnum", &[bx.type_f32()]),
116        sym::minnumf64 => ("llvm.minnum", &[bx.type_f64()]),
117        sym::minnumf128 => ("llvm.minnum", &[bx.type_f128()]),
118
119        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
120        // when llvm/llvm-project#{139380,139381,140445} are fixed.
121        //sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]),
122        //sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]),
123        //sym::minimumf64 => ("llvm.minimum", &[bx.type_f64()]),
124        //sym::minimumf128 => ("llvm.minimum", &[cx.type_f128()]),
125        //
126        sym::maxnumf16 => ("llvm.maxnum", &[bx.type_f16()]),
127        sym::maxnumf32 => ("llvm.maxnum", &[bx.type_f32()]),
128        sym::maxnumf64 => ("llvm.maxnum", &[bx.type_f64()]),
129        sym::maxnumf128 => ("llvm.maxnum", &[bx.type_f128()]),
130
131        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
132        // when llvm/llvm-project#{139380,139381,140445} are fixed.
133        //sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]),
134        //sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]),
135        //sym::maximumf64 => ("llvm.maximum", &[bx.type_f64()]),
136        //sym::maximumf128 => ("llvm.maximum", &[cx.type_f128()]),
137        //
138        sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]),
139        sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]),
140        sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]),
141        sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]),
142
143        sym::floorf16 => ("llvm.floor", &[bx.type_f16()]),
144        sym::floorf32 => ("llvm.floor", &[bx.type_f32()]),
145        sym::floorf64 => ("llvm.floor", &[bx.type_f64()]),
146        sym::floorf128 => ("llvm.floor", &[bx.type_f128()]),
147
148        sym::ceilf16 => ("llvm.ceil", &[bx.type_f16()]),
149        sym::ceilf32 => ("llvm.ceil", &[bx.type_f32()]),
150        sym::ceilf64 => ("llvm.ceil", &[bx.type_f64()]),
151        sym::ceilf128 => ("llvm.ceil", &[bx.type_f128()]),
152
153        sym::truncf16 => ("llvm.trunc", &[bx.type_f16()]),
154        sym::truncf32 => ("llvm.trunc", &[bx.type_f32()]),
155        sym::truncf64 => ("llvm.trunc", &[bx.type_f64()]),
156        sym::truncf128 => ("llvm.trunc", &[bx.type_f128()]),
157
158        // We could use any of `rint`, `nearbyint`, or `roundeven`
159        // for this -- they are all identical in semantics when
160        // assuming the default FP environment.
161        // `rint` is what we used for $forever.
162        sym::round_ties_even_f16 => ("llvm.rint", &[bx.type_f16()]),
163        sym::round_ties_even_f32 => ("llvm.rint", &[bx.type_f32()]),
164        sym::round_ties_even_f64 => ("llvm.rint", &[bx.type_f64()]),
165        sym::round_ties_even_f128 => ("llvm.rint", &[bx.type_f128()]),
166
167        sym::roundf16 => ("llvm.round", &[bx.type_f16()]),
168        sym::roundf32 => ("llvm.round", &[bx.type_f32()]),
169        sym::roundf64 => ("llvm.round", &[bx.type_f64()]),
170        sym::roundf128 => ("llvm.round", &[bx.type_f128()]),
171
172        _ => return None,
173    };
174    Some(bx.call_intrinsic(
175        base_name,
176        type_params,
177        &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
178    ))
179}
180
181impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
182    fn codegen_intrinsic_call(
183        &mut self,
184        instance: ty::Instance<'tcx>,
185        args: &[OperandRef<'tcx, &'ll Value>],
186        result: PlaceRef<'tcx, &'ll Value>,
187        span: Span,
188    ) -> Result<(), ty::Instance<'tcx>> {
189        let tcx = self.tcx;
190
191        let name = tcx.item_name(instance.def_id());
192        let fn_args = instance.args;
193
194        let simple = call_simple_intrinsic(self, name, args);
195        let llval = match name {
196            _ if simple.is_some() => simple.unwrap(),
197            sym::ptr_mask => {
198                let ptr = args[0].immediate();
199                self.call_intrinsic(
200                    "llvm.ptrmask",
201                    &[self.val_ty(ptr), self.type_isize()],
202                    &[ptr, args[1].immediate()],
203                )
204            }
205            sym::autodiff => {
206                codegen_autodiff(self, tcx, instance, args, result);
207                return Ok(());
208            }
209            sym::offload => {
210                if tcx.sess.opts.unstable_opts.offload.is_empty() {
211                    let _ = tcx.dcx().emit_almost_fatal(OffloadWithoutEnable);
212                }
213
214                if tcx.sess.lto() != rustc_session::config::Lto::Fat {
215                    let _ = tcx.dcx().emit_almost_fatal(OffloadWithoutFatLTO);
216                }
217
218                codegen_offload(self, tcx, instance, args);
219                return Ok(());
220            }
221            sym::is_val_statically_known => {
222                if let OperandValue::Immediate(imm) = args[0].val {
223                    self.call_intrinsic(
224                        "llvm.is.constant",
225                        &[args[0].layout.immediate_llvm_type(self.cx)],
226                        &[imm],
227                    )
228                } else {
229                    self.const_bool(false)
230                }
231            }
232            sym::select_unpredictable => {
233                let cond = args[0].immediate();
234                assert_eq!(args[1].layout, args[2].layout);
235                let select = |bx: &mut Self, true_val, false_val| {
236                    let result = bx.select(cond, true_val, false_val);
237                    bx.set_unpredictable(&result);
238                    result
239                };
240                match (args[1].val, args[2].val) {
241                    (OperandValue::Ref(true_val), OperandValue::Ref(false_val)) => {
242                        assert!(true_val.llextra.is_none());
243                        assert!(false_val.llextra.is_none());
244                        assert_eq!(true_val.align, false_val.align);
245                        let ptr = select(self, true_val.llval, false_val.llval);
246                        let selected =
247                            OperandValue::Ref(PlaceValue::new_sized(ptr, true_val.align));
248                        selected.store(self, result);
249                        return Ok(());
250                    }
251                    (OperandValue::Immediate(_), OperandValue::Immediate(_))
252                    | (OperandValue::Pair(_, _), OperandValue::Pair(_, _)) => {
253                        let true_val = args[1].immediate_or_packed_pair(self);
254                        let false_val = args[2].immediate_or_packed_pair(self);
255                        select(self, true_val, false_val)
256                    }
257                    (OperandValue::ZeroSized, OperandValue::ZeroSized) => return Ok(()),
258                    _ => span_bug!(span, "Incompatible OperandValue for select_unpredictable"),
259                }
260            }
261            sym::catch_unwind => {
262                catch_unwind_intrinsic(
263                    self,
264                    args[0].immediate(),
265                    args[1].immediate(),
266                    args[2].immediate(),
267                    result,
268                );
269                return Ok(());
270            }
271            sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[], &[]),
272            sym::va_copy => {
273                let dest = args[0].immediate();
274                self.call_intrinsic(
275                    "llvm.va_copy",
276                    &[self.val_ty(dest)],
277                    &[dest, args[1].immediate()],
278                )
279            }
280            sym::va_arg => {
281                match result.layout.backend_repr {
282                    BackendRepr::Scalar(scalar) => {
283                        match scalar.primitive() {
284                            Primitive::Int(..) => {
285                                if self.cx().size_of(result.layout.ty).bytes() < 4 {
286                                    // `va_arg` should not be called on an integer type
287                                    // less than 4 bytes in length. If it is, promote
288                                    // the integer to an `i32` and truncate the result
289                                    // back to the smaller type.
290                                    let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
291                                    self.trunc(promoted_result, result.layout.llvm_type(self))
292                                } else {
293                                    emit_va_arg(self, args[0], result.layout.ty)
294                                }
295                            }
296                            Primitive::Float(Float::F16) => {
297                                bug!("the va_arg intrinsic does not work with `f16`")
298                            }
299                            Primitive::Float(Float::F64) | Primitive::Pointer(_) => {
300                                emit_va_arg(self, args[0], result.layout.ty)
301                            }
302                            // `va_arg` should never be used with the return type f32.
303                            Primitive::Float(Float::F32) => {
304                                bug!("the va_arg intrinsic does not work with `f32`")
305                            }
306                            Primitive::Float(Float::F128) => {
307                                bug!("the va_arg intrinsic does not work with `f128`")
308                            }
309                        }
310                    }
311                    _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
312                }
313            }
314
315            sym::volatile_load | sym::unaligned_volatile_load => {
316                let ptr = args[0].immediate();
317                let load = self.volatile_load(result.layout.llvm_type(self), ptr);
318                let align = if name == sym::unaligned_volatile_load {
319                    1
320                } else {
321                    result.layout.align.bytes() as u32
322                };
323                unsafe {
324                    llvm::LLVMSetAlignment(load, align);
325                }
326                if !result.layout.is_zst() {
327                    self.store_to_place(load, result.val);
328                }
329                return Ok(());
330            }
331            sym::volatile_store => {
332                let dst = args[0].deref(self.cx());
333                args[1].val.volatile_store(self, dst);
334                return Ok(());
335            }
336            sym::unaligned_volatile_store => {
337                let dst = args[0].deref(self.cx());
338                args[1].val.unaligned_volatile_store(self, dst);
339                return Ok(());
340            }
341            sym::prefetch_read_data
342            | sym::prefetch_write_data
343            | sym::prefetch_read_instruction
344            | sym::prefetch_write_instruction => {
345                let (rw, cache_type) = match name {
346                    sym::prefetch_read_data => (0, 1),
347                    sym::prefetch_write_data => (1, 1),
348                    sym::prefetch_read_instruction => (0, 0),
349                    sym::prefetch_write_instruction => (1, 0),
350                    _ => bug!(),
351                };
352                let ptr = args[0].immediate();
353                let locality = fn_args.const_at(1).to_leaf().to_i32();
354                self.call_intrinsic(
355                    "llvm.prefetch",
356                    &[self.val_ty(ptr)],
357                    &[
358                        ptr,
359                        self.const_i32(rw),
360                        self.const_i32(locality),
361                        self.const_i32(cache_type),
362                    ],
363                )
364            }
365            sym::carrying_mul_add => {
366                let (size, signed) = fn_args.type_at(0).int_size_and_signed(self.tcx);
367
368                let wide_llty = self.type_ix(size.bits() * 2);
369                let args = args.as_array().unwrap();
370                let [a, b, c, d] = args.map(|a| self.intcast(a.immediate(), wide_llty, signed));
371
372                let wide = if signed {
373                    let prod = self.unchecked_smul(a, b);
374                    let acc = self.unchecked_sadd(prod, c);
375                    self.unchecked_sadd(acc, d)
376                } else {
377                    let prod = self.unchecked_umul(a, b);
378                    let acc = self.unchecked_uadd(prod, c);
379                    self.unchecked_uadd(acc, d)
380                };
381
382                let narrow_llty = self.type_ix(size.bits());
383                let low = self.trunc(wide, narrow_llty);
384                let bits_const = self.const_uint(wide_llty, size.bits());
385                // No need for ashr when signed; LLVM changes it to lshr anyway.
386                let high = self.lshr(wide, bits_const);
387                // FIXME: could be `trunc nuw`, even for signed.
388                let high = self.trunc(high, narrow_llty);
389
390                let pair_llty = self.type_struct(&[narrow_llty, narrow_llty], false);
391                let pair = self.const_poison(pair_llty);
392                let pair = self.insert_value(pair, low, 0);
393                let pair = self.insert_value(pair, high, 1);
394                pair
395            }
396            sym::ctlz
397            | sym::ctlz_nonzero
398            | sym::cttz
399            | sym::cttz_nonzero
400            | sym::ctpop
401            | sym::bswap
402            | sym::bitreverse
403            | sym::saturating_add
404            | sym::saturating_sub
405            | sym::unchecked_funnel_shl
406            | sym::unchecked_funnel_shr => {
407                let ty = args[0].layout.ty;
408                if !ty.is_integral() {
409                    tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
410                        span,
411                        name,
412                        ty,
413                    });
414                    return Ok(());
415                }
416                let (size, signed) = ty.int_size_and_signed(self.tcx);
417                let width = size.bits();
418                let llty = self.type_ix(width);
419                match name {
420                    sym::ctlz | sym::ctlz_nonzero | sym::cttz | sym::cttz_nonzero => {
421                        let y =
422                            self.const_bool(name == sym::ctlz_nonzero || name == sym::cttz_nonzero);
423                        let llvm_name = if name == sym::ctlz || name == sym::ctlz_nonzero {
424                            "llvm.ctlz"
425                        } else {
426                            "llvm.cttz"
427                        };
428                        let ret =
429                            self.call_intrinsic(llvm_name, &[llty], &[args[0].immediate(), y]);
430                        self.intcast(ret, result.layout.llvm_type(self), false)
431                    }
432                    sym::ctpop => {
433                        let ret =
434                            self.call_intrinsic("llvm.ctpop", &[llty], &[args[0].immediate()]);
435                        self.intcast(ret, result.layout.llvm_type(self), false)
436                    }
437                    sym::bswap => {
438                        if width == 8 {
439                            args[0].immediate() // byte swap a u8/i8 is just a no-op
440                        } else {
441                            self.call_intrinsic("llvm.bswap", &[llty], &[args[0].immediate()])
442                        }
443                    }
444                    sym::bitreverse => {
445                        self.call_intrinsic("llvm.bitreverse", &[llty], &[args[0].immediate()])
446                    }
447                    sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
448                        let is_left = name == sym::unchecked_funnel_shl;
449                        let lhs = args[0].immediate();
450                        let rhs = args[1].immediate();
451                        let raw_shift = args[2].immediate();
452                        let llvm_name = format!("llvm.fsh{}", if is_left { 'l' } else { 'r' });
453
454                        // llvm expects shift to be the same type as the values, but rust
455                        // always uses `u32`.
456                        let raw_shift = self.intcast(raw_shift, self.val_ty(lhs), false);
457
458                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs, raw_shift])
459                    }
460                    sym::saturating_add | sym::saturating_sub => {
461                        let is_add = name == sym::saturating_add;
462                        let lhs = args[0].immediate();
463                        let rhs = args[1].immediate();
464                        let llvm_name = format!(
465                            "llvm.{}{}.sat",
466                            if signed { 's' } else { 'u' },
467                            if is_add { "add" } else { "sub" },
468                        );
469                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
470                    }
471                    _ => bug!(),
472                }
473            }
474
475            sym::raw_eq => {
476                use BackendRepr::*;
477                let tp_ty = fn_args.type_at(0);
478                let layout = self.layout_of(tp_ty).layout;
479                let use_integer_compare = match layout.backend_repr() {
480                    Scalar(_) | ScalarPair(_, _) => true,
481                    SimdVector { .. } => false,
482                    ScalableVector { .. } => {
483                        tcx.dcx().emit_err(InvalidMonomorphization::NonScalableType {
484                            span,
485                            name: sym::raw_eq,
486                            ty: tp_ty,
487                        });
488                        return Ok(());
489                    }
490                    Memory { .. } => {
491                        // For rusty ABIs, small aggregates are actually passed
492                        // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
493                        // so we re-use that same threshold here.
494                        layout.size() <= self.data_layout().pointer_size() * 2
495                    }
496                };
497
498                let a = args[0].immediate();
499                let b = args[1].immediate();
500                if layout.size().bytes() == 0 {
501                    self.const_bool(true)
502                } else if use_integer_compare {
503                    let integer_ty = self.type_ix(layout.size().bits());
504                    let a_val = self.load(integer_ty, a, layout.align().abi);
505                    let b_val = self.load(integer_ty, b, layout.align().abi);
506                    self.icmp(IntPredicate::IntEQ, a_val, b_val)
507                } else {
508                    let n = self.const_usize(layout.size().bytes());
509                    let cmp = self.call_intrinsic("memcmp", &[], &[a, b, n]);
510                    self.icmp(IntPredicate::IntEQ, cmp, self.const_int(self.type_int(), 0))
511                }
512            }
513
514            sym::compare_bytes => {
515                // Here we assume that the `memcmp` provided by the target is a NOP for size 0.
516                let cmp = self.call_intrinsic(
517                    "memcmp",
518                    &[],
519                    &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
520                );
521                // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`.
522                self.sext(cmp, self.type_ix(32))
523            }
524
525            sym::black_box => {
526                args[0].val.store(self, result);
527                let result_val_span = [result.val.llval];
528                // We need to "use" the argument in some way LLVM can't introspect, and on
529                // targets that support it we can typically leverage inline assembly to do
530                // this. LLVM's interpretation of inline assembly is that it's, well, a black
531                // box. This isn't the greatest implementation since it probably deoptimizes
532                // more than we want, but it's so far good enough.
533                //
534                // For zero-sized types, the location pointed to by the result may be
535                // uninitialized. Do not "use" the result in this case; instead just clobber
536                // the memory.
537                let (constraint, inputs): (&str, &[_]) = if result.layout.is_zst() {
538                    ("~{memory}", &[])
539                } else {
540                    ("r,~{memory}", &result_val_span)
541                };
542                crate::asm::inline_asm_call(
543                    self,
544                    "",
545                    constraint,
546                    inputs,
547                    self.type_void(),
548                    &[],
549                    true,
550                    false,
551                    llvm::AsmDialect::Att,
552                    &[span],
553                    false,
554                    None,
555                    None,
556                )
557                .unwrap_or_else(|| bug!("failed to generate inline asm call for `black_box`"));
558
559                // We have copied the value to `result` already.
560                return Ok(());
561            }
562
563            _ if name.as_str().starts_with("simd_") => {
564                // Unpack non-power-of-2 #[repr(packed, simd)] arguments.
565                // This gives them the expected layout of a regular #[repr(simd)] vector.
566                let mut loaded_args = Vec::new();
567                for arg in args {
568                    loaded_args.push(
569                        // #[repr(packed, simd)] vectors are passed like arrays (as references,
570                        // with reduced alignment and no padding) rather than as immediates.
571                        // We can use a vector load to fix the layout and turn the argument
572                        // into an immediate.
573                        if arg.layout.ty.is_simd()
574                            && let OperandValue::Ref(place) = arg.val
575                        {
576                            let (size, elem_ty) = arg.layout.ty.simd_size_and_type(self.tcx());
577                            let elem_ll_ty = match elem_ty.kind() {
578                                ty::Float(f) => self.type_float_from_ty(*f),
579                                ty::Int(i) => self.type_int_from_ty(*i),
580                                ty::Uint(u) => self.type_uint_from_ty(*u),
581                                ty::RawPtr(_, _) => self.type_ptr(),
582                                _ => unreachable!(),
583                            };
584                            let loaded =
585                                self.load_from_place(self.type_vector(elem_ll_ty, size), place);
586                            OperandRef::from_immediate_or_packed_pair(self, loaded, arg.layout)
587                        } else {
588                            *arg
589                        },
590                    );
591                }
592
593                let llret_ty = if result.layout.ty.is_simd()
594                    && let BackendRepr::Memory { .. } = result.layout.backend_repr
595                {
596                    let (size, elem_ty) = result.layout.ty.simd_size_and_type(self.tcx());
597                    let elem_ll_ty = match elem_ty.kind() {
598                        ty::Float(f) => self.type_float_from_ty(*f),
599                        ty::Int(i) => self.type_int_from_ty(*i),
600                        ty::Uint(u) => self.type_uint_from_ty(*u),
601                        ty::RawPtr(_, _) => self.type_ptr(),
602                        _ => unreachable!(),
603                    };
604                    self.type_vector(elem_ll_ty, size)
605                } else {
606                    result.layout.llvm_type(self)
607                };
608
609                match generic_simd_intrinsic(
610                    self,
611                    name,
612                    fn_args,
613                    &loaded_args,
614                    result.layout.ty,
615                    llret_ty,
616                    span,
617                ) {
618                    Ok(llval) => llval,
619                    // If there was an error, just skip this invocation... we'll abort compilation
620                    // anyway, but we can keep codegen'ing to find more errors.
621                    Err(()) => return Ok(()),
622                }
623            }
624
625            _ => {
626                debug!("unknown intrinsic '{}' -- falling back to default body", name);
627                // Call the fallback body instead of generating the intrinsic code
628                return Err(ty::Instance::new_raw(instance.def_id(), instance.args));
629            }
630        };
631
632        if result.layout.ty.is_bool() {
633            let val = self.from_immediate(llval);
634            self.store_to_place(val, result.val);
635        } else if !result.layout.ty.is_unit() {
636            self.store_to_place(llval, result.val);
637        }
638        Ok(())
639    }
640
641    fn codegen_llvm_intrinsic_call(
642        &mut self,
643        instance: ty::Instance<'tcx>,
644        args: &[OperandRef<'tcx, Self::Value>],
645        is_cleanup: bool,
646    ) -> Self::Value {
647        let tcx = self.tcx();
648
649        // FIXME remove usage of fn_abi
650        let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty());
651        assert!(!fn_abi.ret.is_indirect());
652        let fn_ty = fn_abi.llvm_type(self);
653
654        let fn_ptr = if let Some(&llfn) = self.intrinsic_instances.borrow().get(&instance) {
655            llfn
656        } else {
657            let sym = tcx.symbol_name(instance).name;
658
659            // FIXME use get_intrinsic
660            let llfn = if let Some(llfn) = self.get_declared_value(sym) {
661                llfn
662            } else {
663                // Function addresses in Rust are never significant, allowing functions to
664                // be merged.
665                let llfn = declare_raw_fn(
666                    self,
667                    sym,
668                    fn_abi.llvm_cconv(self),
669                    llvm::UnnamedAddr::Global,
670                    llvm::Visibility::Default,
671                    fn_ty,
672                );
673                fn_abi.apply_attrs_llfn(self, llfn, Some(instance));
674
675                llfn
676            };
677
678            self.intrinsic_instances.borrow_mut().insert(instance, llfn);
679
680            llfn
681        };
682
683        let mut llargs = vec![];
684
685        for arg in args {
686            match arg.val {
687                OperandValue::ZeroSized => {}
688                OperandValue::Immediate(_) => llargs.push(arg.immediate()),
689                OperandValue::Pair(a, b) => {
690                    llargs.push(a);
691                    llargs.push(b);
692                }
693                OperandValue::Ref(op_place_val) => {
694                    let mut llval = op_place_val.llval;
695                    // We can't use `PlaceRef::load` here because the argument
696                    // may have a type we don't treat as immediate, but the ABI
697                    // used for this call is passing it by-value. In that case,
698                    // the load would just produce `OperandValue::Ref` instead
699                    // of the `OperandValue::Immediate` we need for the call.
700                    llval = self.load(self.backend_type(arg.layout), llval, op_place_val.align);
701                    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
702                        if scalar.is_bool() {
703                            self.range_metadata(llval, WrappingRange { start: 0, end: 1 });
704                        }
705                        // We store bools as `i8` so we need to truncate to `i1`.
706                        llval = self.to_immediate_scalar(llval, scalar);
707                    }
708                    llargs.push(llval);
709                }
710            }
711        }
712
713        debug!("call intrinsic {:?} with args ({:?})", instance, llargs);
714        let args = self.check_call("call", fn_ty, fn_ptr, &llargs);
715        let llret = unsafe {
716            llvm::LLVMBuildCallWithOperandBundles(
717                self.llbuilder,
718                fn_ty,
719                fn_ptr,
720                args.as_ptr() as *const &llvm::Value,
721                args.len() as c_uint,
722                ptr::dangling(),
723                0,
724                c"".as_ptr(),
725            )
726        };
727        if is_cleanup {
728            self.apply_attrs_to_cleanup_callsite(llret);
729        }
730
731        llret
732    }
733
734    fn abort(&mut self) {
735        self.call_intrinsic("llvm.trap", &[], &[]);
736    }
737
738    fn assume(&mut self, val: Self::Value) {
739        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
740            self.call_intrinsic("llvm.assume", &[], &[val]);
741        }
742    }
743
744    fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
745        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
746            self.call_intrinsic(
747                "llvm.expect",
748                &[self.type_i1()],
749                &[cond, self.const_bool(expected)],
750            )
751        } else {
752            cond
753        }
754    }
755
756    fn type_checked_load(
757        &mut self,
758        llvtable: &'ll Value,
759        vtable_byte_offset: u64,
760        typeid: &'ll Metadata,
761    ) -> Self::Value {
762        let typeid = self.get_metadata_value(typeid);
763        let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
764        let type_checked_load = self.call_intrinsic(
765            "llvm.type.checked.load",
766            &[],
767            &[llvtable, vtable_byte_offset, typeid],
768        );
769        self.extract_value(type_checked_load, 0)
770    }
771
772    fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
773        self.call_intrinsic("llvm.va_start", &[self.val_ty(va_list)], &[va_list])
774    }
775
776    fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
777        self.call_intrinsic("llvm.va_end", &[self.val_ty(va_list)], &[va_list])
778    }
779}
780
781fn catch_unwind_intrinsic<'ll, 'tcx>(
782    bx: &mut Builder<'_, 'll, 'tcx>,
783    try_func: &'ll Value,
784    data: &'ll Value,
785    catch_func: &'ll Value,
786    dest: PlaceRef<'tcx, &'ll Value>,
787) {
788    if !bx.sess().panic_strategy().unwinds() {
789        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
790        bx.call(try_func_ty, None, None, try_func, &[data], None, None);
791        // Return 0 unconditionally from the intrinsic call;
792        // we can never unwind.
793        OperandValue::Immediate(bx.const_i32(0)).store(bx, dest);
794    } else if wants_msvc_seh(bx.sess()) {
795        codegen_msvc_try(bx, try_func, data, catch_func, dest);
796    } else if wants_wasm_eh(bx.sess()) {
797        codegen_wasm_try(bx, try_func, data, catch_func, dest);
798    } else if bx.sess().target.os == Os::Emscripten {
799        codegen_emcc_try(bx, try_func, data, catch_func, dest);
800    } else {
801        codegen_gnu_try(bx, try_func, data, catch_func, dest);
802    }
803}
804
805// MSVC's definition of the `rust_try` function.
806//
807// This implementation uses the new exception handling instructions in LLVM
808// which have support in LLVM for SEH on MSVC targets. Although these
809// instructions are meant to work for all targets, as of the time of this
810// writing, however, LLVM does not recommend the usage of these new instructions
811// as the old ones are still more optimized.
812fn codegen_msvc_try<'ll, 'tcx>(
813    bx: &mut Builder<'_, 'll, 'tcx>,
814    try_func: &'ll Value,
815    data: &'ll Value,
816    catch_func: &'ll Value,
817    dest: PlaceRef<'tcx, &'ll Value>,
818) {
819    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
820        bx.set_personality_fn(bx.eh_personality());
821
822        let normal = bx.append_sibling_block("normal");
823        let catchswitch = bx.append_sibling_block("catchswitch");
824        let catchpad_rust = bx.append_sibling_block("catchpad_rust");
825        let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
826        let caught = bx.append_sibling_block("caught");
827
828        let try_func = llvm::get_param(bx.llfn(), 0);
829        let data = llvm::get_param(bx.llfn(), 1);
830        let catch_func = llvm::get_param(bx.llfn(), 2);
831
832        // We're generating an IR snippet that looks like:
833        //
834        //   declare i32 @rust_try(%try_func, %data, %catch_func) {
835        //      %slot = alloca i8*
836        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
837        //
838        //   normal:
839        //      ret i32 0
840        //
841        //   catchswitch:
842        //      %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
843        //
844        //   catchpad_rust:
845        //      %tok = catchpad within %cs [%type_descriptor, 8, %slot]
846        //      %ptr = load %slot
847        //      call %catch_func(%data, %ptr)
848        //      catchret from %tok to label %caught
849        //
850        //   catchpad_foreign:
851        //      %tok = catchpad within %cs [null, 64, null]
852        //      call %catch_func(%data, null)
853        //      catchret from %tok to label %caught
854        //
855        //   caught:
856        //      ret i32 1
857        //   }
858        //
859        // This structure follows the basic usage of throw/try/catch in LLVM.
860        // For example, compile this C++ snippet to see what LLVM generates:
861        //
862        //      struct rust_panic {
863        //          rust_panic(const rust_panic&);
864        //          ~rust_panic();
865        //
866        //          void* x[2];
867        //      };
868        //
869        //      int __rust_try(
870        //          void (*try_func)(void*),
871        //          void *data,
872        //          void (*catch_func)(void*, void*) noexcept
873        //      ) {
874        //          try {
875        //              try_func(data);
876        //              return 0;
877        //          } catch(rust_panic& a) {
878        //              catch_func(data, &a);
879        //              return 1;
880        //          } catch(...) {
881        //              catch_func(data, NULL);
882        //              return 1;
883        //          }
884        //      }
885        //
886        // More information can be found in libstd's seh.rs implementation.
887        let ptr_size = bx.tcx().data_layout.pointer_size();
888        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
889        let slot = bx.alloca(ptr_size, ptr_align);
890        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
891        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
892
893        bx.switch_to_block(normal);
894        bx.ret(bx.const_i32(0));
895
896        bx.switch_to_block(catchswitch);
897        let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
898
899        // We can't use the TypeDescriptor defined in libpanic_unwind because it
900        // might be in another DLL and the SEH encoding only supports specifying
901        // a TypeDescriptor from the current module.
902        //
903        // However this isn't an issue since the MSVC runtime uses string
904        // comparison on the type name to match TypeDescriptors rather than
905        // pointer equality.
906        //
907        // So instead we generate a new TypeDescriptor in each module that uses
908        // `try` and let the linker merge duplicate definitions in the same
909        // module.
910        //
911        // When modifying, make sure that the type_name string exactly matches
912        // the one used in library/panic_unwind/src/seh.rs.
913        let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_ptr());
914        let type_name = bx.const_bytes(b"rust_panic\0");
915        let type_info =
916            bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false);
917        let tydesc = bx.declare_global(
918            &mangle_internal_symbol(bx.tcx, "__rust_panic_type_info"),
919            bx.val_ty(type_info),
920        );
921
922        llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
923        if bx.cx.tcx.sess.target.supports_comdat() {
924            llvm::SetUniqueComdat(bx.llmod, tydesc);
925        }
926        llvm::set_initializer(tydesc, type_info);
927
928        // The flag value of 8 indicates that we are catching the exception by
929        // reference instead of by value. We can't use catch by value because
930        // that requires copying the exception object, which we don't support
931        // since our exception object effectively contains a Box.
932        //
933        // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
934        bx.switch_to_block(catchpad_rust);
935        let flags = bx.const_i32(8);
936        let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
937        let ptr = bx.load(bx.type_ptr(), slot, ptr_align);
938        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
939        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
940        bx.catch_ret(&funclet, caught);
941
942        // The flag value of 64 indicates a "catch-all".
943        bx.switch_to_block(catchpad_foreign);
944        let flags = bx.const_i32(64);
945        let null = bx.const_null(bx.type_ptr());
946        let funclet = bx.catch_pad(cs, &[null, flags, null]);
947        bx.call(catch_ty, None, None, catch_func, &[data, null], Some(&funclet), None);
948        bx.catch_ret(&funclet, caught);
949
950        bx.switch_to_block(caught);
951        bx.ret(bx.const_i32(1));
952    });
953
954    // Note that no invoke is used here because by definition this function
955    // can't panic (that's what it's catching).
956    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
957    OperandValue::Immediate(ret).store(bx, dest);
958}
959
960// WASM's definition of the `rust_try` function.
961fn codegen_wasm_try<'ll, 'tcx>(
962    bx: &mut Builder<'_, 'll, 'tcx>,
963    try_func: &'ll Value,
964    data: &'ll Value,
965    catch_func: &'ll Value,
966    dest: PlaceRef<'tcx, &'ll Value>,
967) {
968    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
969        bx.set_personality_fn(bx.eh_personality());
970
971        let normal = bx.append_sibling_block("normal");
972        let catchswitch = bx.append_sibling_block("catchswitch");
973        let catchpad = bx.append_sibling_block("catchpad");
974        let caught = bx.append_sibling_block("caught");
975
976        let try_func = llvm::get_param(bx.llfn(), 0);
977        let data = llvm::get_param(bx.llfn(), 1);
978        let catch_func = llvm::get_param(bx.llfn(), 2);
979
980        // We're generating an IR snippet that looks like:
981        //
982        //   declare i32 @rust_try(%try_func, %data, %catch_func) {
983        //      %slot = alloca i8*
984        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
985        //
986        //   normal:
987        //      ret i32 0
988        //
989        //   catchswitch:
990        //      %cs = catchswitch within none [%catchpad] unwind to caller
991        //
992        //   catchpad:
993        //      %tok = catchpad within %cs [null]
994        //      %ptr = call @llvm.wasm.get.exception(token %tok)
995        //      %sel = call @llvm.wasm.get.ehselector(token %tok)
996        //      call %catch_func(%data, %ptr)
997        //      catchret from %tok to label %caught
998        //
999        //   caught:
1000        //      ret i32 1
1001        //   }
1002        //
1003        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1004        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
1005
1006        bx.switch_to_block(normal);
1007        bx.ret(bx.const_i32(0));
1008
1009        bx.switch_to_block(catchswitch);
1010        let cs = bx.catch_switch(None, None, &[catchpad]);
1011
1012        bx.switch_to_block(catchpad);
1013        let null = bx.const_null(bx.type_ptr());
1014        let funclet = bx.catch_pad(cs, &[null]);
1015
1016        let ptr = bx.call_intrinsic("llvm.wasm.get.exception", &[], &[funclet.cleanuppad()]);
1017        let _sel = bx.call_intrinsic("llvm.wasm.get.ehselector", &[], &[funclet.cleanuppad()]);
1018
1019        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1020        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
1021        bx.catch_ret(&funclet, caught);
1022
1023        bx.switch_to_block(caught);
1024        bx.ret(bx.const_i32(1));
1025    });
1026
1027    // Note that no invoke is used here because by definition this function
1028    // can't panic (that's what it's catching).
1029    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1030    OperandValue::Immediate(ret).store(bx, dest);
1031}
1032
1033// Definition of the standard `try` function for Rust using the GNU-like model
1034// of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1035// instructions).
1036//
1037// This codegen is a little surprising because we always call a shim
1038// function instead of inlining the call to `invoke` manually here. This is done
1039// because in LLVM we're only allowed to have one personality per function
1040// definition. The call to the `try` intrinsic is being inlined into the
1041// function calling it, and that function may already have other personality
1042// functions in play. By calling a shim we're guaranteed that our shim will have
1043// the right personality function.
1044fn codegen_gnu_try<'ll, 'tcx>(
1045    bx: &mut Builder<'_, 'll, 'tcx>,
1046    try_func: &'ll Value,
1047    data: &'ll Value,
1048    catch_func: &'ll Value,
1049    dest: PlaceRef<'tcx, &'ll Value>,
1050) {
1051    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1052        // Codegens the shims described above:
1053        //
1054        //   bx:
1055        //      invoke %try_func(%data) normal %normal unwind %catch
1056        //
1057        //   normal:
1058        //      ret 0
1059        //
1060        //   catch:
1061        //      (%ptr, _) = landingpad
1062        //      call %catch_func(%data, %ptr)
1063        //      ret 1
1064        let then = bx.append_sibling_block("then");
1065        let catch = bx.append_sibling_block("catch");
1066
1067        let try_func = llvm::get_param(bx.llfn(), 0);
1068        let data = llvm::get_param(bx.llfn(), 1);
1069        let catch_func = llvm::get_param(bx.llfn(), 2);
1070        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1071        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1072
1073        bx.switch_to_block(then);
1074        bx.ret(bx.const_i32(0));
1075
1076        // Type indicator for the exception being thrown.
1077        //
1078        // The first value in this tuple is a pointer to the exception object
1079        // being thrown. The second value is a "selector" indicating which of
1080        // the landing pad clauses the exception's type had been matched to.
1081        // rust_try ignores the selector.
1082        bx.switch_to_block(catch);
1083        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1084        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
1085        let tydesc = bx.const_null(bx.type_ptr());
1086        bx.add_clause(vals, tydesc);
1087        let ptr = bx.extract_value(vals, 0);
1088        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1089        bx.call(catch_ty, None, None, catch_func, &[data, ptr], None, None);
1090        bx.ret(bx.const_i32(1));
1091    });
1092
1093    // Note that no invoke is used here because by definition this function
1094    // can't panic (that's what it's catching).
1095    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1096    OperandValue::Immediate(ret).store(bx, dest);
1097}
1098
1099// Variant of codegen_gnu_try used for emscripten where Rust panics are
1100// implemented using C++ exceptions. Here we use exceptions of a specific type
1101// (`struct rust_panic`) to represent Rust panics.
1102fn codegen_emcc_try<'ll, 'tcx>(
1103    bx: &mut Builder<'_, 'll, 'tcx>,
1104    try_func: &'ll Value,
1105    data: &'ll Value,
1106    catch_func: &'ll Value,
1107    dest: PlaceRef<'tcx, &'ll Value>,
1108) {
1109    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1110        // Codegens the shims described above:
1111        //
1112        //   bx:
1113        //      invoke %try_func(%data) normal %normal unwind %catch
1114        //
1115        //   normal:
1116        //      ret 0
1117        //
1118        //   catch:
1119        //      (%ptr, %selector) = landingpad
1120        //      %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
1121        //      %is_rust_panic = %selector == %rust_typeid
1122        //      %catch_data = alloca { i8*, i8 }
1123        //      %catch_data[0] = %ptr
1124        //      %catch_data[1] = %is_rust_panic
1125        //      call %catch_func(%data, %catch_data)
1126        //      ret 1
1127        let then = bx.append_sibling_block("then");
1128        let catch = bx.append_sibling_block("catch");
1129
1130        let try_func = llvm::get_param(bx.llfn(), 0);
1131        let data = llvm::get_param(bx.llfn(), 1);
1132        let catch_func = llvm::get_param(bx.llfn(), 2);
1133        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1134        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1135
1136        bx.switch_to_block(then);
1137        bx.ret(bx.const_i32(0));
1138
1139        // Type indicator for the exception being thrown.
1140        //
1141        // The first value in this tuple is a pointer to the exception object
1142        // being thrown. The second value is a "selector" indicating which of
1143        // the landing pad clauses the exception's type had been matched to.
1144        bx.switch_to_block(catch);
1145        let tydesc = bx.eh_catch_typeinfo();
1146        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1147        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
1148        bx.add_clause(vals, tydesc);
1149        bx.add_clause(vals, bx.const_null(bx.type_ptr()));
1150        let ptr = bx.extract_value(vals, 0);
1151        let selector = bx.extract_value(vals, 1);
1152
1153        // Check if the typeid we got is the one for a Rust panic.
1154        let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[bx.val_ty(tydesc)], &[tydesc]);
1155        let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
1156        let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
1157
1158        // We need to pass two values to catch_func (ptr and is_rust_panic), so
1159        // create an alloca and pass a pointer to that.
1160        let ptr_size = bx.tcx().data_layout.pointer_size();
1161        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1162        let i8_align = bx.tcx().data_layout.i8_align;
1163        // Required in order for there to be no padding between the fields.
1164        assert!(i8_align <= ptr_align);
1165        let catch_data = bx.alloca(2 * ptr_size, ptr_align);
1166        bx.store(ptr, catch_data, ptr_align);
1167        let catch_data_1 = bx.inbounds_ptradd(catch_data, bx.const_usize(ptr_size.bytes()));
1168        bx.store(is_rust_panic, catch_data_1, i8_align);
1169
1170        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1171        bx.call(catch_ty, None, None, catch_func, &[data, catch_data], None, None);
1172        bx.ret(bx.const_i32(1));
1173    });
1174
1175    // Note that no invoke is used here because by definition this function
1176    // can't panic (that's what it's catching).
1177    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1178    OperandValue::Immediate(ret).store(bx, dest);
1179}
1180
1181// Helper function to give a Block to a closure to codegen a shim function.
1182// This is currently primarily used for the `try` intrinsic functions above.
1183fn gen_fn<'a, 'll, 'tcx>(
1184    cx: &'a CodegenCx<'ll, 'tcx>,
1185    name: &str,
1186    rust_fn_sig: ty::PolyFnSig<'tcx>,
1187    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1188) -> (&'ll Type, &'ll Value) {
1189    let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1190    let llty = fn_abi.llvm_type(cx);
1191    let llfn = cx.declare_fn(name, fn_abi, None);
1192    cx.set_frame_pointer_type(llfn);
1193    cx.apply_target_cpu_attr(llfn);
1194    // FIXME(eddyb) find a nicer way to do this.
1195    llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage);
1196    let llbb = Builder::append_block(cx, llfn, "entry-block");
1197    let bx = Builder::build(cx, llbb);
1198    codegen(bx);
1199    (llty, llfn)
1200}
1201
1202// Helper function used to get a handle to the `__rust_try` function used to
1203// catch exceptions.
1204//
1205// This function is only generated once and is then cached.
1206fn get_rust_try_fn<'a, 'll, 'tcx>(
1207    cx: &'a CodegenCx<'ll, 'tcx>,
1208    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1209) -> (&'ll Type, &'ll Value) {
1210    if let Some(llfn) = cx.rust_try_fn.get() {
1211        return llfn;
1212    }
1213
1214    // Define the type up front for the signature of the rust_try function.
1215    let tcx = cx.tcx;
1216    let i8p = Ty::new_mut_ptr(tcx, tcx.types.i8);
1217    // `unsafe fn(*mut i8) -> ()`
1218    let try_fn_ty = Ty::new_fn_ptr(
1219        tcx,
1220        ty::Binder::dummy(tcx.mk_fn_sig(
1221            [i8p],
1222            tcx.types.unit,
1223            false,
1224            hir::Safety::Unsafe,
1225            ExternAbi::Rust,
1226        )),
1227    );
1228    // `unsafe fn(*mut i8, *mut i8) -> ()`
1229    let catch_fn_ty = Ty::new_fn_ptr(
1230        tcx,
1231        ty::Binder::dummy(tcx.mk_fn_sig(
1232            [i8p, i8p],
1233            tcx.types.unit,
1234            false,
1235            hir::Safety::Unsafe,
1236            ExternAbi::Rust,
1237        )),
1238    );
1239    // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
1240    let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
1241        [try_fn_ty, i8p, catch_fn_ty],
1242        tcx.types.i32,
1243        false,
1244        hir::Safety::Unsafe,
1245        ExternAbi::Rust,
1246    ));
1247    let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
1248    cx.rust_try_fn.set(Some(rust_try));
1249    rust_try
1250}
1251
1252fn codegen_autodiff<'ll, 'tcx>(
1253    bx: &mut Builder<'_, 'll, 'tcx>,
1254    tcx: TyCtxt<'tcx>,
1255    instance: ty::Instance<'tcx>,
1256    args: &[OperandRef<'tcx, &'ll Value>],
1257    result: PlaceRef<'tcx, &'ll Value>,
1258) {
1259    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
1260        let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutEnable);
1261    }
1262
1263    let ct = tcx.crate_types();
1264    let lto = tcx.sess.lto();
1265    if ct.len() == 1 && ct.contains(&CrateType::Executable) {
1266        if lto != rustc_session::config::Lto::Fat {
1267            let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutLto);
1268        }
1269    } else {
1270        if lto != rustc_session::config::Lto::Fat && !tcx.sess.opts.cg.linker_plugin_lto.enabled() {
1271            let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutLto);
1272        }
1273    }
1274
1275    let fn_args = instance.args;
1276    let callee_ty = instance.ty(tcx, bx.typing_env());
1277
1278    let sig = callee_ty.fn_sig(tcx).skip_binder();
1279
1280    let ret_ty = sig.output();
1281    let llret_ty = bx.layout_of(ret_ty).llvm_type(bx);
1282
1283    // Get source, diff, and attrs
1284    let (source_id, source_args) = match fn_args.into_type_list(tcx)[0].kind() {
1285        ty::FnDef(def_id, source_params) => (def_id, source_params),
1286        _ => bug!("invalid autodiff intrinsic args"),
1287    };
1288
1289    let fn_source = match Instance::try_resolve(tcx, bx.cx.typing_env(), *source_id, source_args) {
1290        Ok(Some(instance)) => instance,
1291        Ok(None) => bug!(
1292            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1293            source_id,
1294            source_args
1295        ),
1296        Err(_) => {
1297            // An error has already been emitted
1298            return;
1299        }
1300    };
1301
1302    let source_symbol = symbol_name_for_instance_in_crate(tcx, fn_source.clone(), LOCAL_CRATE);
1303    let Some(fn_to_diff) = bx.cx.get_function(&source_symbol) else {
1304        bug!("could not find source function")
1305    };
1306
1307    let (diff_id, diff_args) = match fn_args.into_type_list(tcx)[1].kind() {
1308        ty::FnDef(def_id, diff_args) => (def_id, diff_args),
1309        _ => bug!("invalid args"),
1310    };
1311
1312    let fn_diff = match Instance::try_resolve(tcx, bx.cx.typing_env(), *diff_id, diff_args) {
1313        Ok(Some(instance)) => instance,
1314        Ok(None) => bug!(
1315            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1316            diff_id,
1317            diff_args
1318        ),
1319        Err(_) => {
1320            // An error has already been emitted
1321            return;
1322        }
1323    };
1324
1325    let val_arr = get_args_from_tuple(bx, args[2], fn_diff);
1326    let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff.clone(), LOCAL_CRATE);
1327
1328    let Some(mut diff_attrs) = autodiff_attrs(tcx, fn_diff.def_id()) else {
1329        bug!("could not find autodiff attrs")
1330    };
1331
1332    adjust_activity_to_abi(
1333        tcx,
1334        fn_source,
1335        TypingEnv::fully_monomorphized(),
1336        &mut diff_attrs.input_activity,
1337    );
1338
1339    let fnc_tree =
1340        rustc_middle::ty::fnc_typetrees(tcx, fn_source.ty(tcx, TypingEnv::fully_monomorphized()));
1341
1342    // Build body
1343    generate_enzyme_call(
1344        bx,
1345        bx.cx,
1346        fn_to_diff,
1347        &diff_symbol,
1348        llret_ty,
1349        &val_arr,
1350        diff_attrs.clone(),
1351        result,
1352        fnc_tree,
1353    );
1354}
1355
1356// Generates the LLVM code to offload a Rust function to a target device (e.g., GPU).
1357// For each kernel call, it generates the necessary globals (including metadata such as
1358// size and pass mode), manages memory mapping to and from the device, handles all
1359// data transfers, and launches the kernel on the target device.
1360fn codegen_offload<'ll, 'tcx>(
1361    bx: &mut Builder<'_, 'll, 'tcx>,
1362    tcx: TyCtxt<'tcx>,
1363    instance: ty::Instance<'tcx>,
1364    args: &[OperandRef<'tcx, &'ll Value>],
1365) {
1366    let cx = bx.cx;
1367    let fn_args = instance.args;
1368
1369    let (target_id, target_args) = match fn_args.into_type_list(tcx)[0].kind() {
1370        ty::FnDef(def_id, params) => (def_id, params),
1371        _ => bug!("invalid offload intrinsic arg"),
1372    };
1373
1374    let fn_target = match Instance::try_resolve(tcx, cx.typing_env(), *target_id, target_args) {
1375        Ok(Some(instance)) => instance,
1376        Ok(None) => bug!(
1377            "could not resolve ({:?}, {:?}) to a specific offload instance",
1378            target_id,
1379            target_args
1380        ),
1381        Err(_) => {
1382            // An error has already been emitted
1383            return;
1384        }
1385    };
1386
1387    let args = get_args_from_tuple(bx, args[1], fn_target);
1388    let target_symbol = symbol_name_for_instance_in_crate(tcx, fn_target, LOCAL_CRATE);
1389
1390    let sig = tcx.fn_sig(fn_target.def_id()).skip_binder().skip_binder();
1391    let inputs = sig.inputs();
1392
1393    let metadata = inputs.iter().map(|ty| OffloadMetadata::from_ty(tcx, *ty)).collect::<Vec<_>>();
1394
1395    let types = inputs.iter().map(|ty| cx.layout_of(*ty).llvm_type(cx)).collect::<Vec<_>>();
1396
1397    let offload_globals_ref = cx.offload_globals.borrow();
1398    let offload_globals = match offload_globals_ref.as_ref() {
1399        Some(globals) => globals,
1400        None => {
1401            // Offload is not initialized, cannot continue
1402            return;
1403        }
1404    };
1405    let offload_data = gen_define_handling(&cx, &metadata, &types, target_symbol, offload_globals);
1406    gen_call_handling(bx, &offload_data, &args, &types, &metadata, offload_globals);
1407}
1408
1409fn get_args_from_tuple<'ll, 'tcx>(
1410    bx: &mut Builder<'_, 'll, 'tcx>,
1411    tuple_op: OperandRef<'tcx, &'ll Value>,
1412    fn_instance: Instance<'tcx>,
1413) -> Vec<&'ll Value> {
1414    let cx = bx.cx;
1415    let fn_abi = cx.fn_abi_of_instance(fn_instance, ty::List::empty());
1416
1417    match tuple_op.val {
1418        OperandValue::Immediate(val) => vec![val],
1419        OperandValue::Pair(v1, v2) => vec![v1, v2],
1420        OperandValue::Ref(ptr) => {
1421            let tuple_place = PlaceRef { val: ptr, layout: tuple_op.layout };
1422
1423            let mut result = Vec::with_capacity(fn_abi.args.len());
1424            let mut tuple_index = 0;
1425
1426            for arg in &fn_abi.args {
1427                match arg.mode {
1428                    PassMode::Ignore => {}
1429                    PassMode::Direct(_) | PassMode::Cast { .. } => {
1430                        let field = tuple_place.project_field(bx, tuple_index);
1431                        let llvm_ty = field.layout.llvm_type(bx.cx);
1432                        let val = bx.load(llvm_ty, field.val.llval, field.val.align);
1433                        result.push(val);
1434                        tuple_index += 1;
1435                    }
1436                    PassMode::Pair(_, _) => {
1437                        let field = tuple_place.project_field(bx, tuple_index);
1438                        let llvm_ty = field.layout.llvm_type(bx.cx);
1439                        let pair_val = bx.load(llvm_ty, field.val.llval, field.val.align);
1440                        result.push(bx.extract_value(pair_val, 0));
1441                        result.push(bx.extract_value(pair_val, 1));
1442                        tuple_index += 1;
1443                    }
1444                    PassMode::Indirect { .. } => {
1445                        let field = tuple_place.project_field(bx, tuple_index);
1446                        result.push(field.val.llval);
1447                        tuple_index += 1;
1448                    }
1449                }
1450            }
1451
1452            result
1453        }
1454
1455        OperandValue::ZeroSized => vec![],
1456    }
1457}
1458
1459fn generic_simd_intrinsic<'ll, 'tcx>(
1460    bx: &mut Builder<'_, 'll, 'tcx>,
1461    name: Symbol,
1462    fn_args: GenericArgsRef<'tcx>,
1463    args: &[OperandRef<'tcx, &'ll Value>],
1464    ret_ty: Ty<'tcx>,
1465    llret_ty: &'ll Type,
1466    span: Span,
1467) -> Result<&'ll Value, ()> {
1468    macro_rules! return_error {
1469        ($diag: expr) => {{
1470            bx.sess().dcx().emit_err($diag);
1471            return Err(());
1472        }};
1473    }
1474
1475    macro_rules! require {
1476        ($cond: expr, $diag: expr) => {
1477            if !$cond {
1478                return_error!($diag);
1479            }
1480        };
1481    }
1482
1483    macro_rules! require_simd {
1484        ($ty: expr, $variant:ident) => {{
1485            require!($ty.is_simd(), InvalidMonomorphization::$variant { span, name, ty: $ty });
1486            $ty.simd_size_and_type(bx.tcx())
1487        }};
1488    }
1489
1490    /// Returns the bitwidth of the `$ty` argument if it is an `Int` or `Uint` type.
1491    macro_rules! require_int_or_uint_ty {
1492        ($ty: expr, $diag: expr) => {
1493            match $ty {
1494                ty::Int(i) => {
1495                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
1496                }
1497                ty::Uint(i) => {
1498                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
1499                }
1500                _ => {
1501                    return_error!($diag);
1502                }
1503            }
1504        };
1505    }
1506
1507    let llvm_version = crate::llvm_util::get_version();
1508
1509    /// Converts a vector mask, where each element has a bit width equal to the data elements it is used with,
1510    /// down to an i1 based mask that can be used by llvm intrinsics.
1511    ///
1512    /// The rust simd semantics are that each element should either consist of all ones or all zeroes,
1513    /// but this information is not available to llvm. Truncating the vector effectively uses the lowest bit,
1514    /// but codegen for several targets is better if we consider the highest bit by shifting.
1515    ///
1516    /// For x86 SSE/AVX targets this is beneficial since most instructions with mask parameters only consider the highest bit.
1517    /// So even though on llvm level we have an additional shift, in the final assembly there is no shift or truncate and
1518    /// instead the mask can be used as is.
1519    ///
1520    /// For aarch64 and other targets there is a benefit because a mask from the sign bit can be more
1521    /// efficiently converted to an all ones / all zeroes mask by comparing whether each element is negative.
1522    fn vector_mask_to_bitmask<'a, 'll, 'tcx>(
1523        bx: &mut Builder<'a, 'll, 'tcx>,
1524        i_xn: &'ll Value,
1525        in_elem_bitwidth: u64,
1526        in_len: u64,
1527    ) -> &'ll Value {
1528        // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1529        let shift_idx = bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1530        let shift_indices = vec![shift_idx; in_len as _];
1531        let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1532        // Truncate vector to an <i1 x N>
1533        bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len))
1534    }
1535
1536    // Sanity-check: all vector arguments must be immediates.
1537    if cfg!(debug_assertions) {
1538        for arg in args {
1539            if arg.layout.ty.is_simd() {
1540                assert_matches!(arg.val, OperandValue::Immediate(_));
1541            }
1542        }
1543    }
1544
1545    if name == sym::simd_select_bitmask {
1546        let (len, _) = require_simd!(args[1].layout.ty, SimdArgument);
1547
1548        let expected_int_bits = len.max(8).next_power_of_two();
1549        let expected_bytes = len.div_ceil(8);
1550
1551        let mask_ty = args[0].layout.ty;
1552        let mask = match mask_ty.kind() {
1553            ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
1554            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
1555            ty::Array(elem, len)
1556                if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1557                    && len
1558                        .try_to_target_usize(bx.tcx)
1559                        .expect("expected monomorphic const in codegen")
1560                        == expected_bytes =>
1561            {
1562                let place = PlaceRef::alloca(bx, args[0].layout);
1563                args[0].val.store(bx, place);
1564                let int_ty = bx.type_ix(expected_bytes * 8);
1565                bx.load(int_ty, place.val.llval, Align::ONE)
1566            }
1567            _ => return_error!(InvalidMonomorphization::InvalidBitmask {
1568                span,
1569                name,
1570                mask_ty,
1571                expected_int_bits,
1572                expected_bytes
1573            }),
1574        };
1575
1576        let i1 = bx.type_i1();
1577        let im = bx.type_ix(len);
1578        let i1xn = bx.type_vector(i1, len);
1579        let m_im = bx.trunc(mask, im);
1580        let m_i1s = bx.bitcast(m_im, i1xn);
1581        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1582    }
1583
1584    // every intrinsic below takes a SIMD vector as its first argument
1585    let (in_len, in_elem) = require_simd!(args[0].layout.ty, SimdInput);
1586    let in_ty = args[0].layout.ty;
1587
1588    let comparison = match name {
1589        sym::simd_eq => Some(BinOp::Eq),
1590        sym::simd_ne => Some(BinOp::Ne),
1591        sym::simd_lt => Some(BinOp::Lt),
1592        sym::simd_le => Some(BinOp::Le),
1593        sym::simd_gt => Some(BinOp::Gt),
1594        sym::simd_ge => Some(BinOp::Ge),
1595        _ => None,
1596    };
1597
1598    if let Some(cmp_op) = comparison {
1599        let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1600
1601        require!(
1602            in_len == out_len,
1603            InvalidMonomorphization::ReturnLengthInputType {
1604                span,
1605                name,
1606                in_len,
1607                in_ty,
1608                ret_ty,
1609                out_len
1610            }
1611        );
1612        require!(
1613            bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1614            InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty }
1615        );
1616
1617        return Ok(compare_simd_types(
1618            bx,
1619            args[0].immediate(),
1620            args[1].immediate(),
1621            in_elem,
1622            llret_ty,
1623            cmp_op,
1624        ));
1625    }
1626
1627    if name == sym::simd_shuffle_const_generic {
1628        let idx = fn_args[2].expect_const().to_branch();
1629        let n = idx.len() as u64;
1630
1631        let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1632        require!(
1633            out_len == n,
1634            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
1635        );
1636        require!(
1637            in_elem == out_ty,
1638            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
1639        );
1640
1641        let total_len = in_len * 2;
1642
1643        let indices: Option<Vec<_>> = idx
1644            .iter()
1645            .enumerate()
1646            .map(|(arg_idx, val)| {
1647                let idx = val.to_leaf().to_i32();
1648                if idx >= i32::try_from(total_len).unwrap() {
1649                    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
1650                        span,
1651                        name,
1652                        arg_idx: arg_idx as u64,
1653                        total_len: total_len.into(),
1654                    });
1655                    None
1656                } else {
1657                    Some(bx.const_i32(idx))
1658                }
1659            })
1660            .collect();
1661        let Some(indices) = indices else {
1662            return Ok(bx.const_null(llret_ty));
1663        };
1664
1665        return Ok(bx.shuffle_vector(
1666            args[0].immediate(),
1667            args[1].immediate(),
1668            bx.const_vector(&indices),
1669        ));
1670    }
1671
1672    if name == sym::simd_shuffle {
1673        // Make sure this is actually a SIMD vector.
1674        let idx_ty = args[2].layout.ty;
1675        let n: u64 = if idx_ty.is_simd()
1676            && matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
1677        {
1678            idx_ty.simd_size_and_type(bx.cx.tcx).0
1679        } else {
1680            return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
1681        };
1682
1683        let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1684        require!(
1685            out_len == n,
1686            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
1687        );
1688        require!(
1689            in_elem == out_ty,
1690            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
1691        );
1692
1693        let total_len = u128::from(in_len) * 2;
1694
1695        // Check that the indices are in-bounds.
1696        let indices = args[2].immediate();
1697        for i in 0..n {
1698            let val = bx.const_get_elt(indices, i as u64);
1699            let idx = bx
1700                .const_to_opt_u128(val, true)
1701                .unwrap_or_else(|| bug!("typeck should have already ensured that these are const"));
1702            if idx >= total_len {
1703                return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
1704                    span,
1705                    name,
1706                    arg_idx: i,
1707                    total_len,
1708                });
1709            }
1710        }
1711
1712        return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
1713    }
1714
1715    if name == sym::simd_insert || name == sym::simd_insert_dyn {
1716        require!(
1717            in_elem == args[2].layout.ty,
1718            InvalidMonomorphization::InsertedType {
1719                span,
1720                name,
1721                in_elem,
1722                in_ty,
1723                out_ty: args[2].layout.ty
1724            }
1725        );
1726
1727        let index_imm = if name == sym::simd_insert {
1728            let idx = bx
1729                .const_to_opt_u128(args[1].immediate(), false)
1730                .expect("typeck should have ensure that this is a const");
1731            if idx >= in_len.into() {
1732                return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
1733                    span,
1734                    name,
1735                    arg_idx: 1,
1736                    total_len: in_len.into(),
1737                });
1738            }
1739            bx.const_i32(idx as i32)
1740        } else {
1741            args[1].immediate()
1742        };
1743
1744        return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), index_imm));
1745    }
1746    if name == sym::simd_extract || name == sym::simd_extract_dyn {
1747        require!(
1748            ret_ty == in_elem,
1749            InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
1750        );
1751        let index_imm = if name == sym::simd_extract {
1752            let idx = bx
1753                .const_to_opt_u128(args[1].immediate(), false)
1754                .expect("typeck should have ensure that this is a const");
1755            if idx >= in_len.into() {
1756                return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
1757                    span,
1758                    name,
1759                    arg_idx: 1,
1760                    total_len: in_len.into(),
1761                });
1762            }
1763            bx.const_i32(idx as i32)
1764        } else {
1765            args[1].immediate()
1766        };
1767
1768        return Ok(bx.extract_element(args[0].immediate(), index_imm));
1769    }
1770
1771    if name == sym::simd_select {
1772        let m_elem_ty = in_elem;
1773        let m_len = in_len;
1774        let (v_len, _) = require_simd!(args[1].layout.ty, SimdArgument);
1775        require!(
1776            m_len == v_len,
1777            InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len }
1778        );
1779
1780        let m_i1s = if args[1].layout.ty.is_scalable_vector() {
1781            match m_elem_ty.kind() {
1782                ty::Bool => {}
1783                _ => return_error!(InvalidMonomorphization::MaskWrongElementType {
1784                    span,
1785                    name,
1786                    ty: m_elem_ty
1787                }),
1788            };
1789            let i1 = bx.type_i1();
1790            let i1xn = bx.type_scalable_vector(i1, m_len as u64);
1791            bx.trunc(args[0].immediate(), i1xn)
1792        } else {
1793            let in_elem_bitwidth = require_int_or_uint_ty!(
1794                m_elem_ty.kind(),
1795                InvalidMonomorphization::MaskWrongElementType { span, name, ty: m_elem_ty }
1796            );
1797            vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len)
1798        };
1799
1800        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1801    }
1802
1803    if name == sym::simd_bitmask {
1804        // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a vector mask and
1805        // returns one bit for each lane (which must all be `0` or `!0`) in the form of either:
1806        // * an unsigned integer
1807        // * an array of `u8`
1808        // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
1809        //
1810        // The bit order of the result depends on the byte endianness, LSB-first for little
1811        // endian and MSB-first for big endian.
1812        let expected_int_bits = in_len.max(8).next_power_of_two();
1813        let expected_bytes = in_len.div_ceil(8);
1814
1815        // Integer vector <i{in_bitwidth} x in_len>:
1816        let in_elem_bitwidth = require_int_or_uint_ty!(
1817            in_elem.kind(),
1818            InvalidMonomorphization::MaskWrongElementType { span, name, ty: in_elem }
1819        );
1820
1821        let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len);
1822        // Bitcast <i1 x N> to iN:
1823        let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1824
1825        match ret_ty.kind() {
1826            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
1827                // Zero-extend iN to the bitmask type:
1828                return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1829            }
1830            ty::Array(elem, len)
1831                if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1832                    && len
1833                        .try_to_target_usize(bx.tcx)
1834                        .expect("expected monomorphic const in codegen")
1835                        == expected_bytes =>
1836            {
1837                // Zero-extend iN to the array length:
1838                let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
1839
1840                // Convert the integer to a byte array
1841                let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE);
1842                bx.store(ze, ptr, Align::ONE);
1843                let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
1844                return Ok(bx.load(array_ty, ptr, Align::ONE));
1845            }
1846            _ => return_error!(InvalidMonomorphization::CannotReturn {
1847                span,
1848                name,
1849                ret_ty,
1850                expected_int_bits,
1851                expected_bytes
1852            }),
1853        }
1854    }
1855
1856    fn simd_simple_float_intrinsic<'ll, 'tcx>(
1857        name: Symbol,
1858        in_elem: Ty<'_>,
1859        in_ty: Ty<'_>,
1860        in_len: u64,
1861        bx: &mut Builder<'_, 'll, 'tcx>,
1862        span: Span,
1863        args: &[OperandRef<'tcx, &'ll Value>],
1864    ) -> Result<&'ll Value, ()> {
1865        macro_rules! return_error {
1866            ($diag: expr) => {{
1867                bx.sess().dcx().emit_err($diag);
1868                return Err(());
1869            }};
1870        }
1871
1872        let ty::Float(f) = in_elem.kind() else {
1873            return_error!(InvalidMonomorphization::FloatingPointType { span, name, in_ty });
1874        };
1875        let elem_ty = bx.cx.type_float_from_ty(*f);
1876
1877        let vec_ty = bx.type_vector(elem_ty, in_len);
1878
1879        let intr_name = match name {
1880            sym::simd_ceil => "llvm.ceil",
1881            sym::simd_fabs => "llvm.fabs",
1882            sym::simd_fcos => "llvm.cos",
1883            sym::simd_fexp2 => "llvm.exp2",
1884            sym::simd_fexp => "llvm.exp",
1885            sym::simd_flog10 => "llvm.log10",
1886            sym::simd_flog2 => "llvm.log2",
1887            sym::simd_flog => "llvm.log",
1888            sym::simd_floor => "llvm.floor",
1889            sym::simd_fma => "llvm.fma",
1890            sym::simd_relaxed_fma => "llvm.fmuladd",
1891            sym::simd_fsin => "llvm.sin",
1892            sym::simd_fsqrt => "llvm.sqrt",
1893            sym::simd_round => "llvm.round",
1894            sym::simd_round_ties_even => "llvm.rint",
1895            sym::simd_trunc => "llvm.trunc",
1896            _ => return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
1897        };
1898        Ok(bx.call_intrinsic(
1899            intr_name,
1900            &[vec_ty],
1901            &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1902        ))
1903    }
1904
1905    if std::matches!(
1906        name,
1907        sym::simd_ceil
1908            | sym::simd_fabs
1909            | sym::simd_fcos
1910            | sym::simd_fexp2
1911            | sym::simd_fexp
1912            | sym::simd_flog10
1913            | sym::simd_flog2
1914            | sym::simd_flog
1915            | sym::simd_floor
1916            | sym::simd_fma
1917            | sym::simd_fsin
1918            | sym::simd_fsqrt
1919            | sym::simd_relaxed_fma
1920            | sym::simd_round
1921            | sym::simd_round_ties_even
1922            | sym::simd_trunc
1923    ) {
1924        return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1925    }
1926
1927    fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) -> &'ll Type {
1928        let elem_ty = match *elem_ty.kind() {
1929            ty::Int(v) => cx.type_int_from_ty(v),
1930            ty::Uint(v) => cx.type_uint_from_ty(v),
1931            ty::Float(v) => cx.type_float_from_ty(v),
1932            ty::RawPtr(_, _) => cx.type_ptr(),
1933            _ => unreachable!(),
1934        };
1935        cx.type_vector(elem_ty, vec_len)
1936    }
1937
1938    if name == sym::simd_gather {
1939        // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1940        //             mask: <N x i{M}>) -> <N x T>
1941        // * N: number of elements in the input vectors
1942        // * T: type of the element to load
1943        // * M: any integer width is supported, will be truncated to i1
1944
1945        // All types must be simd vector types
1946
1947        // The second argument must be a simd vector with an element type that's a pointer
1948        // to the element type of the first argument
1949        let (_, element_ty0) = require_simd!(in_ty, SimdFirst);
1950        let (out_len, element_ty1) = require_simd!(args[1].layout.ty, SimdSecond);
1951        // The element type of the third argument must be a signed integer type of any width:
1952        let (out_len2, element_ty2) = require_simd!(args[2].layout.ty, SimdThird);
1953        require_simd!(ret_ty, SimdReturn);
1954
1955        // Of the same length:
1956        require!(
1957            in_len == out_len,
1958            InvalidMonomorphization::SecondArgumentLength {
1959                span,
1960                name,
1961                in_len,
1962                in_ty,
1963                arg_ty: args[1].layout.ty,
1964                out_len
1965            }
1966        );
1967        require!(
1968            in_len == out_len2,
1969            InvalidMonomorphization::ThirdArgumentLength {
1970                span,
1971                name,
1972                in_len,
1973                in_ty,
1974                arg_ty: args[2].layout.ty,
1975                out_len: out_len2
1976            }
1977        );
1978
1979        // The return type must match the first argument type
1980        require!(
1981            ret_ty == in_ty,
1982            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty }
1983        );
1984
1985        require!(
1986            matches!(
1987                *element_ty1.kind(),
1988                ty::RawPtr(p_ty, _) if p_ty == in_elem && p_ty.kind() == element_ty0.kind()
1989            ),
1990            InvalidMonomorphization::ExpectedElementType {
1991                span,
1992                name,
1993                expected_element: element_ty1,
1994                second_arg: args[1].layout.ty,
1995                in_elem,
1996                in_ty,
1997                mutability: ExpectedPointerMutability::Not,
1998            }
1999        );
2000
2001        let mask_elem_bitwidth = require_int_or_uint_ty!(
2002            element_ty2.kind(),
2003            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2004        );
2005
2006        // Alignment of T, must be a constant integer value:
2007        let alignment = bx.align_of(in_elem).bytes();
2008
2009        // Truncate the mask vector to a vector of i1s:
2010        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2011
2012        // Type of the vector of pointers:
2013        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2014
2015        // Type of the vector of elements:
2016        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2017
2018        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2019            let alignment = bx.const_i32(alignment as i32);
2020            &[args[1].immediate(), alignment, mask, args[0].immediate()]
2021        } else {
2022            &[args[1].immediate(), mask, args[0].immediate()]
2023        };
2024
2025        let call =
2026            bx.call_intrinsic("llvm.masked.gather", &[llvm_elem_vec_ty, llvm_pointer_vec_ty], args);
2027        if llvm_version >= (22, 0, 0) {
2028            crate::attributes::apply_to_callsite(
2029                call,
2030                crate::llvm::AttributePlace::Argument(0),
2031                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2032            )
2033        }
2034        return Ok(call);
2035    }
2036
2037    fn llvm_alignment<'ll, 'tcx>(
2038        bx: &mut Builder<'_, 'll, 'tcx>,
2039        alignment: SimdAlign,
2040        vector_ty: Ty<'tcx>,
2041        element_ty: Ty<'tcx>,
2042    ) -> u64 {
2043        match alignment {
2044            SimdAlign::Unaligned => 1,
2045            SimdAlign::Element => bx.align_of(element_ty).bytes(),
2046            SimdAlign::Vector => bx.align_of(vector_ty).bytes(),
2047        }
2048    }
2049
2050    if name == sym::simd_masked_load {
2051        // simd_masked_load<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *_ T, values: <N x T>) -> <N x T>
2052        // * N: number of elements in the input vectors
2053        // * T: type of the element to load
2054        // * M: any integer width is supported, will be truncated to i1
2055        // Loads contiguous elements from memory behind `pointer`, but only for
2056        // those lanes whose `mask` bit is enabled.
2057        // The memory addresses corresponding to the “off” lanes are not accessed.
2058
2059        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2060
2061        // The element type of the "mask" argument must be a signed integer type of any width
2062        let mask_ty = in_ty;
2063        let (mask_len, mask_elem) = (in_len, in_elem);
2064
2065        // The second argument must be a pointer matching the element type
2066        let pointer_ty = args[1].layout.ty;
2067
2068        // The last argument is a passthrough vector providing values for disabled lanes
2069        let values_ty = args[2].layout.ty;
2070        let (values_len, values_elem) = require_simd!(values_ty, SimdThird);
2071
2072        require_simd!(ret_ty, SimdReturn);
2073
2074        // Of the same length:
2075        require!(
2076            values_len == mask_len,
2077            InvalidMonomorphization::ThirdArgumentLength {
2078                span,
2079                name,
2080                in_len: mask_len,
2081                in_ty: mask_ty,
2082                arg_ty: values_ty,
2083                out_len: values_len
2084            }
2085        );
2086
2087        // The return type must match the last argument type
2088        require!(
2089            ret_ty == values_ty,
2090            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty }
2091        );
2092
2093        require!(
2094            matches!(
2095                *pointer_ty.kind(),
2096                ty::RawPtr(p_ty, _) if p_ty == values_elem && p_ty.kind() == values_elem.kind()
2097            ),
2098            InvalidMonomorphization::ExpectedElementType {
2099                span,
2100                name,
2101                expected_element: values_elem,
2102                second_arg: pointer_ty,
2103                in_elem: values_elem,
2104                in_ty: values_ty,
2105                mutability: ExpectedPointerMutability::Not,
2106            }
2107        );
2108
2109        let m_elem_bitwidth = require_int_or_uint_ty!(
2110            mask_elem.kind(),
2111            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2112        );
2113
2114        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2115
2116        // Alignment of T, must be a constant integer value:
2117        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2118
2119        let llvm_pointer = bx.type_ptr();
2120
2121        // Type of the vector of elements:
2122        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2123
2124        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2125            let alignment = bx.const_i32(alignment as i32);
2126
2127            &[args[1].immediate(), alignment, mask, args[2].immediate()]
2128        } else {
2129            &[args[1].immediate(), mask, args[2].immediate()]
2130        };
2131
2132        let call = bx.call_intrinsic("llvm.masked.load", &[llvm_elem_vec_ty, llvm_pointer], args);
2133        if llvm_version >= (22, 0, 0) {
2134            crate::attributes::apply_to_callsite(
2135                call,
2136                crate::llvm::AttributePlace::Argument(0),
2137                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2138            )
2139        }
2140        return Ok(call);
2141    }
2142
2143    if name == sym::simd_masked_store {
2144        // simd_masked_store<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *mut T, values: <N x T>) -> ()
2145        // * N: number of elements in the input vectors
2146        // * T: type of the element to load
2147        // * M: any integer width is supported, will be truncated to i1
2148        // Stores contiguous elements to memory behind `pointer`, but only for
2149        // those lanes whose `mask` bit is enabled.
2150        // The memory addresses corresponding to the “off” lanes are not accessed.
2151
2152        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2153
2154        // The element type of the "mask" argument must be a signed integer type of any width
2155        let mask_ty = in_ty;
2156        let (mask_len, mask_elem) = (in_len, in_elem);
2157
2158        // The second argument must be a pointer matching the element type
2159        let pointer_ty = args[1].layout.ty;
2160
2161        // The last argument specifies the values to store to memory
2162        let values_ty = args[2].layout.ty;
2163        let (values_len, values_elem) = require_simd!(values_ty, SimdThird);
2164
2165        // Of the same length:
2166        require!(
2167            values_len == mask_len,
2168            InvalidMonomorphization::ThirdArgumentLength {
2169                span,
2170                name,
2171                in_len: mask_len,
2172                in_ty: mask_ty,
2173                arg_ty: values_ty,
2174                out_len: values_len
2175            }
2176        );
2177
2178        // The second argument must be a mutable pointer type matching the element type
2179        require!(
2180            matches!(
2181                *pointer_ty.kind(),
2182                ty::RawPtr(p_ty, p_mutbl)
2183                    if p_ty == values_elem && p_ty.kind() == values_elem.kind() && p_mutbl.is_mut()
2184            ),
2185            InvalidMonomorphization::ExpectedElementType {
2186                span,
2187                name,
2188                expected_element: values_elem,
2189                second_arg: pointer_ty,
2190                in_elem: values_elem,
2191                in_ty: values_ty,
2192                mutability: ExpectedPointerMutability::Mut,
2193            }
2194        );
2195
2196        let m_elem_bitwidth = require_int_or_uint_ty!(
2197            mask_elem.kind(),
2198            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2199        );
2200
2201        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2202
2203        // Alignment of T, must be a constant integer value:
2204        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2205
2206        let llvm_pointer = bx.type_ptr();
2207
2208        // Type of the vector of elements:
2209        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2210
2211        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2212            let alignment = bx.const_i32(alignment as i32);
2213            &[args[2].immediate(), args[1].immediate(), alignment, mask]
2214        } else {
2215            &[args[2].immediate(), args[1].immediate(), mask]
2216        };
2217
2218        let call = bx.call_intrinsic("llvm.masked.store", &[llvm_elem_vec_ty, llvm_pointer], args);
2219        if llvm_version >= (22, 0, 0) {
2220            crate::attributes::apply_to_callsite(
2221                call,
2222                crate::llvm::AttributePlace::Argument(1),
2223                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2224            )
2225        }
2226        return Ok(call);
2227    }
2228
2229    if name == sym::simd_scatter {
2230        // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
2231        //             mask: <N x i{M}>) -> ()
2232        // * N: number of elements in the input vectors
2233        // * T: type of the element to load
2234        // * M: any integer width is supported, will be truncated to i1
2235
2236        // All types must be simd vector types
2237        // The second argument must be a simd vector with an element type that's a pointer
2238        // to the element type of the first argument
2239        let (_, element_ty0) = require_simd!(in_ty, SimdFirst);
2240        let (element_len1, element_ty1) = require_simd!(args[1].layout.ty, SimdSecond);
2241        let (element_len2, element_ty2) = require_simd!(args[2].layout.ty, SimdThird);
2242
2243        // Of the same length:
2244        require!(
2245            in_len == element_len1,
2246            InvalidMonomorphization::SecondArgumentLength {
2247                span,
2248                name,
2249                in_len,
2250                in_ty,
2251                arg_ty: args[1].layout.ty,
2252                out_len: element_len1
2253            }
2254        );
2255        require!(
2256            in_len == element_len2,
2257            InvalidMonomorphization::ThirdArgumentLength {
2258                span,
2259                name,
2260                in_len,
2261                in_ty,
2262                arg_ty: args[2].layout.ty,
2263                out_len: element_len2
2264            }
2265        );
2266
2267        require!(
2268            matches!(
2269                *element_ty1.kind(),
2270                ty::RawPtr(p_ty, p_mutbl)
2271                    if p_ty == in_elem && p_mutbl.is_mut() && p_ty.kind() == element_ty0.kind()
2272            ),
2273            InvalidMonomorphization::ExpectedElementType {
2274                span,
2275                name,
2276                expected_element: element_ty1,
2277                second_arg: args[1].layout.ty,
2278                in_elem,
2279                in_ty,
2280                mutability: ExpectedPointerMutability::Mut,
2281            }
2282        );
2283
2284        // The element type of the third argument must be an integer type of any width:
2285        let mask_elem_bitwidth = require_int_or_uint_ty!(
2286            element_ty2.kind(),
2287            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2288        );
2289
2290        // Alignment of T, must be a constant integer value:
2291        let alignment = bx.align_of(in_elem).bytes();
2292
2293        // Truncate the mask vector to a vector of i1s:
2294        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2295
2296        // Type of the vector of pointers:
2297        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2298
2299        // Type of the vector of elements:
2300        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2301        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2302            let alignment = bx.const_i32(alignment as i32);
2303            &[args[0].immediate(), args[1].immediate(), alignment, mask]
2304        } else {
2305            &[args[0].immediate(), args[1].immediate(), mask]
2306        };
2307        let call = bx.call_intrinsic(
2308            "llvm.masked.scatter",
2309            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2310            args,
2311        );
2312        if llvm_version >= (22, 0, 0) {
2313            crate::attributes::apply_to_callsite(
2314                call,
2315                crate::llvm::AttributePlace::Argument(1),
2316                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2317            )
2318        }
2319        return Ok(call);
2320    }
2321
2322    macro_rules! arith_red {
2323        ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
2324         $identity:expr) => {
2325            if name == sym::$name {
2326                require!(
2327                    ret_ty == in_elem,
2328                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2329                );
2330                return match in_elem.kind() {
2331                    ty::Int(_) | ty::Uint(_) => {
2332                        let r = bx.$integer_reduce(args[0].immediate());
2333                        if $ordered {
2334                            // if overflow occurs, the result is the
2335                            // mathematical result modulo 2^n:
2336                            Ok(bx.$op(args[1].immediate(), r))
2337                        } else {
2338                            Ok(bx.$integer_reduce(args[0].immediate()))
2339                        }
2340                    }
2341                    ty::Float(f) => {
2342                        let acc = if $ordered {
2343                            // ordered arithmetic reductions take an accumulator
2344                            args[1].immediate()
2345                        } else {
2346                            // unordered arithmetic reductions use the identity accumulator
2347                            match f.bit_width() {
2348                                32 => bx.const_real(bx.type_f32(), $identity),
2349                                64 => bx.const_real(bx.type_f64(), $identity),
2350                                v => return_error!(
2351                                    InvalidMonomorphization::UnsupportedSymbolOfSize {
2352                                        span,
2353                                        name,
2354                                        symbol: sym::$name,
2355                                        in_ty,
2356                                        in_elem,
2357                                        size: v,
2358                                        ret_ty
2359                                    }
2360                                ),
2361                            }
2362                        };
2363                        Ok(bx.$float_reduce(acc, args[0].immediate()))
2364                    }
2365                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2366                        span,
2367                        name,
2368                        symbol: sym::$name,
2369                        in_ty,
2370                        in_elem,
2371                        ret_ty
2372                    }),
2373                };
2374            }
2375        };
2376    }
2377
2378    arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, -0.0);
2379    arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
2380    arith_red!(
2381        simd_reduce_add_unordered: vector_reduce_add,
2382        vector_reduce_fadd_reassoc,
2383        false,
2384        add,
2385        -0.0
2386    );
2387    arith_red!(
2388        simd_reduce_mul_unordered: vector_reduce_mul,
2389        vector_reduce_fmul_reassoc,
2390        false,
2391        mul,
2392        1.0
2393    );
2394
2395    macro_rules! minmax_red {
2396        ($name:ident: $int_red:ident, $float_red:ident) => {
2397            if name == sym::$name {
2398                require!(
2399                    ret_ty == in_elem,
2400                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2401                );
2402                return match in_elem.kind() {
2403                    ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
2404                    ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
2405                    ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
2406                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2407                        span,
2408                        name,
2409                        symbol: sym::$name,
2410                        in_ty,
2411                        in_elem,
2412                        ret_ty
2413                    }),
2414                };
2415            }
2416        };
2417    }
2418
2419    minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
2420    minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
2421
2422    macro_rules! bitwise_red {
2423        ($name:ident : $red:ident, $boolean:expr) => {
2424            if name == sym::$name {
2425                let input = if !$boolean {
2426                    require!(
2427                        ret_ty == in_elem,
2428                        InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2429                    );
2430                    args[0].immediate()
2431                } else {
2432                    let bitwidth = match in_elem.kind() {
2433                        ty::Int(i) => {
2434                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2435                        }
2436                        ty::Uint(i) => {
2437                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2438                        }
2439                        _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2440                            span,
2441                            name,
2442                            symbol: sym::$name,
2443                            in_ty,
2444                            in_elem,
2445                            ret_ty
2446                        }),
2447                    };
2448
2449                    vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth, in_len as _)
2450                };
2451                return match in_elem.kind() {
2452                    ty::Int(_) | ty::Uint(_) => {
2453                        let r = bx.$red(input);
2454                        Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2455                    }
2456                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2457                        span,
2458                        name,
2459                        symbol: sym::$name,
2460                        in_ty,
2461                        in_elem,
2462                        ret_ty
2463                    }),
2464                };
2465            }
2466        };
2467    }
2468
2469    bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2470    bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2471    bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2472    bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2473    bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2474
2475    if name == sym::simd_cast_ptr {
2476        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2477        require!(
2478            in_len == out_len,
2479            InvalidMonomorphization::ReturnLengthInputType {
2480                span,
2481                name,
2482                in_len,
2483                in_ty,
2484                ret_ty,
2485                out_len
2486            }
2487        );
2488
2489        match in_elem.kind() {
2490            ty::RawPtr(p_ty, _) => {
2491                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
2492                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
2493                });
2494                require!(
2495                    metadata.is_unit(),
2496                    InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem }
2497                );
2498            }
2499            _ => {
2500                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
2501            }
2502        }
2503        match out_elem.kind() {
2504            ty::RawPtr(p_ty, _) => {
2505                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
2506                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
2507                });
2508                require!(
2509                    metadata.is_unit(),
2510                    InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem }
2511                );
2512            }
2513            _ => {
2514                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
2515            }
2516        }
2517
2518        return Ok(args[0].immediate());
2519    }
2520
2521    if name == sym::simd_expose_provenance {
2522        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2523        require!(
2524            in_len == out_len,
2525            InvalidMonomorphization::ReturnLengthInputType {
2526                span,
2527                name,
2528                in_len,
2529                in_ty,
2530                ret_ty,
2531                out_len
2532            }
2533        );
2534
2535        match in_elem.kind() {
2536            ty::RawPtr(_, _) => {}
2537            _ => {
2538                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
2539            }
2540        }
2541        match out_elem.kind() {
2542            ty::Uint(ty::UintTy::Usize) => {}
2543            _ => return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: out_elem }),
2544        }
2545
2546        return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
2547    }
2548
2549    if name == sym::simd_with_exposed_provenance {
2550        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2551        require!(
2552            in_len == out_len,
2553            InvalidMonomorphization::ReturnLengthInputType {
2554                span,
2555                name,
2556                in_len,
2557                in_ty,
2558                ret_ty,
2559                out_len
2560            }
2561        );
2562
2563        match in_elem.kind() {
2564            ty::Uint(ty::UintTy::Usize) => {}
2565            _ => return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: in_elem }),
2566        }
2567        match out_elem.kind() {
2568            ty::RawPtr(_, _) => {}
2569            _ => {
2570                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
2571            }
2572        }
2573
2574        return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
2575    }
2576
2577    if name == sym::simd_cast || name == sym::simd_as {
2578        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2579        require!(
2580            in_len == out_len,
2581            InvalidMonomorphization::ReturnLengthInputType {
2582                span,
2583                name,
2584                in_len,
2585                in_ty,
2586                ret_ty,
2587                out_len
2588            }
2589        );
2590        // casting cares about nominal type, not just structural type
2591        if in_elem == out_elem {
2592            return Ok(args[0].immediate());
2593        }
2594
2595        #[derive(Copy, Clone)]
2596        enum Sign {
2597            Unsigned,
2598            Signed,
2599        }
2600        use Sign::*;
2601
2602        enum Style {
2603            Float,
2604            Int(Sign),
2605            Unsupported,
2606        }
2607
2608        let (in_style, in_width) = match in_elem.kind() {
2609            // vectors of pointer-sized integers should've been
2610            // disallowed before here, so this unwrap is safe.
2611            ty::Int(i) => (
2612                Style::Int(Signed),
2613                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2614            ),
2615            ty::Uint(u) => (
2616                Style::Int(Unsigned),
2617                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2618            ),
2619            ty::Float(f) => (Style::Float, f.bit_width()),
2620            _ => (Style::Unsupported, 0),
2621        };
2622        let (out_style, out_width) = match out_elem.kind() {
2623            ty::Int(i) => (
2624                Style::Int(Signed),
2625                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2626            ),
2627            ty::Uint(u) => (
2628                Style::Int(Unsigned),
2629                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2630            ),
2631            ty::Float(f) => (Style::Float, f.bit_width()),
2632            _ => (Style::Unsupported, 0),
2633        };
2634
2635        match (in_style, out_style) {
2636            (Style::Int(sign), Style::Int(_)) => {
2637                return Ok(match in_width.cmp(&out_width) {
2638                    Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2639                    Ordering::Equal => args[0].immediate(),
2640                    Ordering::Less => match sign {
2641                        Sign::Signed => bx.sext(args[0].immediate(), llret_ty),
2642                        Sign::Unsigned => bx.zext(args[0].immediate(), llret_ty),
2643                    },
2644                });
2645            }
2646            (Style::Int(Sign::Signed), Style::Float) => {
2647                return Ok(bx.sitofp(args[0].immediate(), llret_ty));
2648            }
2649            (Style::Int(Sign::Unsigned), Style::Float) => {
2650                return Ok(bx.uitofp(args[0].immediate(), llret_ty));
2651            }
2652            (Style::Float, Style::Int(sign)) => {
2653                return Ok(match (sign, name == sym::simd_as) {
2654                    (Sign::Unsigned, false) => bx.fptoui(args[0].immediate(), llret_ty),
2655                    (Sign::Signed, false) => bx.fptosi(args[0].immediate(), llret_ty),
2656                    (_, true) => bx.cast_float_to_int(
2657                        matches!(sign, Sign::Signed),
2658                        args[0].immediate(),
2659                        llret_ty,
2660                    ),
2661                });
2662            }
2663            (Style::Float, Style::Float) => {
2664                return Ok(match in_width.cmp(&out_width) {
2665                    Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2666                    Ordering::Equal => args[0].immediate(),
2667                    Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2668                });
2669            }
2670            _ => { /* Unsupported. Fallthrough. */ }
2671        }
2672        return_error!(InvalidMonomorphization::UnsupportedCast {
2673            span,
2674            name,
2675            in_ty,
2676            in_elem,
2677            ret_ty,
2678            out_elem
2679        });
2680    }
2681    macro_rules! arith_binary {
2682        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2683            $(if name == sym::$name {
2684                match in_elem.kind() {
2685                    $($(ty::$p(_))|* => {
2686                        return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2687                    })*
2688                    _ => {},
2689                }
2690                return_error!(
2691                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
2692                );
2693            })*
2694        }
2695    }
2696    arith_binary! {
2697        simd_add: Uint, Int => add, Float => fadd;
2698        simd_sub: Uint, Int => sub, Float => fsub;
2699        simd_mul: Uint, Int => mul, Float => fmul;
2700        simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2701        simd_rem: Uint => urem, Int => srem, Float => frem;
2702        simd_shl: Uint, Int => shl;
2703        simd_shr: Uint => lshr, Int => ashr;
2704        simd_and: Uint, Int => and;
2705        simd_or: Uint, Int => or;
2706        simd_xor: Uint, Int => xor;
2707        simd_fmax: Float => maxnum;
2708        simd_fmin: Float => minnum;
2709
2710    }
2711    macro_rules! arith_unary {
2712        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2713            $(if name == sym::$name {
2714                match in_elem.kind() {
2715                    $($(ty::$p(_))|* => {
2716                        return Ok(bx.$call(args[0].immediate()))
2717                    })*
2718                    _ => {},
2719                }
2720                return_error!(
2721                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
2722                );
2723            })*
2724        }
2725    }
2726    arith_unary! {
2727        simd_neg: Int => neg, Float => fneg;
2728    }
2729
2730    // Unary integer intrinsics
2731    if matches!(
2732        name,
2733        sym::simd_bswap
2734            | sym::simd_bitreverse
2735            | sym::simd_ctlz
2736            | sym::simd_ctpop
2737            | sym::simd_cttz
2738            | sym::simd_funnel_shl
2739            | sym::simd_funnel_shr
2740    ) {
2741        let vec_ty = bx.cx.type_vector(
2742            match *in_elem.kind() {
2743                ty::Int(i) => bx.cx.type_int_from_ty(i),
2744                ty::Uint(i) => bx.cx.type_uint_from_ty(i),
2745                _ => return_error!(InvalidMonomorphization::UnsupportedOperation {
2746                    span,
2747                    name,
2748                    in_ty,
2749                    in_elem
2750                }),
2751            },
2752            in_len as u64,
2753        );
2754        let llvm_intrinsic = match name {
2755            sym::simd_bswap => "llvm.bswap",
2756            sym::simd_bitreverse => "llvm.bitreverse",
2757            sym::simd_ctlz => "llvm.ctlz",
2758            sym::simd_ctpop => "llvm.ctpop",
2759            sym::simd_cttz => "llvm.cttz",
2760            sym::simd_funnel_shl => "llvm.fshl",
2761            sym::simd_funnel_shr => "llvm.fshr",
2762            _ => unreachable!(),
2763        };
2764        let int_size = in_elem.int_size_and_signed(bx.tcx()).0.bits();
2765
2766        return match name {
2767            // byte swap is no-op for i8/u8
2768            sym::simd_bswap if int_size == 8 => Ok(args[0].immediate()),
2769            sym::simd_ctlz | sym::simd_cttz => {
2770                // for the (int, i1 immediate) pair, the second arg adds `(0, true) => poison`
2771                let dont_poison_on_zero = bx.const_int(bx.type_i1(), 0);
2772                Ok(bx.call_intrinsic(
2773                    llvm_intrinsic,
2774                    &[vec_ty],
2775                    &[args[0].immediate(), dont_poison_on_zero],
2776                ))
2777            }
2778            sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctpop => {
2779                // simple unary argument cases
2780                Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[args[0].immediate()]))
2781            }
2782            sym::simd_funnel_shl | sym::simd_funnel_shr => Ok(bx.call_intrinsic(
2783                llvm_intrinsic,
2784                &[vec_ty],
2785                &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
2786            )),
2787            _ => unreachable!(),
2788        };
2789    }
2790
2791    if name == sym::simd_arith_offset {
2792        // This also checks that the first operand is a ptr type.
2793        let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
2794            span_bug!(span, "must be called with a vector of pointer types as first argument")
2795        });
2796        let layout = bx.layout_of(pointee);
2797        let ptrs = args[0].immediate();
2798        // The second argument must be a ptr-sized integer.
2799        // (We don't care about the signedness, this is wrapping anyway.)
2800        let (_offsets_len, offsets_elem) = args[1].layout.ty.simd_size_and_type(bx.tcx());
2801        if !matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
2802            span_bug!(
2803                span,
2804                "must be called with a vector of pointer-sized integers as second argument"
2805            );
2806        }
2807        let offsets = args[1].immediate();
2808
2809        return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
2810    }
2811
2812    if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2813        let lhs = args[0].immediate();
2814        let rhs = args[1].immediate();
2815        let is_add = name == sym::simd_saturating_add;
2816        let (signed, elem_ty) = match *in_elem.kind() {
2817            ty::Int(i) => (true, bx.cx.type_int_from_ty(i)),
2818            ty::Uint(i) => (false, bx.cx.type_uint_from_ty(i)),
2819            _ => {
2820                return_error!(InvalidMonomorphization::ExpectedVectorElementType {
2821                    span,
2822                    name,
2823                    expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
2824                    vector_type: args[0].layout.ty
2825                });
2826            }
2827        };
2828        let llvm_intrinsic = format!(
2829            "llvm.{}{}.sat",
2830            if signed { 's' } else { 'u' },
2831            if is_add { "add" } else { "sub" },
2832        );
2833        let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2834
2835        return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs]));
2836    }
2837
2838    span_bug!(span, "unknown SIMD intrinsic");
2839}