Skip to main content

rustc_codegen_llvm/
builder.rs

1use std::borrow::{Borrow, Cow};
2use std::iter;
3use std::ops::Deref;
4
5use rustc_ast::expand::typetree::FncTree;
6pub(crate) mod autodiff;
7pub(crate) mod gpu_offload;
8
9use libc::{c_char, c_uint};
10use rustc_abi as abi;
11use rustc_abi::{Align, Size, WrappingRange};
12use rustc_codegen_ssa::MemFlags;
13use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
14use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
15use rustc_codegen_ssa::mir::place::PlaceRef;
16use rustc_codegen_ssa::traits::*;
17use rustc_data_structures::small_c_str::SmallCStr;
18use rustc_hir::def_id::DefId;
19use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature, TargetFeatureKind};
20use rustc_middle::ty::layout::{
21    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22    TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::Span;
28use rustc_target::callconv::{FnAbi, PassMode};
29use rustc_target::spec::{Arch, HasTargetSpec, SanitizerSet, Target};
30use smallvec::SmallVec;
31use tracing::{debug, instrument};
32
33use crate::abi::FnAbiLlvmExt;
34use crate::attributes;
35use crate::common::Funclet;
36use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
37use crate::llvm::{
38    self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE,
39    ToLlvmBool, Type, Value,
40};
41use crate::type_of::LayoutLlvmExt;
42
43#[must_use]
44pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
45    pub llbuilder: &'ll mut llvm::Builder<'ll>,
46    pub cx: &'a GenericCx<'ll, CX>,
47}
48
49pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
50pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
51
52impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
53    fn drop(&mut self) {
54        unsafe {
55            llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
56        }
57    }
58}
59
60impl<'a, 'll> SBuilder<'a, 'll> {
61    pub(crate) fn call(
62        &mut self,
63        llty: &'ll Type,
64        llfn: &'ll Value,
65        args: &[&'ll Value],
66        funclet: Option<&Funclet<'ll>>,
67    ) -> &'ll Value {
68        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:68",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(68u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
69
70        let args = self.check_call("call", llty, llfn, args);
71        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
72        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
73        if let Some(funclet_bundle) = funclet_bundle {
74            bundles.push(funclet_bundle);
75        }
76
77        let call = unsafe {
78            llvm::LLVMBuildCallWithOperandBundles(
79                self.llbuilder,
80                llty,
81                llfn,
82                args.as_ptr() as *const &llvm::Value,
83                args.len() as c_uint,
84                bundles.as_ptr(),
85                bundles.len() as c_uint,
86                c"".as_ptr(),
87            )
88        };
89        call
90    }
91}
92
93impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
94    fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
95        // Create a fresh builder from the simple context.
96        let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
97        GenericBuilder { llbuilder, cx: scx }
98    }
99
100    pub(crate) fn append_block(
101        cx: &'a GenericCx<'ll, CX>,
102        llfn: &'ll Value,
103        name: &str,
104    ) -> &'ll BasicBlock {
105        unsafe {
106            let name = SmallCStr::new(name);
107            llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
108        }
109    }
110
111    pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
112        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
113    }
114
115    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
116        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
117    }
118
119    pub(crate) fn ret_void(&mut self) {
120        llvm::LLVMBuildRetVoid(self.llbuilder);
121    }
122
123    pub(crate) fn ret(&mut self, v: &'ll Value) {
124        unsafe {
125            llvm::LLVMBuildRet(self.llbuilder, v);
126        }
127    }
128
129    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
130        let bx = Self::with_cx(cx);
131        unsafe {
132            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
133        }
134        bx
135    }
136
137    // The generic builder has less functionality and thus (unlike the other alloca) we can not
138    // easily jump to the beginning of the function to place our allocas there. We trust the user
139    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
140    // handle this.
141    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
142        let val = unsafe {
143            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
144            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
145            // Cast to default addrspace if necessary
146            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
147        };
148        if name != "" {
149            let name = std::ffi::CString::new(name).unwrap();
150            llvm::set_value_name(val, &name.as_bytes());
151        }
152        val
153    }
154
155    pub(crate) fn inbounds_gep(
156        &mut self,
157        ty: &'ll Type,
158        ptr: &'ll Value,
159        indices: &[&'ll Value],
160    ) -> &'ll Value {
161        unsafe {
162            llvm::LLVMBuildGEPWithNoWrapFlags(
163                self.llbuilder,
164                ty,
165                ptr,
166                indices.as_ptr(),
167                indices.len() as c_uint,
168                UNNAMED,
169                GEPNoWrapFlags::InBounds,
170            )
171        }
172    }
173
174    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
175        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:175",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(175u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
176        match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
177        unsafe {
178            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
179            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
180            store
181        }
182    }
183
184    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
185        unsafe {
186            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
187            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
188            load
189        }
190    }
191}
192
193/// Empty string, to be used where LLVM expects an instruction name, indicating
194/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
195// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
196pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
197
198impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
199    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
200    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
201    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
202
203    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
204    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
205    type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
206
207    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
208    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
209    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
210}
211
212impl abi::HasDataLayout for Builder<'_, '_, '_> {
213    fn data_layout(&self) -> &abi::TargetDataLayout {
214        self.cx.data_layout()
215    }
216}
217
218impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
219    #[inline]
220    fn tcx(&self) -> TyCtxt<'tcx> {
221        self.cx.tcx
222    }
223}
224
225impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
226    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
227        self.cx.typing_env()
228    }
229}
230
231impl HasTargetSpec for Builder<'_, '_, '_> {
232    #[inline]
233    fn target_spec(&self) -> &Target {
234        self.cx.target_spec()
235    }
236}
237
238impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
239    #[inline]
240    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
241        self.cx.handle_layout_err(err, span, ty)
242    }
243}
244
245impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
246    #[inline]
247    fn handle_fn_abi_err(
248        &self,
249        err: FnAbiError<'tcx>,
250        span: Span,
251        fn_abi_request: FnAbiRequest<'tcx>,
252    ) -> ! {
253        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
254    }
255}
256
257impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
258    type Target = CodegenCx<'ll, 'tcx>;
259
260    #[inline]
261    fn deref(&self) -> &Self::Target {
262        self.cx
263    }
264}
265
266macro_rules! math_builder_methods {
267    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
268        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
269            unsafe {
270                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
271            }
272        })+
273    }
274}
275
276macro_rules! set_math_builder_methods {
277    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
278        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
279            unsafe {
280                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
281                llvm::$llvm_set_math(instr);
282                instr
283            }
284        })+
285    }
286}
287
288impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
289    type CodegenCx = CodegenCx<'ll, 'tcx>;
290
291    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
292        let bx = Builder::with_cx(cx);
293        unsafe {
294            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
295        }
296        bx
297    }
298
299    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
300        self.cx
301    }
302
303    fn llbb(&self) -> &'ll BasicBlock {
304        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
305    }
306
307    fn set_span(&mut self, _span: Span) {}
308
309    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
310        unsafe {
311            let name = SmallCStr::new(name);
312            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
313        }
314    }
315
316    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
317        Self::append_block(self.cx, self.llfn(), name)
318    }
319
320    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
321        *self = Self::build(self.cx, llbb)
322    }
323
324    fn ret_void(&mut self) {
325        llvm::LLVMBuildRetVoid(self.llbuilder);
326    }
327
328    fn ret(&mut self, v: &'ll Value) {
329        unsafe {
330            llvm::LLVMBuildRet(self.llbuilder, v);
331        }
332    }
333
334    fn br(&mut self, dest: &'ll BasicBlock) {
335        unsafe {
336            llvm::LLVMBuildBr(self.llbuilder, dest);
337        }
338    }
339
340    fn cond_br(
341        &mut self,
342        cond: &'ll Value,
343        then_llbb: &'ll BasicBlock,
344        else_llbb: &'ll BasicBlock,
345    ) {
346        unsafe {
347            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
348        }
349    }
350
351    fn switch(
352        &mut self,
353        v: &'ll Value,
354        else_llbb: &'ll BasicBlock,
355        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
356    ) {
357        let switch =
358            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
359        for (on_val, dest) in cases {
360            let on_val = self.const_uint_big(self.val_ty(v), on_val);
361            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
362        }
363    }
364
365    fn switch_with_weights(
366        &mut self,
367        v: Self::Value,
368        else_llbb: Self::BasicBlock,
369        else_is_cold: bool,
370        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
371    ) {
372        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
373            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
374            return;
375        }
376
377        let id = self.cx.create_metadata(b"branch_weights");
378
379        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
380        // This function handles switch instructions with more than 2 targets and it needs to
381        // emit branch weights metadata instead of using the intrinsic.
382        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
383        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
384        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
385        let weight =
386            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
387
388        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
389        md.push(id);
390        md.push(weight(else_is_cold));
391
392        let switch =
393            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
394        for (on_val, dest, is_cold) in cases {
395            let on_val = self.const_uint_big(self.val_ty(v), on_val);
396            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
397            md.push(weight(is_cold));
398        }
399
400        self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
401    }
402
403    fn invoke(
404        &mut self,
405        llty: &'ll Type,
406        fn_attrs: Option<&CodegenFnAttrs>,
407        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
408        llfn: &'ll Value,
409        args: &[&'ll Value],
410        then: &'ll BasicBlock,
411        catch: &'ll BasicBlock,
412        funclet: Option<&Funclet<'ll>>,
413        instance: Option<Instance<'tcx>>,
414    ) -> &'ll Value {
415        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:415",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(415u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
416
417        let args = self.check_call("invoke", llty, llfn, args);
418        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
419        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
420        if let Some(funclet_bundle) = funclet_bundle {
421            bundles.push(funclet_bundle);
422        }
423
424        // Emit CFI pointer type membership test
425        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
426
427        // Emit KCFI operand bundle
428        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
429        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
430            bundles.push(kcfi_bundle);
431        }
432
433        let invoke = unsafe {
434            llvm::LLVMBuildInvokeWithOperandBundles(
435                self.llbuilder,
436                llty,
437                llfn,
438                args.as_ptr(),
439                args.len() as c_uint,
440                then,
441                catch,
442                bundles.as_ptr(),
443                bundles.len() as c_uint,
444                UNNAMED,
445            )
446        };
447        if let Some(fn_abi) = fn_abi {
448            fn_abi.apply_attrs_callsite(self, invoke);
449        }
450        invoke
451    }
452
453    fn unreachable(&mut self) {
454        unsafe {
455            llvm::LLVMBuildUnreachable(self.llbuilder);
456        }
457    }
458
459    self
&'ll Value
x
&'ll Value
y
&'ll Value
unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }math_builder_methods! {
460        add(a, b) => LLVMBuildAdd,
461        fadd(a, b) => LLVMBuildFAdd,
462        sub(a, b) => LLVMBuildSub,
463        fsub(a, b) => LLVMBuildFSub,
464        mul(a, b) => LLVMBuildMul,
465        fmul(a, b) => LLVMBuildFMul,
466        udiv(a, b) => LLVMBuildUDiv,
467        exactudiv(a, b) => LLVMBuildExactUDiv,
468        sdiv(a, b) => LLVMBuildSDiv,
469        exactsdiv(a, b) => LLVMBuildExactSDiv,
470        fdiv(a, b) => LLVMBuildFDiv,
471        urem(a, b) => LLVMBuildURem,
472        srem(a, b) => LLVMBuildSRem,
473        frem(a, b) => LLVMBuildFRem,
474        shl(a, b) => LLVMBuildShl,
475        lshr(a, b) => LLVMBuildLShr,
476        ashr(a, b) => LLVMBuildAShr,
477        and(a, b) => LLVMBuildAnd,
478        or(a, b) => LLVMBuildOr,
479        xor(a, b) => LLVMBuildXor,
480        neg(x) => LLVMBuildNeg,
481        fneg(x) => LLVMBuildFNeg,
482        not(x) => LLVMBuildNot,
483        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
484        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
485        unchecked_ssub(x, y) => LLVMBuildNSWSub,
486        unchecked_usub(x, y) => LLVMBuildNUWSub,
487        unchecked_smul(x, y) => LLVMBuildNSWMul,
488        unchecked_umul(x, y) => LLVMBuildNUWMul,
489    }
490
491    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
492        unsafe {
493            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
494            if llvm::LLVMIsAInstruction(add).is_some() {
495                llvm::LLVMSetNUW(add, TRUE);
496                llvm::LLVMSetNSW(add, TRUE);
497            }
498            add
499        }
500    }
501    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
502        unsafe {
503            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
504            if llvm::LLVMIsAInstruction(sub).is_some() {
505                llvm::LLVMSetNUW(sub, TRUE);
506                llvm::LLVMSetNSW(sub, TRUE);
507            }
508            sub
509        }
510    }
511    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
512        unsafe {
513            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
514            if llvm::LLVMIsAInstruction(mul).is_some() {
515                llvm::LLVMSetNUW(mul, TRUE);
516                llvm::LLVMSetNSW(mul, TRUE);
517            }
518            mul
519        }
520    }
521
522    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
523        unsafe {
524            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
525
526            // If a and b are both values, then `or` is a value, rather than
527            // an instruction, so we need to check before setting the flag.
528            // (See also `LLVMBuildNUWNeg` which also needs a check.)
529            if llvm::LLVMIsAInstruction(or).is_some() {
530                llvm::LLVMSetIsDisjoint(or, TRUE);
531            }
532            or
533        }
534    }
535
536    self
&'ll Value
x
&'ll Value
y
&'ll Value
unsafe {
    let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
    llvm::LLVMRustSetAlgebraicMath(instr);
    instr
}set_math_builder_methods! {
537        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
538        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
539        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
540        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
541        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
542        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
543        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
544        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
545        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
546        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
547    }
548
549    fn checked_binop(
550        &mut self,
551        oop: OverflowOp,
552        ty: Ty<'tcx>,
553        lhs: Self::Value,
554        rhs: Self::Value,
555    ) -> (Self::Value, Self::Value) {
556        let (size, signed) = ty.int_size_and_signed(self.tcx);
557        let width = size.bits();
558
559        if !signed {
560            match oop {
561                OverflowOp::Sub => {
562                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
563                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
564                    // in the backend if profitable.
565                    let sub = self.sub(lhs, rhs);
566                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
567                    return (sub, cmp);
568                }
569                OverflowOp::Add => {
570                    // Like with sub above, using icmp is the preferred form. See
571                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
572                    let add = self.add(lhs, rhs);
573                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
574                    return (add, cmp);
575                }
576                OverflowOp::Mul => {}
577            }
578        }
579
580        let oop_str = match oop {
581            OverflowOp::Add => "add",
582            OverflowOp::Sub => "sub",
583            OverflowOp::Mul => "mul",
584        };
585
586        let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.with.overflow",
                if signed { 's' } else { 'u' }, oop_str))
    })format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
587
588        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
589        (self.extract_value(res, 0), self.extract_value(res, 1))
590    }
591
592    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
593        if self.cx().val_ty(val) == self.cx().type_i1() {
594            self.zext(val, self.cx().type_i8())
595        } else {
596            val
597        }
598    }
599
600    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
601        if scalar.is_bool() {
602            return self.unchecked_utrunc(val, self.cx().type_i1());
603        }
604        val
605    }
606
607    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
608        let mut bx = Builder::with_cx(self.cx);
609        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
610        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
611        unsafe {
612            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
613            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
614            // Cast to default addrspace if necessary
615            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
616        }
617    }
618
619    fn scalable_alloca(&mut self, elt: u64, align: Align, element_ty: Ty<'_>) -> Self::Value {
620        let mut bx = Builder::with_cx(self.cx);
621        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
622        let llvm_ty = match element_ty.kind() {
623            ty::Bool => bx.type_i1(),
624            ty::Int(int_ty) => self.cx.type_int_from_ty(*int_ty),
625            ty::Uint(uint_ty) => self.cx.type_uint_from_ty(*uint_ty),
626            ty::Float(float_ty) => self.cx.type_float_from_ty(*float_ty),
627            _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("scalable vectors can only contain a bool, int, uint or float")));
}unreachable!("scalable vectors can only contain a bool, int, uint or float"),
628        };
629
630        unsafe {
631            let ty = llvm::LLVMScalableVectorType(llvm_ty, elt.try_into().unwrap());
632            let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, ty, UNNAMED);
633            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
634            alloca
635        }
636    }
637
638    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
639        unsafe {
640            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
641            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
642            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
643            load
644        }
645    }
646
647    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
648        unsafe {
649            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
650            llvm::LLVMSetVolatile(load, llvm::TRUE);
651            load
652        }
653    }
654
655    fn atomic_load(
656        &mut self,
657        ty: &'ll Type,
658        ptr: &'ll Value,
659        order: rustc_middle::ty::AtomicOrdering,
660        size: Size,
661    ) -> &'ll Value {
662        unsafe {
663            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
664            // Set atomic ordering
665            llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
666            // LLVM requires the alignment of atomic loads to be at least the size of the type.
667            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
668            load
669        }
670    }
671
672    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("load_operand",
                                    "rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(672u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&["place"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: OperandRef<'tcx, &'ll Value> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if place.layout.is_unsized() {
                let tail =
                    self.tcx.struct_tail_for_codegen(place.layout.ty,
                        self.typing_env());
                if #[allow(non_exhaustive_omitted_patterns)] match tail.kind()
                        {
                        ty::Foreign(..) => true,
                        _ => false,
                    } {
                    {
                        ::core::panicking::panic_fmt(format_args!("unsized locals must not be `extern` types"));
                    };
                }
            }
            match (&place.val.llextra.is_some(), &place.layout.is_unsized()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            if place.layout.is_zst() {
                return OperandRef::zero_sized(place.layout);
            }
            fn scalar_load_metadata<'a, 'll,
                'tcx>(bx: &mut Builder<'a, 'll, 'tcx>, load: &'ll Value,
                scalar: abi::Scalar, layout: TyAndLayout<'tcx>,
                offset: Size) {
                {}

                #[allow(clippy :: suspicious_else_formatting)]
                {
                    let __tracing_attr_span;
                    let __tracing_attr_guard;
                    if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() ||
                            { false } {
                        __tracing_attr_span =
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("scalar_load_metadata",
                                                    "rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(689u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                                    ::tracing_core::field::FieldSet::new(&["load", "scalar",
                                                                    "layout", "offset"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::SPAN)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let mut interest = ::tracing::subscriber::Interest::never();
                                if ::tracing::Level::TRACE <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::TRACE <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            { interest = __CALLSITE.interest(); !interest.is_never() }
                                        &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest) {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Span::new(meta,
                                        &{
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = meta.fields().iter();
                                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
                                                                            as &dyn Value))])
                                            })
                                } else {
                                    let span =
                                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                                    {};
                                    span
                                }
                            };
                        __tracing_attr_guard = __tracing_attr_span.enter();
                    }

                    #[warn(clippy :: suspicious_else_formatting)]
                    {

                        #[allow(unknown_lints, unreachable_code, clippy ::
                        diverging_sub_expression, clippy :: empty_loop, clippy ::
                        let_unit_value, clippy :: let_with_type_underscore, clippy
                        :: needless_return, clippy :: unreachable)]
                        if false {
                            let __tracing_attr_fake_return: () = loop {};
                            return __tracing_attr_fake_return;
                        }
                        {
                            if bx.cx.sess().opts.optimize == OptLevel::No { return; }
                            if !scalar.is_uninit_valid() { bx.noundef_metadata(load); }
                            match scalar.primitive() {
                                abi::Primitive::Int(..) => {
                                    if !scalar.is_always_valid(bx) {
                                        bx.range_metadata(load, scalar.valid_range(bx));
                                    }
                                }
                                abi::Primitive::Pointer(_) => {
                                    if !scalar.valid_range(bx).contains(0) {
                                        bx.nonnull_metadata(load);
                                    }
                                    if let Some(pointee) = layout.pointee_info_at(bx, offset) &&
                                            pointee.align > Align::ONE {
                                        bx.align_metadata(load, pointee.align);
                                    }
                                }
                                abi::Primitive::Float(_) => {}
                            }
                        }
                    }
                }
            }
            let val =
                if let Some(_) = place.val.llextra {
                    OperandValue::Ref(place.val)
                } else if place.layout.is_llvm_immediate() {
                    let mut const_llval = None;
                    let llty = place.layout.llvm_type(self);
                    if let Some(global) =
                            llvm::LLVMIsAGlobalVariable(place.val.llval) {
                        if llvm::LLVMIsGlobalConstant(global).is_true() {
                            if let Some(init) = llvm::LLVMGetInitializer(global) {
                                if self.val_ty(init) == llty { const_llval = Some(init); }
                            }
                        }
                    }
                    let llval =
                        const_llval.unwrap_or_else(||
                                {
                                    let load =
                                        self.load(llty, place.val.llval, place.val.align);
                                    if let abi::BackendRepr::Scalar(scalar) =
                                            place.layout.backend_repr {
                                        scalar_load_metadata(self, load, scalar, place.layout,
                                            Size::ZERO);
                                        self.to_immediate_scalar(load, scalar)
                                    } else { load }
                                });
                    OperandValue::Immediate(llval)
                } else if let abi::BackendRepr::ScalarPair(a, b) =
                        place.layout.backend_repr {
                    let b_offset = a.size(self).align_to(b.align(self).abi);
                    let mut load =
                        |i, scalar: abi::Scalar, layout, align, offset|
                            {
                                let llptr =
                                    if i == 0 {
                                        place.val.llval
                                    } else {
                                        self.inbounds_ptradd(place.val.llval,
                                            self.const_usize(b_offset.bytes()))
                                    };
                                let llty =
                                    place.layout.scalar_pair_element_llvm_type(self, i, false);
                                let load = self.load(llty, llptr, align);
                                scalar_load_metadata(self, load, scalar, layout, offset);
                                self.to_immediate_scalar(load, scalar)
                            };
                    OperandValue::Pair(load(0, a, place.layout, place.val.align,
                            Size::ZERO),
                        load(1, b, place.layout,
                            place.val.align.restrict_for_offset(b_offset), b_offset))
                } else { OperandValue::Ref(place.val) };
            OperandRef { val, layout: place.layout, move_annotation: None }
        }
    }
}#[instrument(level = "trace", skip(self))]
673    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
674        if place.layout.is_unsized() {
675            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
676            if matches!(tail.kind(), ty::Foreign(..)) {
677                // Unsized locals and, at least conceptually, even unsized arguments must be copied
678                // around, which requires dynamically determining their size. Therefore, we cannot
679                // allow `extern` types here. Consult t-opsem before removing this check.
680                panic!("unsized locals must not be `extern` types");
681            }
682        }
683        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
684
685        if place.layout.is_zst() {
686            return OperandRef::zero_sized(place.layout);
687        }
688
689        #[instrument(level = "trace", skip(bx))]
690        fn scalar_load_metadata<'a, 'll, 'tcx>(
691            bx: &mut Builder<'a, 'll, 'tcx>,
692            load: &'ll Value,
693            scalar: abi::Scalar,
694            layout: TyAndLayout<'tcx>,
695            offset: Size,
696        ) {
697            if bx.cx.sess().opts.optimize == OptLevel::No {
698                // Don't emit metadata we're not going to use
699                return;
700            }
701
702            if !scalar.is_uninit_valid() {
703                bx.noundef_metadata(load);
704            }
705
706            match scalar.primitive() {
707                abi::Primitive::Int(..) => {
708                    if !scalar.is_always_valid(bx) {
709                        bx.range_metadata(load, scalar.valid_range(bx));
710                    }
711                }
712                abi::Primitive::Pointer(_) => {
713                    if !scalar.valid_range(bx).contains(0) {
714                        bx.nonnull_metadata(load);
715                    }
716
717                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
718                        && pointee.align > Align::ONE
719                    {
720                        bx.align_metadata(load, pointee.align);
721                    }
722                }
723                abi::Primitive::Float(_) => {}
724            }
725        }
726
727        let val = if let Some(_) = place.val.llextra {
728            // FIXME: Merge with the `else` below?
729            OperandValue::Ref(place.val)
730        } else if place.layout.is_llvm_immediate() {
731            let mut const_llval = None;
732            let llty = place.layout.llvm_type(self);
733            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
734                if llvm::LLVMIsGlobalConstant(global).is_true() {
735                    if let Some(init) = llvm::LLVMGetInitializer(global) {
736                        if self.val_ty(init) == llty {
737                            const_llval = Some(init);
738                        }
739                    }
740                }
741            }
742
743            let llval = const_llval.unwrap_or_else(|| {
744                let load = self.load(llty, place.val.llval, place.val.align);
745                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
746                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
747                    self.to_immediate_scalar(load, scalar)
748                } else {
749                    load
750                }
751            });
752            OperandValue::Immediate(llval)
753        } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
754            let b_offset = a.size(self).align_to(b.align(self).abi);
755
756            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
757                let llptr = if i == 0 {
758                    place.val.llval
759                } else {
760                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
761                };
762                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
763                let load = self.load(llty, llptr, align);
764                scalar_load_metadata(self, load, scalar, layout, offset);
765                self.to_immediate_scalar(load, scalar)
766            };
767
768            OperandValue::Pair(
769                load(0, a, place.layout, place.val.align, Size::ZERO),
770                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
771            )
772        } else {
773            OperandValue::Ref(place.val)
774        };
775
776        OperandRef { val, layout: place.layout, move_annotation: None }
777    }
778
779    fn write_operand_repeatedly(
780        &mut self,
781        cg_elem: OperandRef<'tcx, &'ll Value>,
782        count: u64,
783        dest: PlaceRef<'tcx, &'ll Value>,
784    ) {
785        if self.cx.sess().opts.optimize == OptLevel::No {
786            // To let debuggers single-step over lines like
787            //
788            //     let foo = ["bar"; 42];
789            //
790            // we need the debugger-friendly LLVM IR that `_unoptimized()`
791            // provides. The `_optimized()` version generates trickier LLVM IR.
792            // See PR #148058 for a failed attempt at handling that.
793            self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
794        } else {
795            self.write_operand_repeatedly_optimized(cg_elem, count, dest);
796        }
797    }
798
799    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
800        if self.cx.sess().opts.optimize == OptLevel::No {
801            // Don't emit metadata we're not going to use
802            return;
803        }
804
805        let llty = self.cx.val_ty(load);
806        let md = [
807            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
808            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
809        ];
810        self.set_metadata_node(load, llvm::MD_range, &md);
811    }
812
813    fn nonnull_metadata(&mut self, load: &'ll Value) {
814        self.set_metadata_node(load, llvm::MD_nonnull, &[]);
815    }
816
817    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
818        self.store_with_flags(val, ptr, align, MemFlags::empty())
819    }
820
821    fn store_with_flags(
822        &mut self,
823        val: &'ll Value,
824        ptr: &'ll Value,
825        align: Align,
826        flags: MemFlags,
827    ) -> &'ll Value {
828        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:828",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(828u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?} ({2:?})",
                                                    val, ptr, flags) as &dyn Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
829        match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
830        unsafe {
831            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
832            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
833            let align =
834                if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
835            llvm::LLVMSetAlignment(store, align);
836            if flags.contains(MemFlags::VOLATILE) {
837                llvm::LLVMSetVolatile(store, llvm::TRUE);
838            }
839            if flags.contains(MemFlags::NONTEMPORAL) {
840                // Make sure that the current target architectures supports "sane" non-temporal
841                // stores, i.e., non-temporal stores that are equivalent to regular stores except
842                // for performance. LLVM doesn't seem to care about this, and will happily treat
843                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
844                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
845                // regular stores but require special fences. So we keep a list of architectures
846                // where `!nontemporal` is known to be truly just a hint, and use regular stores
847                // everywhere else. (In the future, we could alternatively ensure that an sfence
848                // gets emitted after a sequence of movnt before any kind of synchronizing
849                // operation. But it's not clear how to do that with LLVM.)
850                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
851                // <https://github.com/llvm/llvm-project/issues/64521>.
852                let use_nontemporal = #[allow(non_exhaustive_omitted_patterns)] match self.cx.tcx.sess.target.arch {
    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64 => true,
    _ => false,
}matches!(
853                    self.cx.tcx.sess.target.arch,
854                    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
855                );
856                if use_nontemporal {
857                    // According to LLVM [1] building a nontemporal store must
858                    // *always* point to a metadata value of the integer 1.
859                    //
860                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
861                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
862                    self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
863                }
864            }
865            store
866        }
867    }
868
869    fn atomic_store(
870        &mut self,
871        val: &'ll Value,
872        ptr: &'ll Value,
873        order: rustc_middle::ty::AtomicOrdering,
874        size: Size,
875    ) {
876        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:876",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(876u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
877        match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
878        unsafe {
879            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
880            // Set atomic ordering
881            llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
882            // LLVM requires the alignment of atomic stores to be at least the size of the type.
883            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
884        }
885    }
886
887    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
888        unsafe {
889            llvm::LLVMBuildGEPWithNoWrapFlags(
890                self.llbuilder,
891                ty,
892                ptr,
893                indices.as_ptr(),
894                indices.len() as c_uint,
895                UNNAMED,
896                GEPNoWrapFlags::default(),
897            )
898        }
899    }
900
901    fn inbounds_gep(
902        &mut self,
903        ty: &'ll Type,
904        ptr: &'ll Value,
905        indices: &[&'ll Value],
906    ) -> &'ll Value {
907        unsafe {
908            llvm::LLVMBuildGEPWithNoWrapFlags(
909                self.llbuilder,
910                ty,
911                ptr,
912                indices.as_ptr(),
913                indices.len() as c_uint,
914                UNNAMED,
915                GEPNoWrapFlags::InBounds,
916            )
917        }
918    }
919
920    fn inbounds_nuw_gep(
921        &mut self,
922        ty: &'ll Type,
923        ptr: &'ll Value,
924        indices: &[&'ll Value],
925    ) -> &'ll Value {
926        unsafe {
927            llvm::LLVMBuildGEPWithNoWrapFlags(
928                self.llbuilder,
929                ty,
930                ptr,
931                indices.as_ptr(),
932                indices.len() as c_uint,
933                UNNAMED,
934                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
935            )
936        }
937    }
938
939    /* Casts */
940    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
941        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
942    }
943
944    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
945        if true {
    match (&self.val_ty(val), &dest_ty) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_ne!(self.val_ty(val), dest_ty);
946
947        let trunc = self.trunc(val, dest_ty);
948        unsafe {
949            if llvm::LLVMIsAInstruction(trunc).is_some() {
950                llvm::LLVMSetNUW(trunc, TRUE);
951            }
952        }
953        trunc
954    }
955
956    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
957        if true {
    match (&self.val_ty(val), &dest_ty) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_ne!(self.val_ty(val), dest_ty);
958
959        let trunc = self.trunc(val, dest_ty);
960        unsafe {
961            if llvm::LLVMIsAInstruction(trunc).is_some() {
962                llvm::LLVMSetNSW(trunc, TRUE);
963            }
964        }
965        trunc
966    }
967
968    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
969        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
970    }
971
972    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
973        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
974    }
975
976    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
977        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
978    }
979
980    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
981        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
982        // poor codegen. The reason for this is that the corresponding wasm
983        // instructions, `i32.trunc_f32_s` for example, will trap when the float
984        // is out-of-bounds, infinity, or nan. This means that LLVM
985        // automatically inserts control flow around `fptoui` and `fptosi`
986        // because the LLVM instruction `fptoui` is defined as producing a
987        // poison value, not having UB on out-of-bounds values.
988        //
989        // This method, however, is only used with non-saturating casts that
990        // have UB on out-of-bounds values. This means that it's ok if we use
991        // the raw wasm instruction since out-of-bounds values can do whatever
992        // we like. To ensure that LLVM picks the right instruction we choose
993        // the raw wasm intrinsic functions which avoid LLVM inserting all the
994        // other control flow automatically.
995        if self.sess().target.is_like_wasm {
996            let src_ty = self.cx.val_ty(val);
997            if self.cx.type_kind(src_ty) != TypeKind::Vector {
998                let float_width = self.cx.float_width(src_ty);
999                let int_width = self.cx.int_width(dest_ty);
1000                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
    (32 | 64, 32 | 64) => true,
    _ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1001                    return self.call_intrinsic(
1002                        "llvm.wasm.trunc.unsigned",
1003                        &[dest_ty, src_ty],
1004                        &[val],
1005                    );
1006                }
1007            }
1008        }
1009        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1010    }
1011
1012    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1013        // see `fptoui` above for why wasm is different here
1014        if self.sess().target.is_like_wasm {
1015            let src_ty = self.cx.val_ty(val);
1016            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1017                let float_width = self.cx.float_width(src_ty);
1018                let int_width = self.cx.int_width(dest_ty);
1019                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
    (32 | 64, 32 | 64) => true,
    _ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1020                    return self.call_intrinsic(
1021                        "llvm.wasm.trunc.signed",
1022                        &[dest_ty, src_ty],
1023                        &[val],
1024                    );
1025                }
1026            }
1027        }
1028        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1029    }
1030
1031    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1032        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1033    }
1034
1035    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1036        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1037    }
1038
1039    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1040        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1041    }
1042
1043    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1044        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1045    }
1046
1047    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1048        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1049    }
1050
1051    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1052        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1053    }
1054
1055    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1056        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1057    }
1058
1059    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1060        unsafe {
1061            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1062        }
1063    }
1064
1065    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1066        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1067    }
1068
1069    /* Comparisons */
1070    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1071        let op = llvm::IntPredicate::from_generic(op);
1072        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1073    }
1074
1075    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1076        let op = llvm::RealPredicate::from_generic(op);
1077        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1078    }
1079
1080    fn three_way_compare(
1081        &mut self,
1082        ty: Ty<'tcx>,
1083        lhs: Self::Value,
1084        rhs: Self::Value,
1085    ) -> Self::Value {
1086        let size = ty.primitive_size(self.tcx);
1087        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1088
1089        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1090    }
1091
1092    /* Miscellaneous instructions */
1093    fn memcpy(
1094        &mut self,
1095        dst: &'ll Value,
1096        dst_align: Align,
1097        src: &'ll Value,
1098        src_align: Align,
1099        size: &'ll Value,
1100        flags: MemFlags,
1101        tt: Option<FncTree>,
1102    ) {
1103        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memcpy not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1104        let size = self.intcast(size, self.type_isize(), false);
1105        let is_volatile = flags.contains(MemFlags::VOLATILE);
1106        let memcpy = unsafe {
1107            llvm::LLVMRustBuildMemCpy(
1108                self.llbuilder,
1109                dst,
1110                dst_align.bytes() as c_uint,
1111                src,
1112                src_align.bytes() as c_uint,
1113                size,
1114                is_volatile,
1115            )
1116        };
1117
1118        // TypeTree metadata for memcpy is especially important: when Enzyme encounters
1119        // a memcpy during autodiff, it needs to know the structure of the data being
1120        // copied to properly track derivatives. For example, copying an array of floats
1121        // vs. copying a struct with mixed types requires different derivative handling.
1122        // The TypeTree tells Enzyme exactly what memory layout to expect.
1123        if let Some(tt) = tt {
1124            crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, memcpy, tt);
1125        }
1126    }
1127
1128    fn memmove(
1129        &mut self,
1130        dst: &'ll Value,
1131        dst_align: Align,
1132        src: &'ll Value,
1133        src_align: Align,
1134        size: &'ll Value,
1135        flags: MemFlags,
1136    ) {
1137        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memmove not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1138        let size = self.intcast(size, self.type_isize(), false);
1139        let is_volatile = flags.contains(MemFlags::VOLATILE);
1140        unsafe {
1141            llvm::LLVMRustBuildMemMove(
1142                self.llbuilder,
1143                dst,
1144                dst_align.bytes() as c_uint,
1145                src,
1146                src_align.bytes() as c_uint,
1147                size,
1148                is_volatile,
1149            );
1150        }
1151    }
1152
1153    fn memset(
1154        &mut self,
1155        ptr: &'ll Value,
1156        fill_byte: &'ll Value,
1157        size: &'ll Value,
1158        align: Align,
1159        flags: MemFlags,
1160    ) {
1161        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memset not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1162        let is_volatile = flags.contains(MemFlags::VOLATILE);
1163        unsafe {
1164            llvm::LLVMRustBuildMemSet(
1165                self.llbuilder,
1166                ptr,
1167                align.bytes() as c_uint,
1168                fill_byte,
1169                size,
1170                is_volatile,
1171            );
1172        }
1173    }
1174
1175    fn select(
1176        &mut self,
1177        cond: &'ll Value,
1178        then_val: &'ll Value,
1179        else_val: &'ll Value,
1180    ) -> &'ll Value {
1181        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1182    }
1183
1184    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1185        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1186    }
1187
1188    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1189        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1190    }
1191
1192    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1193        unsafe {
1194            let elt_ty = self.cx.val_ty(elt);
1195            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1196            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1197            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1198            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1199        }
1200    }
1201
1202    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1203        match (&(idx as c_uint as u64), &idx) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(idx as c_uint as u64, idx);
1204        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1205    }
1206
1207    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1208        match (&(idx as c_uint as u64), &idx) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(idx as c_uint as u64, idx);
1209        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1210    }
1211
1212    fn set_personality_fn(&mut self, personality: &'ll Value) {
1213        unsafe {
1214            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1215        }
1216    }
1217
1218    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1219        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1220        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1221        unsafe {
1222            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1223        }
1224        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1225    }
1226
1227    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1228        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1229        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1230        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1231    }
1232
1233    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1234        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1235        let mut exn = self.const_poison(ty);
1236        exn = self.insert_value(exn, exn0, 0);
1237        exn = self.insert_value(exn, exn1, 1);
1238        unsafe {
1239            llvm::LLVMBuildResume(self.llbuilder, exn);
1240        }
1241    }
1242
1243    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1244        let ret = unsafe {
1245            llvm::LLVMBuildCleanupPad(
1246                self.llbuilder,
1247                parent,
1248                args.as_ptr(),
1249                args.len() as c_uint,
1250                c"cleanuppad".as_ptr(),
1251            )
1252        };
1253        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1254    }
1255
1256    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1257        unsafe {
1258            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1259                .expect("LLVM does not have support for cleanupret");
1260        }
1261    }
1262
1263    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1264        let ret = unsafe {
1265            llvm::LLVMBuildCatchPad(
1266                self.llbuilder,
1267                parent,
1268                args.as_ptr(),
1269                args.len() as c_uint,
1270                c"catchpad".as_ptr(),
1271            )
1272        };
1273        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1274    }
1275
1276    fn catch_switch(
1277        &mut self,
1278        parent: Option<&'ll Value>,
1279        unwind: Option<&'ll BasicBlock>,
1280        handlers: &[&'ll BasicBlock],
1281    ) -> &'ll Value {
1282        let ret = unsafe {
1283            llvm::LLVMBuildCatchSwitch(
1284                self.llbuilder,
1285                parent,
1286                unwind,
1287                handlers.len() as c_uint,
1288                c"catchswitch".as_ptr(),
1289            )
1290        };
1291        let ret = ret.expect("LLVM does not have support for catchswitch");
1292        for handler in handlers {
1293            unsafe {
1294                llvm::LLVMAddHandler(ret, handler);
1295            }
1296        }
1297        ret
1298    }
1299
1300    fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1301        funclet.cleanuppad()
1302    }
1303
1304    // Atomic Operations
1305    fn atomic_cmpxchg(
1306        &mut self,
1307        dst: &'ll Value,
1308        cmp: &'ll Value,
1309        src: &'ll Value,
1310        order: rustc_middle::ty::AtomicOrdering,
1311        failure_order: rustc_middle::ty::AtomicOrdering,
1312        weak: bool,
1313    ) -> (&'ll Value, &'ll Value) {
1314        unsafe {
1315            let value = llvm::LLVMBuildAtomicCmpXchg(
1316                self.llbuilder,
1317                dst,
1318                cmp,
1319                src,
1320                AtomicOrdering::from_generic(order),
1321                AtomicOrdering::from_generic(failure_order),
1322                llvm::FALSE, // SingleThreaded
1323            );
1324            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1325            let val = self.extract_value(value, 0);
1326            let success = self.extract_value(value, 1);
1327            (val, success)
1328        }
1329    }
1330
1331    fn atomic_rmw(
1332        &mut self,
1333        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1334        dst: &'ll Value,
1335        src: &'ll Value,
1336        order: rustc_middle::ty::AtomicOrdering,
1337        ret_ptr: bool,
1338    ) -> &'ll Value {
1339        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1340        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1341        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1342        let mut res = unsafe {
1343            llvm::LLVMBuildAtomicRMW(
1344                self.llbuilder,
1345                AtomicRmwBinOp::from_generic(op),
1346                dst,
1347                src,
1348                AtomicOrdering::from_generic(order),
1349                llvm::FALSE, // SingleThreaded
1350            )
1351        };
1352        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1353            res = self.inttoptr(res, self.type_ptr());
1354        }
1355        res
1356    }
1357
1358    fn atomic_fence(
1359        &mut self,
1360        order: rustc_middle::ty::AtomicOrdering,
1361        scope: SynchronizationScope,
1362    ) {
1363        let single_threaded = match scope {
1364            SynchronizationScope::SingleThread => true,
1365            SynchronizationScope::CrossThread => false,
1366        };
1367        unsafe {
1368            llvm::LLVMBuildFence(
1369                self.llbuilder,
1370                AtomicOrdering::from_generic(order),
1371                single_threaded.to_llvm_bool(),
1372                UNNAMED,
1373            );
1374        }
1375    }
1376
1377    fn set_invariant_load(&mut self, load: &'ll Value) {
1378        self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1379    }
1380
1381    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1382        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1383    }
1384
1385    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1386        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1387    }
1388
1389    fn call(
1390        &mut self,
1391        llty: &'ll Type,
1392        caller_attrs: Option<&CodegenFnAttrs>,
1393        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1394        llfn: &'ll Value,
1395        args: &[&'ll Value],
1396        funclet: Option<&Funclet<'ll>>,
1397        callee_instance: Option<Instance<'tcx>>,
1398    ) -> &'ll Value {
1399        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1399",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1399u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1400
1401        let args = self.check_call("call", llty, llfn, args);
1402        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1403        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1404        if let Some(funclet_bundle) = funclet_bundle {
1405            bundles.push(funclet_bundle);
1406        }
1407
1408        // Emit CFI pointer type membership test
1409        self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1410
1411        // Emit KCFI operand bundle
1412        let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1413        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1414            bundles.push(kcfi_bundle);
1415        }
1416
1417        let call = unsafe {
1418            llvm::LLVMBuildCallWithOperandBundles(
1419                self.llbuilder,
1420                llty,
1421                llfn,
1422                args.as_ptr() as *const &llvm::Value,
1423                args.len() as c_uint,
1424                bundles.as_ptr(),
1425                bundles.len() as c_uint,
1426                c"".as_ptr(),
1427            )
1428        };
1429
1430        if let Some(callee_instance) = callee_instance {
1431            // Attributes on the function definition being called
1432            let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1433            if let Some(caller_attrs) = caller_attrs
1434                // If there is an inline attribute and a target feature that matches
1435                // we will add the attribute to the callsite otherwise we'll omit
1436                // this and not add the attribute to prevent soundness issues.
1437                && let Some(inlining_rule) = attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance)
1438                && self.cx.tcx.is_target_feature_call_safe(
1439                    &callee_attrs.target_features,
1440                    &caller_attrs.target_features.iter().cloned().chain(
1441                        self.cx.tcx.sess.target_features.iter().map(|feat| TargetFeature {
1442                            name: *feat,
1443                            kind: TargetFeatureKind::Implied,
1444                        })
1445                    ).collect::<Vec<_>>(),
1446                )
1447            {
1448                attributes::apply_to_callsite(
1449                    call,
1450                    llvm::AttributePlace::Function,
1451                    &[inlining_rule],
1452                );
1453            }
1454        }
1455
1456        if let Some(fn_abi) = fn_abi {
1457            fn_abi.apply_attrs_callsite(self, call);
1458        }
1459        call
1460    }
1461
1462    fn tail_call(
1463        &mut self,
1464        llty: Self::Type,
1465        caller_attrs: Option<&CodegenFnAttrs>,
1466        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1467        llfn: Self::Value,
1468        args: &[Self::Value],
1469        funclet: Option<&Self::Funclet>,
1470        callee_instance: Option<Instance<'tcx>>,
1471    ) {
1472        let call =
1473            self.call(llty, caller_attrs, Some(fn_abi), llfn, args, funclet, callee_instance);
1474        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1475
1476        match &fn_abi.ret.mode {
1477            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1478            PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1479        }
1480    }
1481
1482    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1483        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1484    }
1485
1486    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1487        // Cleanup is always the cold path.
1488        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1489        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1490    }
1491}
1492
1493impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1494    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1495        // Forward to the `get_static` method of `CodegenCx`
1496        let global = self.cx().get_static(def_id);
1497        if self.cx().tcx.is_thread_local_static(def_id) {
1498            let pointer =
1499                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1500            // Cast to default address space if globals are in a different addrspace
1501            self.pointercast(pointer, self.type_ptr())
1502        } else {
1503            // Cast to default address space if globals are in a different addrspace
1504            self.cx().const_pointercast(global, self.type_ptr())
1505        }
1506    }
1507}
1508
1509impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1510    pub(crate) fn llfn(&self) -> &'ll Value {
1511        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1512    }
1513}
1514
1515impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1516    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1517        unsafe {
1518            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1519        }
1520    }
1521}
1522impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1523    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1524        let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1525        self.set_metadata_node(load, llvm::MD_align, &md);
1526    }
1527
1528    fn noundef_metadata(&mut self, load: &'ll Value) {
1529        self.set_metadata_node(load, llvm::MD_noundef, &[]);
1530    }
1531
1532    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1533        self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1534    }
1535
1536    fn write_operand_repeatedly_optimized(
1537        &mut self,
1538        cg_elem: OperandRef<'tcx, &'ll Value>,
1539        count: u64,
1540        dest: PlaceRef<'tcx, &'ll Value>,
1541    ) {
1542        let zero = self.const_usize(0);
1543        let count = self.const_usize(count);
1544
1545        let header_bb = self.append_sibling_block("repeat_loop_header");
1546        let body_bb = self.append_sibling_block("repeat_loop_body");
1547        let next_bb = self.append_sibling_block("repeat_loop_next");
1548
1549        self.br(header_bb);
1550
1551        let mut header_bx = Self::build(self.cx, header_bb);
1552        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1553
1554        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1555        header_bx.cond_br(keep_going, body_bb, next_bb);
1556
1557        let mut body_bx = Self::build(self.cx, body_bb);
1558        let dest_elem = dest.project_index(&mut body_bx, i);
1559        cg_elem.val.store(&mut body_bx, dest_elem);
1560
1561        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1562        body_bx.br(header_bb);
1563        header_bx.add_incoming_to_phi(i, next, body_bb);
1564
1565        *self = Self::build(self.cx, next_bb);
1566    }
1567
1568    fn write_operand_repeatedly_unoptimized(
1569        &mut self,
1570        cg_elem: OperandRef<'tcx, &'ll Value>,
1571        count: u64,
1572        dest: PlaceRef<'tcx, &'ll Value>,
1573    ) {
1574        let zero = self.const_usize(0);
1575        let count = self.const_usize(count);
1576        let start = dest.project_index(self, zero).val.llval;
1577        let end = dest.project_index(self, count).val.llval;
1578
1579        let header_bb = self.append_sibling_block("repeat_loop_header");
1580        let body_bb = self.append_sibling_block("repeat_loop_body");
1581        let next_bb = self.append_sibling_block("repeat_loop_next");
1582
1583        self.br(header_bb);
1584
1585        let mut header_bx = Self::build(self.cx, header_bb);
1586        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1587
1588        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1589        header_bx.cond_br(keep_going, body_bb, next_bb);
1590
1591        let mut body_bx = Self::build(self.cx, body_bb);
1592        let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1593        cg_elem
1594            .val
1595            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1596
1597        let next = body_bx.inbounds_gep(
1598            self.backend_type(cg_elem.layout),
1599            current,
1600            &[self.const_usize(1)],
1601        );
1602        body_bx.br(header_bb);
1603        header_bx.add_incoming_to_phi(current, next, body_bb);
1604
1605        *self = Self::build(self.cx, next_bb);
1606    }
1607
1608    pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1609        self.call_intrinsic("llvm.minnum", &[self.val_ty(lhs)], &[lhs, rhs])
1610    }
1611
1612    pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1613        self.call_intrinsic("llvm.maxnum", &[self.val_ty(lhs)], &[lhs, rhs])
1614    }
1615
1616    pub(crate) fn insert_element(
1617        &mut self,
1618        vec: &'ll Value,
1619        elt: &'ll Value,
1620        idx: &'ll Value,
1621    ) -> &'ll Value {
1622        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1623    }
1624
1625    pub(crate) fn shuffle_vector(
1626        &mut self,
1627        v1: &'ll Value,
1628        v2: &'ll Value,
1629        mask: &'ll Value,
1630    ) -> &'ll Value {
1631        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1632    }
1633
1634    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1635        self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1636    }
1637    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1638        self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1639    }
1640    pub(crate) fn vector_reduce_fadd_reassoc(
1641        &mut self,
1642        acc: &'ll Value,
1643        src: &'ll Value,
1644    ) -> &'ll Value {
1645        unsafe {
1646            let instr =
1647                self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1648            llvm::LLVMRustSetAllowReassoc(instr);
1649            instr
1650        }
1651    }
1652    pub(crate) fn vector_reduce_fmul_reassoc(
1653        &mut self,
1654        acc: &'ll Value,
1655        src: &'ll Value,
1656    ) -> &'ll Value {
1657        unsafe {
1658            let instr =
1659                self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1660            llvm::LLVMRustSetAllowReassoc(instr);
1661            instr
1662        }
1663    }
1664    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1665        self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1666    }
1667    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1668        self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1669    }
1670    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1671        self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1672    }
1673    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1674        self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1675    }
1676    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1677        self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1678    }
1679    pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1680        self.call_intrinsic("llvm.vector.reduce.fmin", &[self.val_ty(src)], &[src])
1681    }
1682    pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1683        self.call_intrinsic("llvm.vector.reduce.fmax", &[self.val_ty(src)], &[src])
1684    }
1685    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1686        self.call_intrinsic(
1687            if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1688            &[self.val_ty(src)],
1689            &[src],
1690        )
1691    }
1692    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1693        self.call_intrinsic(
1694            if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1695            &[self.val_ty(src)],
1696            &[src],
1697        )
1698    }
1699}
1700impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1701    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1702        unsafe {
1703            llvm::LLVMAddClause(landing_pad, clause);
1704        }
1705    }
1706
1707    pub(crate) fn catch_ret(
1708        &mut self,
1709        funclet: &Funclet<'ll>,
1710        unwind: &'ll BasicBlock,
1711    ) -> &'ll Value {
1712        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1713        ret.expect("LLVM does not have support for catchret")
1714    }
1715
1716    pub(crate) fn check_call<'b>(
1717        &mut self,
1718        typ: &str,
1719        fn_ty: &'ll Type,
1720        llfn: &'ll Value,
1721        args: &'b [&'ll Value],
1722    ) -> Cow<'b, [&'ll Value]> {
1723        if !(self.cx.type_kind(fn_ty) == TypeKind::Function) {
    {
        ::core::panicking::panic_fmt(format_args!("builder::{0} not passed a function, but {1:?}",
                typ, fn_ty));
    }
};assert!(
1724            self.cx.type_kind(fn_ty) == TypeKind::Function,
1725            "builder::{typ} not passed a function, but {fn_ty:?}"
1726        );
1727
1728        let param_tys = self.cx.func_params_types(fn_ty);
1729
1730        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1731            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1732
1733        if all_args_match {
1734            return Cow::Borrowed(args);
1735        }
1736
1737        let casted_args: Vec<_> = iter::zip(param_tys, args)
1738            .enumerate()
1739            .map(|(i, (expected_ty, &actual_val))| {
1740                let actual_ty = self.cx.val_ty(actual_val);
1741                if expected_ty != actual_ty {
1742                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1742",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1742u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("type mismatch in function call of {0:?}. Expected {1:?} for param {2}, got {3:?}; injecting bitcast",
                                                    llfn, expected_ty, i, actual_ty) as &dyn Value))])
            });
    } else { ; }
};debug!(
1743                        "type mismatch in function call of {:?}. \
1744                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1745                        llfn, expected_ty, i, actual_ty
1746                    );
1747                    self.bitcast(actual_val, expected_ty)
1748                } else {
1749                    actual_val
1750                }
1751            })
1752            .collect();
1753
1754        Cow::Owned(casted_args)
1755    }
1756
1757    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1758        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1759    }
1760}
1761
1762impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1763    pub(crate) fn call_intrinsic(
1764        &mut self,
1765        base_name: impl Into<Cow<'static, str>>,
1766        type_params: &[&'ll Type],
1767        args: &[&'ll Value],
1768    ) -> &'ll Value {
1769        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1770        self.call(ty, None, None, f, args, None, None)
1771    }
1772
1773    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1774        let size = size.bytes();
1775        if size == 0 {
1776            return;
1777        }
1778
1779        if !self.cx().sess().emit_lifetime_markers() {
1780            return;
1781        }
1782
1783        if crate::llvm_util::get_version() >= (22, 0, 0) {
1784            // LLVM 22 requires the lifetime intrinsic to act directly on the alloca,
1785            // there can't be an addrspacecast in between.
1786            let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1787            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1788        } else {
1789            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1790        }
1791    }
1792}
1793impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1794    pub(crate) fn phi(
1795        &mut self,
1796        ty: &'ll Type,
1797        vals: &[&'ll Value],
1798        bbs: &[&'ll BasicBlock],
1799    ) -> &'ll Value {
1800        match (&vals.len(), &bbs.len()) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(vals.len(), bbs.len());
1801        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1802        unsafe {
1803            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1804            phi
1805        }
1806    }
1807
1808    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1809        unsafe {
1810            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1811        }
1812    }
1813}
1814impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1815    pub(crate) fn landing_pad(
1816        &mut self,
1817        ty: &'ll Type,
1818        pers_fn: &'ll Value,
1819        num_clauses: usize,
1820    ) -> &'ll Value {
1821        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1822        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1823        // personality lives on the parent function anyway.
1824        self.set_personality_fn(pers_fn);
1825        unsafe {
1826            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1827        }
1828    }
1829
1830    pub(crate) fn callbr(
1831        &mut self,
1832        llty: &'ll Type,
1833        fn_attrs: Option<&CodegenFnAttrs>,
1834        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1835        llfn: &'ll Value,
1836        args: &[&'ll Value],
1837        default_dest: &'ll BasicBlock,
1838        indirect_dest: &[&'ll BasicBlock],
1839        funclet: Option<&Funclet<'ll>>,
1840        instance: Option<Instance<'tcx>>,
1841    ) -> &'ll Value {
1842        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1842",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1842u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1843
1844        let args = self.check_call("callbr", llty, llfn, args);
1845        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1846        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1847        if let Some(funclet_bundle) = funclet_bundle {
1848            bundles.push(funclet_bundle);
1849        }
1850
1851        // Emit CFI pointer type membership test
1852        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1853
1854        // Emit KCFI operand bundle
1855        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1856        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1857            bundles.push(kcfi_bundle);
1858        }
1859
1860        let callbr = unsafe {
1861            llvm::LLVMBuildCallBr(
1862                self.llbuilder,
1863                llty,
1864                llfn,
1865                default_dest,
1866                indirect_dest.as_ptr(),
1867                indirect_dest.len() as c_uint,
1868                args.as_ptr(),
1869                args.len() as c_uint,
1870                bundles.as_ptr(),
1871                bundles.len() as c_uint,
1872                UNNAMED,
1873            )
1874        };
1875        if let Some(fn_abi) = fn_abi {
1876            fn_abi.apply_attrs_callsite(self, callbr);
1877        }
1878        callbr
1879    }
1880
1881    // Emits CFI pointer type membership tests.
1882    fn cfi_type_test(
1883        &mut self,
1884        fn_attrs: Option<&CodegenFnAttrs>,
1885        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1886        instance: Option<Instance<'tcx>>,
1887        llfn: &'ll Value,
1888    ) {
1889        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1890        if self.tcx.sess.is_sanitizer_cfi_enabled()
1891            && let Some(fn_abi) = fn_abi
1892            && is_indirect_call
1893        {
1894            if let Some(fn_attrs) = fn_attrs
1895                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
1896            {
1897                return;
1898            }
1899
1900            let mut options = cfi::TypeIdOptions::empty();
1901            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1902                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1903            }
1904            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1905                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1906            }
1907
1908            let typeid = if let Some(instance) = instance {
1909                cfi::typeid_for_instance(self.tcx, instance, options)
1910            } else {
1911                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1912            };
1913            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1914            let dbg_loc = self.get_dbg_loc();
1915
1916            // Test whether the function pointer is associated with the type identifier using the
1917            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
1918            // calls to this intrinsic with code to test type membership.
1919            let typeid = self.get_metadata_value(typeid_metadata);
1920            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1921            let bb_pass = self.append_sibling_block("type_test.pass");
1922            let bb_fail = self.append_sibling_block("type_test.fail");
1923            self.cond_br(cond, bb_pass, bb_fail);
1924
1925            self.switch_to_block(bb_fail);
1926            if let Some(dbg_loc) = dbg_loc {
1927                self.set_dbg_loc(dbg_loc);
1928            }
1929            self.abort();
1930            self.unreachable();
1931
1932            self.switch_to_block(bb_pass);
1933            if let Some(dbg_loc) = dbg_loc {
1934                self.set_dbg_loc(dbg_loc);
1935            }
1936        }
1937    }
1938
1939    // Emits KCFI operand bundles.
1940    fn kcfi_operand_bundle(
1941        &mut self,
1942        fn_attrs: Option<&CodegenFnAttrs>,
1943        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1944        instance: Option<Instance<'tcx>>,
1945        llfn: &'ll Value,
1946    ) -> Option<llvm::OperandBundleBox<'ll>> {
1947        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1948        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1949            && let Some(fn_abi) = fn_abi
1950            && is_indirect_call
1951        {
1952            if let Some(fn_attrs) = fn_attrs
1953                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
1954            {
1955                return None;
1956            }
1957
1958            let mut options = kcfi::TypeIdOptions::empty();
1959            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1960                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
1961            }
1962            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1963                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
1964            }
1965
1966            let kcfi_typeid = if let Some(instance) = instance {
1967                kcfi::typeid_for_instance(self.tcx, instance, options)
1968            } else {
1969                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1970            };
1971
1972            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
1973        } else {
1974            None
1975        };
1976        kcfi_bundle
1977    }
1978
1979    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
1980    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instrprof_increment",
                                    "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1980u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&["fn_name", "hash",
                                                    "num_counters", "index"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.call_intrinsic("llvm.instrprof.increment", &[],
                &[fn_name, hash, num_counters, index]);
        }
    }
}#[instrument(level = "debug", skip(self))]
1981    pub(crate) fn instrprof_increment(
1982        &mut self,
1983        fn_name: &'ll Value,
1984        hash: &'ll Value,
1985        num_counters: &'ll Value,
1986        index: &'ll Value,
1987    ) {
1988        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
1989    }
1990}