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::{self as abi, Align, CanonAbi, Size, WrappingRange};
11use rustc_attr_ir::{AttributeKind, UnrollAttr};
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;
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    pub span: rustc_span::Span,
48}
49
50pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
51pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
52
53impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
54    fn drop(&mut self) {
55        unsafe {
56            llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
57        }
58    }
59}
60
61impl<'a, 'll> SBuilder<'a, 'll> {
62    pub(crate) fn call(
63        &mut self,
64        llty: &'ll Type,
65        llfn: &'ll Value,
66        args: &[&'ll Value],
67        funclet: Option<&Funclet<'ll>>,
68    ) -> &'ll Value {
69        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:69",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(69u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
70
71        let args = self.check_call("call", llty, llfn, args);
72        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
73        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
74        if let Some(funclet_bundle) = funclet_bundle {
75            bundles.push(funclet_bundle);
76        }
77
78        let call = unsafe {
79            llvm::LLVMBuildCallWithOperandBundles(
80                self.llbuilder,
81                llty,
82                llfn,
83                args.as_ptr() as *const &llvm::Value,
84                args.len() as c_uint,
85                bundles.as_ptr(),
86                bundles.len() as c_uint,
87                c"".as_ptr(),
88            )
89        };
90        call
91    }
92}
93
94impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
95    fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
96        // Create a fresh builder from the simple context.
97        let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
98        GenericBuilder { llbuilder, cx: scx, span: rustc_span::DUMMY_SP }
99    }
100
101    pub(crate) fn append_block(
102        cx: &'a GenericCx<'ll, CX>,
103        llfn: &'ll Value,
104        name: &str,
105    ) -> &'ll BasicBlock {
106        unsafe {
107            let name = SmallCStr::new(name);
108            llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
109        }
110    }
111
112    pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
113        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
114    }
115
116    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
117        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
118    }
119
120    pub(crate) fn ret_void(&mut self) {
121        llvm::LLVMBuildRetVoid(self.llbuilder);
122    }
123
124    pub(crate) fn ret(&mut self, v: &'ll Value) {
125        unsafe {
126            llvm::LLVMBuildRet(self.llbuilder, v);
127        }
128    }
129
130    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
131        let bx = Self::with_cx(cx);
132        unsafe {
133            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
134        }
135        bx
136    }
137
138    // The generic builder has less functionality and thus (unlike the other alloca) we can not
139    // easily jump to the beginning of the function to place our allocas there. We trust the user
140    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
141    // handle this.
142    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
143        let val = unsafe {
144            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
145            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
146            // Cast to default addrspace if necessary
147            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
148        };
149        if name != "" {
150            let name = std::ffi::CString::new(name).unwrap();
151            llvm::set_value_name(val, &name.as_bytes());
152        }
153        val
154    }
155
156    pub(crate) fn inbounds_gep(
157        &mut self,
158        ty: &'ll Type,
159        ptr: &'ll Value,
160        indices: &[&'ll Value],
161    ) -> &'ll Value {
162        unsafe {
163            llvm::LLVMBuildGEPWithNoWrapFlags(
164                self.llbuilder,
165                ty,
166                ptr,
167                indices.as_ptr(),
168                indices.len() as c_uint,
169                UNNAMED,
170                GEPNoWrapFlags::InBounds,
171            )
172        }
173    }
174
175    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
176        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:176",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(176u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
177        {
    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);
178        unsafe {
179            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
180            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
181            store
182        }
183    }
184
185    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
186        unsafe {
187            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
188            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
189            load
190        }
191    }
192}
193
194/// Empty string, to be used where LLVM expects an instruction name, indicating
195/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
196// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
197pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
198
199impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
200    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
201    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
202    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
203
204    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
205    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
206    type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
207
208    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
209    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
210    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
211}
212
213impl abi::HasDataLayout for Builder<'_, '_, '_> {
214    fn data_layout(&self) -> &abi::TargetDataLayout {
215        self.cx.data_layout()
216    }
217}
218
219impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
220    #[inline]
221    fn tcx(&self) -> TyCtxt<'tcx> {
222        self.cx.tcx
223    }
224}
225
226impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
227    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
228        self.cx.typing_env()
229    }
230}
231
232impl HasTargetSpec for Builder<'_, '_, '_> {
233    #[inline]
234    fn target_spec(&self) -> &Target {
235        self.cx.target_spec()
236    }
237}
238
239impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
240    #[inline]
241    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
242        self.cx.handle_layout_err(err, span, ty)
243    }
244}
245
246impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
247    #[inline]
248    fn handle_fn_abi_err(
249        &self,
250        err: FnAbiError<'tcx>,
251        span: Span,
252        fn_abi_request: FnAbiRequest<'tcx>,
253    ) -> ! {
254        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
255    }
256}
257
258impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
259    type Target = CodegenCx<'ll, 'tcx>;
260
261    #[inline]
262    fn deref(&self) -> &Self::Target {
263        self.cx
264    }
265}
266
267macro_rules! math_builder_methods {
268    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
269        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
270            unsafe {
271                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
272            }
273        })+
274    }
275}
276
277macro_rules! set_math_builder_methods {
278    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
279        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
280            unsafe {
281                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
282                llvm::$llvm_set_math(instr);
283                instr
284            }
285        })+
286    }
287}
288
289impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
290    type CodegenCx = CodegenCx<'ll, 'tcx>;
291
292    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
293        let bx = Builder::with_cx(cx);
294        unsafe {
295            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
296        }
297        bx
298    }
299
300    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
301        self.cx
302    }
303
304    fn llbb(&self) -> &'ll BasicBlock {
305        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
306    }
307
308    fn set_span(&mut self, span: rustc_span::Span) {
309        self.span = span;
310    }
311
312    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
313        unsafe {
314            let name = SmallCStr::new(name);
315            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
316        }
317    }
318
319    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
320        Self::append_block(self.cx, self.llfn(), name)
321    }
322
323    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
324        *self = Self::build(self.cx, llbb)
325    }
326
327    fn ret_void(&mut self) {
328        llvm::LLVMBuildRetVoid(self.llbuilder);
329    }
330
331    fn ret(&mut self, v: &'ll Value) {
332        unsafe {
333            llvm::LLVMBuildRet(self.llbuilder, v);
334        }
335    }
336
337    fn br(&mut self, dest: &'ll BasicBlock) {
338        unsafe {
339            llvm::LLVMBuildBr(self.llbuilder, dest);
340        }
341    }
342
343    fn br_with_attrs(&mut self, dest: &'ll BasicBlock, loop_hint_attrs: &[AttributeKind]) {
344        unsafe {
345            let val = llvm::LLVMBuildBr(self.llbuilder, dest);
346
347            let mut nodes = Vec::new();
348
349            for loop_hint_attr in loop_hint_attrs {
350                let AttributeKind::Unroll(unroll) = loop_hint_attr else {
351                    continue;
352                };
353                // UnrollAttr::Count needs a second operand, the provided count, but the other
354                // unroll hints do not.
355                let md_node = if let UnrollAttr::Count(count) = unroll {
356                    let unroll_meta = self.create_metadata("llvm.loop.unroll.count".as_bytes());
357                    let count = llvm::LLVMValueAsMetadata(self.get_const_i32(u64::from(*count)));
358                    self.md_node_in_context(&[unroll_meta, count])
359                } else {
360                    let metadata_str = match unroll {
361                        UnrollAttr::Hint => "llvm.loop.unroll.enable",
362                        UnrollAttr::Full => "llvm.loop.unroll.full",
363                        UnrollAttr::Never => "llvm.loop.unroll.disable",
364                        UnrollAttr::Count(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
365                    };
366                    let unroll_meta = self.create_metadata(metadata_str.as_bytes());
367                    self.md_node_in_context(&[unroll_meta])
368                };
369                nodes.push(md_node);
370            }
371
372            if let [first, ..] = nodes[..] {
373                nodes.insert(0, first);
374
375                // Create the loop metadata node
376                let loop_meta_mdnode = self.set_metadata_node(val, llvm::MD_loop, &nodes);
377
378                // Look up the metadata node as a value
379                let loop_meta_val = llvm::LLVMGetMetadata(val, llvm::MD_loop).unwrap();
380
381                // Replace the first entry with a reference to itself
382                // This is required by LLVM. See the LangRef page for llvm.loop metadata.
383                llvm::LLVMReplaceMDNodeOperandWith(loop_meta_val, 0, loop_meta_mdnode);
384            }
385        }
386    }
387
388    fn cond_br(
389        &mut self,
390        cond: &'ll Value,
391        then_llbb: &'ll BasicBlock,
392        else_llbb: &'ll BasicBlock,
393    ) {
394        unsafe {
395            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
396        }
397    }
398
399    fn switch(
400        &mut self,
401        v: &'ll Value,
402        else_llbb: &'ll BasicBlock,
403        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
404    ) {
405        let switch =
406            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
407        for (on_val, dest) in cases {
408            let on_val = self.const_uint_big(self.val_ty(v), on_val);
409            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
410        }
411    }
412
413    fn switch_with_weights(
414        &mut self,
415        v: Self::Value,
416        else_llbb: Self::BasicBlock,
417        else_is_cold: bool,
418        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
419    ) {
420        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
421            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
422            return;
423        }
424
425        let id = self.cx.create_metadata(b"branch_weights");
426
427        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
428        // This function handles switch instructions with more than 2 targets and it needs to
429        // emit branch weights metadata instead of using the intrinsic.
430        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
431        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
432        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
433        let weight =
434            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
435
436        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
437        md.push(id);
438        md.push(weight(else_is_cold));
439
440        let switch =
441            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
442        for (on_val, dest, is_cold) in cases {
443            let on_val = self.const_uint_big(self.val_ty(v), on_val);
444            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
445            md.push(weight(is_cold));
446        }
447
448        self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
449    }
450
451    fn invoke(
452        &mut self,
453        llty: &'ll Type,
454        fn_attrs: Option<&CodegenFnAttrs>,
455        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
456        llfn: &'ll Value,
457        return_slot: ReturnSlot<&'ll Value>,
458        args: &[&'ll Value],
459        then: &'ll BasicBlock,
460        catch: &'ll BasicBlock,
461        funclet: Option<&Funclet<'ll>>,
462        instance: Option<Instance<'tcx>>,
463    ) -> &'ll Value {
464        // If this function returns indirectly (`PassMode::Indirect`),
465        // the `return_slot` should be the first argument.
466        let args = match return_slot {
467            ReturnSlot::Direct => args.to_vec(),
468            ReturnSlot::Indirect(sret_ptr) => {
469                let mut args = args.to_vec();
470                args.insert(0, sret_ptr);
471                args
472            }
473        };
474        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:474",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(474u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
475        let args = self.check_call("invoke", llty, llfn, &args);
476        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
477        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
478        if let Some(funclet_bundle) = funclet_bundle {
479            bundles.push(funclet_bundle);
480        }
481
482        // Emit CFI pointer type membership test
483        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
484
485        // Emit KCFI operand bundle
486        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
487        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
488            bundles.push(kcfi_bundle);
489        }
490
491        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
492        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
493            bundles.push(p);
494        }
495
496        let invoke = unsafe {
497            llvm::LLVMBuildInvokeWithOperandBundles(
498                self.llbuilder,
499                llty,
500                llfn,
501                args.as_ptr(),
502                args.len() as c_uint,
503                then,
504                catch,
505                bundles.as_ptr(),
506                bundles.len() as c_uint,
507                UNNAMED,
508            )
509        };
510        if let Some(fn_abi) = fn_abi {
511            fn_abi.apply_attrs_callsite(self, invoke);
512        }
513        invoke
514    }
515
516    fn unreachable(&mut self) {
517        unsafe {
518            llvm::LLVMBuildUnreachable(self.llbuilder);
519        }
520    }
521
522    fn add(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED) }
}
fn fadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFAdd(self.llbuilder, a, b, UNNAMED) }
}
fn sub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED) }
}
fn fsub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFSub(self.llbuilder, a, b, UNNAMED) }
}
fn mul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED) }
}
fn fmul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFMul(self.llbuilder, a, b, UNNAMED) }
}
fn udiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildUDiv(self.llbuilder, a, b, UNNAMED) }
}
fn exactudiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildExactUDiv(self.llbuilder, a, b, UNNAMED) }
}
fn sdiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildSDiv(self.llbuilder, a, b, UNNAMED) }
}
fn exactsdiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildExactSDiv(self.llbuilder, a, b, UNNAMED) }
}
fn fdiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFDiv(self.llbuilder, a, b, UNNAMED) }
}
fn urem(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildURem(self.llbuilder, a, b, UNNAMED) }
}
fn srem(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildSRem(self.llbuilder, a, b, UNNAMED) }
}
fn frem(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFRem(self.llbuilder, a, b, UNNAMED) }
}
fn shl(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildShl(self.llbuilder, a, b, UNNAMED) }
}
fn lshr(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildLShr(self.llbuilder, a, b, UNNAMED) }
}
fn ashr(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildAShr(self.llbuilder, a, b, UNNAMED) }
}
fn and(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildAnd(self.llbuilder, a, b, UNNAMED) }
}
fn or(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED) }
}
fn xor(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildXor(self.llbuilder, a, b, UNNAMED) }
}
fn neg(&mut self, x: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNeg(self.llbuilder, x, UNNAMED) }
}
fn fneg(&mut self, x: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFNeg(self.llbuilder, x, UNNAMED) }
}
fn not(&mut self, x: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNot(self.llbuilder, x, UNNAMED) }
}
fn unchecked_sadd(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNSWAdd(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_uadd(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWAdd(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_ssub(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNSWSub(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_usub(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWSub(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_smul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNSWMul(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_umul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }
}math_builder_methods! {
523        add(a, b) => LLVMBuildAdd,
524        fadd(a, b) => LLVMBuildFAdd,
525        sub(a, b) => LLVMBuildSub,
526        fsub(a, b) => LLVMBuildFSub,
527        mul(a, b) => LLVMBuildMul,
528        fmul(a, b) => LLVMBuildFMul,
529        udiv(a, b) => LLVMBuildUDiv,
530        exactudiv(a, b) => LLVMBuildExactUDiv,
531        sdiv(a, b) => LLVMBuildSDiv,
532        exactsdiv(a, b) => LLVMBuildExactSDiv,
533        fdiv(a, b) => LLVMBuildFDiv,
534        urem(a, b) => LLVMBuildURem,
535        srem(a, b) => LLVMBuildSRem,
536        frem(a, b) => LLVMBuildFRem,
537        shl(a, b) => LLVMBuildShl,
538        lshr(a, b) => LLVMBuildLShr,
539        ashr(a, b) => LLVMBuildAShr,
540        and(a, b) => LLVMBuildAnd,
541        or(a, b) => LLVMBuildOr,
542        xor(a, b) => LLVMBuildXor,
543        neg(x) => LLVMBuildNeg,
544        fneg(x) => LLVMBuildFNeg,
545        not(x) => LLVMBuildNot,
546        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
547        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
548        unchecked_ssub(x, y) => LLVMBuildNSWSub,
549        unchecked_usub(x, y) => LLVMBuildNUWSub,
550        unchecked_smul(x, y) => LLVMBuildNSWMul,
551        unchecked_umul(x, y) => LLVMBuildNUWMul,
552    }
553
554    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
555        unsafe {
556            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
557            if llvm::LLVMIsAInstruction(add).is_some() {
558                llvm::LLVMSetNUW(add, TRUE);
559                llvm::LLVMSetNSW(add, TRUE);
560            }
561            add
562        }
563    }
564    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
565        unsafe {
566            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
567            if llvm::LLVMIsAInstruction(sub).is_some() {
568                llvm::LLVMSetNUW(sub, TRUE);
569                llvm::LLVMSetNSW(sub, TRUE);
570            }
571            sub
572        }
573    }
574    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
575        unsafe {
576            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
577            if llvm::LLVMIsAInstruction(mul).is_some() {
578                llvm::LLVMSetNUW(mul, TRUE);
579                llvm::LLVMSetNSW(mul, TRUE);
580            }
581            mul
582        }
583    }
584
585    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
586        unsafe {
587            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
588
589            // If a and b are both values, then `or` is a value, rather than
590            // an instruction, so we need to check before setting the flag.
591            // (See also `LLVMBuildNUWNeg` which also needs a check.)
592            if llvm::LLVMIsAInstruction(or).is_some() {
593                llvm::LLVMSetIsDisjoint(or, TRUE);
594            }
595            or
596        }
597    }
598
599    fn fadd_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFAdd(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fsub_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFSub(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fmul_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFMul(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fdiv_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFDiv(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn frem_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fadd_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFAdd(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fsub_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFSub(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fmul_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFMul(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fdiv_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFDiv(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn frem_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}set_math_builder_methods! {
600        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
601        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
602        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
603        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
604        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
605        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
606        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
607        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
608        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
609        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
610    }
611
612    fn checked_binop(
613        &mut self,
614        oop: OverflowOp,
615        ty: Ty<'tcx>,
616        lhs: Self::Value,
617        rhs: Self::Value,
618    ) -> (Self::Value, Self::Value) {
619        let (size, signed) = ty.int_size_and_signed(self.tcx);
620        let width = size.bits();
621
622        if !signed {
623            match oop {
624                OverflowOp::Sub => {
625                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
626                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
627                    // in the backend if profitable.
628                    let sub = self.sub(lhs, rhs);
629                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
630                    return (sub, cmp);
631                }
632                OverflowOp::Add => {
633                    // Like with sub above, using icmp is the preferred form. See
634                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
635                    let add = self.add(lhs, rhs);
636                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
637                    return (add, cmp);
638                }
639                OverflowOp::Mul => {}
640            }
641        }
642
643        let oop_str = match oop {
644            OverflowOp::Add => "add",
645            OverflowOp::Sub => "sub",
646            OverflowOp::Mul => "mul",
647        };
648
649        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' });
650
651        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
652        (self.extract_value(res, 0), self.extract_value(res, 1))
653    }
654
655    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
656        if self.cx().val_ty(val) == self.cx().type_i1() {
657            self.zext(val, self.cx().type_i8())
658        } else {
659            val
660        }
661    }
662
663    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
664        if scalar.is_bool() {
665            return self.unchecked_utrunc(val, self.cx().type_i1());
666        }
667        val
668    }
669
670    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
671        let mut bx = Builder::with_cx(self.cx);
672        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
673        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
674        unsafe {
675            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
676            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
677            // Cast to default addrspace if necessary
678            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
679        }
680    }
681
682    fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
683        let mut bx = Builder::with_cx(self.cx);
684        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
685        let scalable_vector_ty = layout.llvm_type(self.cx);
686
687        unsafe {
688            let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
689            llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
690            alloca
691        }
692    }
693
694    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
695        unsafe {
696            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
697            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
698            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
699            load
700        }
701    }
702
703    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
704        unsafe {
705            let load = self.load(ty, ptr, align);
706            llvm::LLVMSetVolatile(load, llvm::TRUE);
707            load
708        }
709    }
710
711    fn atomic_load(
712        &mut self,
713        ty: &'ll Type,
714        ptr: &'ll Value,
715        order: rustc_middle::ty::AtomicOrdering,
716        volatile: bool,
717        size: Size,
718    ) -> &'ll Value {
719        unsafe {
720            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
721            // Set atomic ordering
722            llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
723            if volatile {
724                llvm::LLVMSetVolatile(load, llvm::TRUE);
725            }
726            // LLVM requires the alignment of atomic loads to be at least the size of the type.
727            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
728            load
729        }
730    }
731
732    {}
#[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("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(732u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn ::tracing::field::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("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(749u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                                    ::tracing_core::field::FieldSet::new(&[{
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("load")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("load");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("scalar")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("scalar");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("layout")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("layout");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("offset")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("offset");
                                                                        NAME.as_str()
                                                                    }], ::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};
                                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
                                                                            as &dyn ::tracing::field::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.backend_repr.is_scalar_or_simd() {
                    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, b_offset }
                        = place.layout.backend_repr {
                    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))]
733    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
734        if place.layout.is_unsized() {
735            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
736            if matches!(tail.kind(), ty::Foreign(..)) {
737                // Unsized locals and, at least conceptually, even unsized arguments must be copied
738                // around, which requires dynamically determining their size. Therefore, we cannot
739                // allow `extern` types here. Consult t-opsem before removing this check.
740                panic!("unsized locals must not be `extern` types");
741            }
742        }
743        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
744
745        if place.layout.is_zst() {
746            return OperandRef::zero_sized(place.layout);
747        }
748
749        #[instrument(level = "trace", skip(bx))]
750        fn scalar_load_metadata<'a, 'll, 'tcx>(
751            bx: &mut Builder<'a, 'll, 'tcx>,
752            load: &'ll Value,
753            scalar: abi::Scalar,
754            layout: TyAndLayout<'tcx>,
755            offset: Size,
756        ) {
757            if bx.cx.sess().opts.optimize == OptLevel::No {
758                // Don't emit metadata we're not going to use
759                return;
760            }
761
762            if !scalar.is_uninit_valid() {
763                bx.noundef_metadata(load);
764            }
765
766            match scalar.primitive() {
767                abi::Primitive::Int(..) => {
768                    if !scalar.is_always_valid(bx) {
769                        bx.range_metadata(load, scalar.valid_range(bx));
770                    }
771                }
772                abi::Primitive::Pointer(_) => {
773                    if !scalar.valid_range(bx).contains(0) {
774                        bx.nonnull_metadata(load);
775                    }
776
777                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
778                        && pointee.align > Align::ONE
779                    {
780                        bx.align_metadata(load, pointee.align);
781                    }
782                }
783                abi::Primitive::Float(_) => {}
784            }
785        }
786
787        let val = if let Some(_) = place.val.llextra {
788            // FIXME: Merge with the `else` below?
789            OperandValue::Ref(place.val)
790        } else if place.layout.backend_repr.is_scalar_or_simd() {
791            let mut const_llval = None;
792            let llty = place.layout.llvm_type(self);
793            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
794                if llvm::LLVMIsGlobalConstant(global).is_true() {
795                    if let Some(init) = llvm::LLVMGetInitializer(global) {
796                        if self.val_ty(init) == llty {
797                            const_llval = Some(init);
798                        }
799                    }
800                }
801            }
802
803            let llval = const_llval.unwrap_or_else(|| {
804                let load = self.load(llty, place.val.llval, place.val.align);
805                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
806                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
807                    self.to_immediate_scalar(load, scalar)
808                } else {
809                    load
810                }
811            });
812            OperandValue::Immediate(llval)
813        } else if let abi::BackendRepr::ScalarPair { a, b, b_offset } = place.layout.backend_repr {
814            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
815                let llptr = if i == 0 {
816                    place.val.llval
817                } else {
818                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
819                };
820                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
821                let load = self.load(llty, llptr, align);
822                scalar_load_metadata(self, load, scalar, layout, offset);
823                self.to_immediate_scalar(load, scalar)
824            };
825
826            OperandValue::Pair(
827                load(0, a, place.layout, place.val.align, Size::ZERO),
828                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
829            )
830        } else {
831            OperandValue::Ref(place.val)
832        };
833
834        OperandRef { val, layout: place.layout, move_annotation: None }
835    }
836
837    fn write_operand_repeatedly(
838        &mut self,
839        cg_elem: OperandRef<'tcx, &'ll Value>,
840        count: u64,
841        dest: PlaceRef<'tcx, &'ll Value>,
842    ) {
843        if self.cx.sess().opts.optimize == OptLevel::No {
844            // To let debuggers single-step over lines like
845            //
846            //     let foo = ["bar"; 42];
847            //
848            // we need the debugger-friendly LLVM IR that `_unoptimized()`
849            // provides. The `_optimized()` version generates trickier LLVM IR.
850            // See PR #148058 for a failed attempt at handling that.
851            self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
852        } else {
853            self.write_operand_repeatedly_optimized(cg_elem, count, dest);
854        }
855    }
856
857    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
858        if self.cx.sess().opts.optimize == OptLevel::No {
859            // Don't emit metadata we're not going to use
860            return;
861        }
862
863        let llty = self.cx.val_ty(load);
864        let md = [
865            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
866            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
867        ];
868        self.set_metadata_node(load, llvm::MD_range, &md);
869    }
870
871    fn nonnull_metadata(&mut self, load: &'ll Value) {
872        self.set_metadata_node(load, llvm::MD_nonnull, &[]);
873    }
874
875    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
876        self.store_with_flags(val, ptr, align, MemFlags::empty())
877    }
878
879    fn store_with_flags(
880        &mut self,
881        val: &'ll Value,
882        ptr: &'ll Value,
883        align: Align,
884        flags: MemFlags,
885    ) -> &'ll Value {
886        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:886",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(886u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?} ({2:?})",
                                                    val, ptr, flags) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
887        {
    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);
888        unsafe {
889            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
890            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
891            let align = align.bytes() as c_uint;
892            llvm::LLVMSetAlignment(store, align);
893            if flags.contains(MemFlags::VOLATILE) {
894                llvm::LLVMSetVolatile(store, llvm::TRUE);
895            }
896            if flags.contains(MemFlags::NONTEMPORAL) {
897                // Make sure that the current target architectures supports "sane" non-temporal
898                // stores, i.e., non-temporal stores that are equivalent to regular stores except
899                // for performance. LLVM doesn't seem to care about this, and will happily treat
900                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
901                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
902                // regular stores but require special fences. So we keep a list of architectures
903                // where `!nontemporal` is known to be truly just a hint, and use regular stores
904                // everywhere else. (In the future, we could alternatively ensure that an sfence
905                // gets emitted after a sequence of movnt before any kind of synchronizing
906                // operation. But it's not clear how to do that with LLVM.)
907                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
908                // <https://github.com/llvm/llvm-project/issues/64521>.
909                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!(
910                    self.cx.tcx.sess.target.arch,
911                    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
912                );
913                if use_nontemporal {
914                    // According to LLVM [1] building a nontemporal store must
915                    // *always* point to a metadata value of the integer 1.
916                    //
917                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
918                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
919                    self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
920                }
921            }
922            if flags.contains(MemFlags::CAPTURES_READ_ONLY) {
923                if !(self.type_kind(self.val_ty(val)) == TypeKind::Pointer) {
    {
        ::core::panicking::panic_fmt(format_args!("CAPTURED_READ_ONLY is only supported on pointer stores"));
    }
};assert!(
924                    self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
925                    "CAPTURED_READ_ONLY is only supported on pointer stores"
926                );
927                let args = [
928                    self.cx.create_metadata(b"address"),
929                    self.cx.create_metadata(b"read_provenance"),
930                ];
931                // FIXME: Switch this to use MD_captures once LLVM 22 is the minimum.
932                let id = self.get_md_kind_id("captures");
933                let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
934                self.set_metadata(store, id, md);
935            }
936            store
937        }
938    }
939
940    fn atomic_store(
941        &mut self,
942        val: &'ll Value,
943        ptr: &'ll Value,
944        order: rustc_middle::ty::AtomicOrdering,
945        volatile: bool,
946        size: Size,
947    ) {
948        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:948",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(948u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
949        {
    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);
950        unsafe {
951            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
952            // Set atomic ordering
953            llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
954            if volatile {
955                llvm::LLVMSetVolatile(store, llvm::TRUE);
956            }
957            // LLVM requires the alignment of atomic stores to be at least the size of the type.
958            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
959        }
960    }
961
962    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
963        unsafe {
964            llvm::LLVMBuildGEPWithNoWrapFlags(
965                self.llbuilder,
966                ty,
967                ptr,
968                indices.as_ptr(),
969                indices.len() as c_uint,
970                UNNAMED,
971                GEPNoWrapFlags::default(),
972            )
973        }
974    }
975
976    fn inbounds_gep(
977        &mut self,
978        ty: &'ll Type,
979        ptr: &'ll Value,
980        indices: &[&'ll Value],
981    ) -> &'ll Value {
982        unsafe {
983            llvm::LLVMBuildGEPWithNoWrapFlags(
984                self.llbuilder,
985                ty,
986                ptr,
987                indices.as_ptr(),
988                indices.len() as c_uint,
989                UNNAMED,
990                GEPNoWrapFlags::InBounds,
991            )
992        }
993    }
994
995    fn inbounds_nuw_gep(
996        &mut self,
997        ty: &'ll Type,
998        ptr: &'ll Value,
999        indices: &[&'ll Value],
1000    ) -> &'ll Value {
1001        unsafe {
1002            llvm::LLVMBuildGEPWithNoWrapFlags(
1003                self.llbuilder,
1004                ty,
1005                ptr,
1006                indices.as_ptr(),
1007                indices.len() as c_uint,
1008                UNNAMED,
1009                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
1010            )
1011        }
1012    }
1013
1014    /* Casts */
1015    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1016        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1017    }
1018
1019    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1020        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);
1021
1022        let trunc = self.trunc(val, dest_ty);
1023        unsafe {
1024            if llvm::LLVMIsAInstruction(trunc).is_some() {
1025                llvm::LLVMSetNUW(trunc, TRUE);
1026            }
1027        }
1028        trunc
1029    }
1030
1031    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1032        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);
1033
1034        let trunc = self.trunc(val, dest_ty);
1035        unsafe {
1036            if llvm::LLVMIsAInstruction(trunc).is_some() {
1037                llvm::LLVMSetNSW(trunc, TRUE);
1038            }
1039        }
1040        trunc
1041    }
1042
1043    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1044        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
1045    }
1046
1047    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1048        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1049    }
1050
1051    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1052        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1053    }
1054
1055    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1056        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
1057        // poor codegen. The reason for this is that the corresponding wasm
1058        // instructions, `i32.trunc_f32_s` for example, will trap when the float
1059        // is out-of-bounds, infinity, or nan. This means that LLVM
1060        // automatically inserts control flow around `fptoui` and `fptosi`
1061        // because the LLVM instruction `fptoui` is defined as producing a
1062        // poison value, not having UB on out-of-bounds values.
1063        //
1064        // This method, however, is only used with non-saturating casts that
1065        // have UB on out-of-bounds values. This means that it's ok if we use
1066        // the raw wasm instruction since out-of-bounds values can do whatever
1067        // we like. To ensure that LLVM picks the right instruction we choose
1068        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1069        // other control flow automatically.
1070        if self.sess().target.is_like_wasm {
1071            let src_ty = self.cx.val_ty(val);
1072            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1073                let float_width = self.cx.float_width(src_ty);
1074                let int_width = self.cx.int_width(dest_ty);
1075                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)) {
1076                    return self.call_intrinsic(
1077                        "llvm.wasm.trunc.unsigned",
1078                        &[dest_ty, src_ty],
1079                        &[val],
1080                    );
1081                }
1082            }
1083        }
1084        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1085    }
1086
1087    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1088        // see `fptoui` above for why wasm is different here
1089        if self.sess().target.is_like_wasm {
1090            let src_ty = self.cx.val_ty(val);
1091            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1092                let float_width = self.cx.float_width(src_ty);
1093                let int_width = self.cx.int_width(dest_ty);
1094                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)) {
1095                    return self.call_intrinsic(
1096                        "llvm.wasm.trunc.signed",
1097                        &[dest_ty, src_ty],
1098                        &[val],
1099                    );
1100                }
1101            }
1102        }
1103        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1104    }
1105
1106    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1107        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1108    }
1109
1110    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1111        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1112    }
1113
1114    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1115        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1116    }
1117
1118    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1119        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1120    }
1121
1122    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1123        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1124    }
1125
1126    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1127        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1128    }
1129
1130    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1131        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1132    }
1133
1134    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1135        unsafe {
1136            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1137        }
1138    }
1139
1140    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1141        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1142    }
1143
1144    /* Comparisons */
1145    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1146        let op = llvm::IntPredicate::from_generic(op);
1147        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1148    }
1149
1150    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1151        let op = llvm::RealPredicate::from_generic(op);
1152        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1153    }
1154
1155    fn three_way_compare(
1156        &mut self,
1157        ty: Ty<'tcx>,
1158        lhs: Self::Value,
1159        rhs: Self::Value,
1160    ) -> Self::Value {
1161        let size = ty.primitive_size(self.tcx);
1162        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1163
1164        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1165    }
1166
1167    /* Miscellaneous instructions */
1168    fn memcpy(
1169        &mut self,
1170        dst: &'ll Value,
1171        dst_align: Align,
1172        src: &'ll Value,
1173        src_align: Align,
1174        size: &'ll Value,
1175        flags: MemFlags,
1176        tt: Option<FncTree>,
1177    ) {
1178        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");
1179        let size = self.intcast(size, self.type_isize(), false);
1180        let is_volatile = flags.contains(MemFlags::VOLATILE);
1181        let memcpy = unsafe {
1182            llvm::LLVMRustBuildMemCpy(
1183                self.llbuilder,
1184                dst,
1185                dst_align.bytes() as c_uint,
1186                src,
1187                src_align.bytes() as c_uint,
1188                size,
1189                is_volatile,
1190            )
1191        };
1192
1193        // TypeTree metadata for memcpy is especially important: when Enzyme encounters
1194        // a memcpy during autodiff, it needs to know the structure of the data being
1195        // copied to properly track derivatives. For example, copying an array of floats
1196        // vs. copying a struct with mixed types requires different derivative handling.
1197        // The TypeTree tells Enzyme exactly what memory layout to expect.
1198        if let Some(tt) = tt {
1199            crate::typetree::add_tt(self, memcpy, tt);
1200        }
1201    }
1202
1203    fn memmove(
1204        &mut self,
1205        dst: &'ll Value,
1206        dst_align: Align,
1207        src: &'ll Value,
1208        src_align: Align,
1209        size: &'ll Value,
1210        flags: MemFlags,
1211    ) {
1212        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");
1213        let size = self.intcast(size, self.type_isize(), false);
1214        let is_volatile = flags.contains(MemFlags::VOLATILE);
1215        unsafe {
1216            llvm::LLVMRustBuildMemMove(
1217                self.llbuilder,
1218                dst,
1219                dst_align.bytes() as c_uint,
1220                src,
1221                src_align.bytes() as c_uint,
1222                size,
1223                is_volatile,
1224            );
1225        }
1226    }
1227
1228    fn memset(
1229        &mut self,
1230        ptr: &'ll Value,
1231        fill_byte: &'ll Value,
1232        size: &'ll Value,
1233        align: Align,
1234        flags: MemFlags,
1235    ) {
1236        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");
1237        let is_volatile = flags.contains(MemFlags::VOLATILE);
1238        unsafe {
1239            llvm::LLVMRustBuildMemSet(
1240                self.llbuilder,
1241                ptr,
1242                align.bytes() as c_uint,
1243                fill_byte,
1244                size,
1245                is_volatile,
1246            );
1247        }
1248    }
1249
1250    fn vscale(&mut self, ty: &'ll Type) -> &'ll Value {
1251        unsafe { llvm::LLVMRustBuildVScale(self.llbuilder, ty) }
1252    }
1253
1254    fn select(
1255        &mut self,
1256        cond: &'ll Value,
1257        then_val: &'ll Value,
1258        else_val: &'ll Value,
1259    ) -> &'ll Value {
1260        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1261    }
1262
1263    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1264        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1265    }
1266
1267    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1268        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1269    }
1270
1271    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1272        unsafe {
1273            let elt_ty = self.cx.val_ty(elt);
1274            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1275            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1276            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1277            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1278        }
1279    }
1280
1281    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1282        {
    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);
1283        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1284    }
1285
1286    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1287        {
    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);
1288        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1289    }
1290
1291    fn set_personality_fn(&mut self, personality: &'ll Value) {
1292        unsafe {
1293            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1294        }
1295    }
1296
1297    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1298        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1299        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1300        unsafe {
1301            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1302        }
1303        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1304    }
1305
1306    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1307        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1308        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1309        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1310    }
1311
1312    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1313        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1314        let mut exn = self.const_poison(ty);
1315        exn = self.insert_value(exn, exn0, 0);
1316        exn = self.insert_value(exn, exn1, 1);
1317        unsafe {
1318            llvm::LLVMBuildResume(self.llbuilder, exn);
1319        }
1320    }
1321
1322    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1323        let ret = unsafe {
1324            llvm::LLVMBuildCleanupPad(
1325                self.llbuilder,
1326                parent,
1327                args.as_ptr(),
1328                args.len() as c_uint,
1329                c"cleanuppad".as_ptr(),
1330            )
1331        };
1332        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1333    }
1334
1335    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1336        unsafe {
1337            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1338                .expect("LLVM does not have support for cleanupret");
1339        }
1340    }
1341
1342    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1343        let ret = unsafe {
1344            llvm::LLVMBuildCatchPad(
1345                self.llbuilder,
1346                parent,
1347                args.as_ptr(),
1348                args.len() as c_uint,
1349                c"catchpad".as_ptr(),
1350            )
1351        };
1352        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1353    }
1354
1355    fn catch_switch(
1356        &mut self,
1357        parent: Option<&'ll Value>,
1358        unwind: Option<&'ll BasicBlock>,
1359        handlers: &[&'ll BasicBlock],
1360    ) -> &'ll Value {
1361        let ret = unsafe {
1362            llvm::LLVMBuildCatchSwitch(
1363                self.llbuilder,
1364                parent,
1365                unwind,
1366                handlers.len() as c_uint,
1367                c"catchswitch".as_ptr(),
1368            )
1369        };
1370        let ret = ret.expect("LLVM does not have support for catchswitch");
1371        for handler in handlers {
1372            unsafe {
1373                llvm::LLVMAddHandler(ret, handler);
1374            }
1375        }
1376        ret
1377    }
1378
1379    fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1380        funclet.cleanuppad()
1381    }
1382
1383    // Atomic Operations
1384    fn atomic_cmpxchg(
1385        &mut self,
1386        dst: &'ll Value,
1387        cmp: &'ll Value,
1388        src: &'ll Value,
1389        order: rustc_middle::ty::AtomicOrdering,
1390        failure_order: rustc_middle::ty::AtomicOrdering,
1391        weak: bool,
1392    ) -> (&'ll Value, &'ll Value) {
1393        unsafe {
1394            let value = llvm::LLVMBuildAtomicCmpXchg(
1395                self.llbuilder,
1396                dst,
1397                cmp,
1398                src,
1399                AtomicOrdering::from_generic(order),
1400                AtomicOrdering::from_generic(failure_order),
1401                llvm::FALSE, // SingleThreaded
1402            );
1403            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1404            let val = self.extract_value(value, 0);
1405            let success = self.extract_value(value, 1);
1406            (val, success)
1407        }
1408    }
1409
1410    fn atomic_rmw(
1411        &mut self,
1412        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1413        dst: &'ll Value,
1414        src: &'ll Value,
1415        order: rustc_middle::ty::AtomicOrdering,
1416        ret_ptr: bool,
1417    ) -> &'ll Value {
1418        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1419        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1420        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1421        let mut res = unsafe {
1422            llvm::LLVMBuildAtomicRMW(
1423                self.llbuilder,
1424                AtomicRmwBinOp::from_generic(op),
1425                dst,
1426                src,
1427                AtomicOrdering::from_generic(order),
1428                llvm::FALSE, // SingleThreaded
1429            )
1430        };
1431        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1432            res = self.inttoptr(res, self.type_ptr());
1433        }
1434        res
1435    }
1436
1437    fn atomic_fence(
1438        &mut self,
1439        order: rustc_middle::ty::AtomicOrdering,
1440        scope: SynchronizationScope,
1441    ) {
1442        let single_threaded = match scope {
1443            SynchronizationScope::SingleThread => true,
1444            SynchronizationScope::CrossThread => false,
1445        };
1446        unsafe {
1447            llvm::LLVMBuildFence(
1448                self.llbuilder,
1449                AtomicOrdering::from_generic(order),
1450                single_threaded.to_llvm_bool(),
1451                UNNAMED,
1452            );
1453        }
1454    }
1455
1456    fn set_invariant_load(&mut self, load: &'ll Value) {
1457        self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1458    }
1459
1460    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1461        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1462    }
1463
1464    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1465        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1466    }
1467
1468    fn call(
1469        &mut self,
1470        llty: &'ll Type,
1471        caller_attrs: Option<&CodegenFnAttrs>,
1472        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1473        llfn: &'ll Value,
1474        return_slot: ReturnSlot<&'ll Value>,
1475        args: &[&'ll Value],
1476        funclet: Option<&Funclet<'ll>>,
1477        callee_instance: Option<Instance<'tcx>>,
1478    ) -> &'ll Value {
1479        // If this function returns indirectly (`PassMode::Indirect`),
1480        // the `return_slot` should be the first argument.
1481        let args = match return_slot {
1482            ReturnSlot::Direct => args.to_vec(),
1483            ReturnSlot::Indirect(sret_ptr) => {
1484                let mut args = args.to_vec();
1485                args.insert(0, sret_ptr);
1486                args
1487            }
1488        };
1489        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:1489",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1489u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1490        let args = self.check_call("call", llty, llfn, &args);
1491        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1492        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1493        if let Some(funclet_bundle) = funclet_bundle {
1494            bundles.push(funclet_bundle);
1495        }
1496
1497        // Emit CFI pointer type membership test
1498        self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1499
1500        // Emit KCFI operand bundle
1501        let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1502        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1503            bundles.push(kcfi_bundle);
1504        }
1505
1506        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1507        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1508            bundles.push(p);
1509        }
1510
1511        let call = unsafe {
1512            llvm::LLVMBuildCallWithOperandBundles(
1513                self.llbuilder,
1514                llty,
1515                llfn,
1516                args.as_ptr() as *const &llvm::Value,
1517                args.len() as c_uint,
1518                bundles.as_ptr(),
1519                bundles.len() as c_uint,
1520                c"".as_ptr(),
1521            )
1522        };
1523
1524        if let Some(fn_abi) = fn_abi {
1525            fn_abi.apply_attrs_callsite(self, call);
1526        }
1527        call
1528    }
1529
1530    fn tail_call(
1531        &mut self,
1532        llty: Self::Type,
1533        caller_attrs: Option<&CodegenFnAttrs>,
1534        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1535        llfn: Self::Value,
1536        return_slot: ReturnSlot<Self::Value>,
1537        args: &[Self::Value],
1538        funclet: Option<&Self::Funclet>,
1539        callee_instance: Option<Instance<'tcx>>,
1540    ) {
1541        let call = self.call(
1542            llty,
1543            caller_attrs,
1544            Some(fn_abi),
1545            llfn,
1546            return_slot,
1547            args,
1548            funclet,
1549            callee_instance,
1550        );
1551        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1552
1553        match &fn_abi.ret.mode {
1554            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1555            PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1556        }
1557    }
1558
1559    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1560        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1561    }
1562
1563    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1564        // Cleanup is always the cold path.
1565        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1566        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1567    }
1568}
1569
1570impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1571    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1572        // Forward to the `get_static` method of `CodegenCx`
1573        let global = self.cx().get_static(def_id);
1574        if self.cx().tcx.is_thread_local_static(def_id) {
1575            let pointer =
1576                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1577            // Cast to default address space if globals are in a different addrspace
1578            self.pointercast(pointer, self.type_ptr())
1579        } else {
1580            // Cast to default address space if globals are in a different addrspace
1581            self.cx().const_pointercast(global, self.type_ptr())
1582        }
1583    }
1584}
1585
1586impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1587    pub(crate) fn llfn(&self) -> &'ll Value {
1588        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1589    }
1590
1591    fn generate_ubsan_cfi_diag_data(
1592        &mut self,
1593        span: rustc_span::Span,
1594        expected_ty: String,
1595        check_kind: u8,
1596    ) -> &'ll Value {
1597        let cx = self.cx();
1598        let tcx = cx.tcx;
1599
1600        let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
1601
1602        let filename_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0",
                loc.file.name.prefer_local_unconditionally()))
    })format!("{}\0", loc.file.name.prefer_local_unconditionally());
1603        let filename_val = cx.const_bytes(filename_str.as_bytes());
1604        let filename_ptr = cx.static_addr_of_impl(filename_val, Align::ONE, None);
1605
1606        // SourceLocation UBSan struct: { const char *filename, uint32_t line, uint32_t column }
1607        let source_location = cx.const_struct(
1608            &[
1609                filename_ptr,
1610                cx.const_u32(loc.line as u32),
1611                // UBSan columns are 1-based
1612                cx.const_u32(loc.col.0 as u32 + 1),
1613            ],
1614            false, // packed = false
1615        );
1616
1617        let ty_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0", expected_ty))
    })format!("{}\0", expected_ty);
1618        let ty_name_val = cx.const_bytes(ty_name.as_bytes());
1619
1620        // TypeDescriptor UBSan struct: { uint16_t TypeKind, uint16_t TypeInfo, const char *TypeName }
1621        let type_descriptor =
1622            cx.const_struct(&[cx.const_i16(0xffffu16 as i16), cx.const_i16(0), ty_name_val], false);
1623
1624        let type_descriptor_ptr =
1625            cx.static_addr_of_impl(type_descriptor, Align::from_bytes(2).unwrap(), None);
1626
1627        // CFICheckFailData UBSan struct: { uint8_t CheckKind, SourceLocation Loc, TypeDescriptor *Type }
1628        let cfi_check_fail_data = cx
1629            .const_struct(&[cx.const_u8(check_kind), source_location, type_descriptor_ptr], false);
1630        let align = tcx.data_layout.aggregate_align;
1631
1632        // Returns the final opaque pointer to the struct to be passed to __ubsan_handle_cfi_check_fail
1633        cx.static_addr_of_mut(cfi_check_fail_data, align, Some("__ubsan_cfi_check_fail_data"))
1634    }
1635}
1636
1637impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1638    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1639        unsafe {
1640            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1641        }
1642    }
1643}
1644impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1645    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1646        let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1647        self.set_metadata_node(load, llvm::MD_align, &md);
1648    }
1649
1650    fn noundef_metadata(&mut self, load: &'ll Value) {
1651        self.set_metadata_node(load, llvm::MD_noundef, &[]);
1652    }
1653
1654    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1655        self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1656    }
1657
1658    fn write_operand_repeatedly_optimized(
1659        &mut self,
1660        cg_elem: OperandRef<'tcx, &'ll Value>,
1661        count: u64,
1662        dest: PlaceRef<'tcx, &'ll Value>,
1663    ) {
1664        let zero = self.const_usize(0);
1665        let count = self.const_usize(count);
1666
1667        let header_bb = self.append_sibling_block("repeat_loop_header");
1668        let body_bb = self.append_sibling_block("repeat_loop_body");
1669        let next_bb = self.append_sibling_block("repeat_loop_next");
1670
1671        self.br(header_bb);
1672
1673        let mut header_bx = Self::build(self.cx, header_bb);
1674        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1675
1676        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1677        header_bx.cond_br(keep_going, body_bb, next_bb);
1678
1679        let mut body_bx = Self::build(self.cx, body_bb);
1680        let dest_elem = dest.project_index(&mut body_bx, i);
1681        cg_elem.val.store(&mut body_bx, dest_elem);
1682
1683        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1684        body_bx.br(header_bb);
1685        header_bx.add_incoming_to_phi(i, next, body_bb);
1686
1687        *self = Self::build(self.cx, next_bb);
1688    }
1689
1690    fn write_operand_repeatedly_unoptimized(
1691        &mut self,
1692        cg_elem: OperandRef<'tcx, &'ll Value>,
1693        count: u64,
1694        dest: PlaceRef<'tcx, &'ll Value>,
1695    ) {
1696        let zero = self.const_usize(0);
1697        let count = self.const_usize(count);
1698        let start = dest.project_index(self, zero).val.llval;
1699        let end = dest.project_index(self, count).val.llval;
1700
1701        let header_bb = self.append_sibling_block("repeat_loop_header");
1702        let body_bb = self.append_sibling_block("repeat_loop_body");
1703        let next_bb = self.append_sibling_block("repeat_loop_next");
1704
1705        self.br(header_bb);
1706
1707        let mut header_bx = Self::build(self.cx, header_bb);
1708        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1709
1710        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1711        header_bx.cond_br(keep_going, body_bb, next_bb);
1712
1713        let mut body_bx = Self::build(self.cx, body_bb);
1714        let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1715        cg_elem
1716            .val
1717            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1718
1719        let next = body_bx.inbounds_gep(
1720            self.backend_type(cg_elem.layout),
1721            current,
1722            &[self.const_usize(1)],
1723        );
1724        body_bx.br(header_bb);
1725        header_bx.add_incoming_to_phi(current, next, body_bb);
1726
1727        *self = Self::build(self.cx, next_bb);
1728    }
1729
1730    pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1731        let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1732        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1733        call
1734    }
1735
1736    pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1737        let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1738        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1739        call
1740    }
1741
1742    pub(crate) fn insert_element(
1743        &mut self,
1744        vec: &'ll Value,
1745        elt: &'ll Value,
1746        idx: &'ll Value,
1747    ) -> &'ll Value {
1748        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1749    }
1750
1751    pub(crate) fn shuffle_vector(
1752        &mut self,
1753        v1: &'ll Value,
1754        v2: &'ll Value,
1755        mask: &'ll Value,
1756    ) -> &'ll Value {
1757        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1758    }
1759
1760    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1761        self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1762    }
1763    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1764        self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1765    }
1766    pub(crate) fn vector_reduce_fadd_reassoc(
1767        &mut self,
1768        acc: &'ll Value,
1769        src: &'ll Value,
1770    ) -> &'ll Value {
1771        unsafe {
1772            let instr =
1773                self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1774            llvm::LLVMRustSetAllowReassoc(instr);
1775            instr
1776        }
1777    }
1778    pub(crate) fn vector_reduce_fmul_reassoc(
1779        &mut self,
1780        acc: &'ll Value,
1781        src: &'ll Value,
1782    ) -> &'ll Value {
1783        unsafe {
1784            let instr =
1785                self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1786            llvm::LLVMRustSetAllowReassoc(instr);
1787            instr
1788        }
1789    }
1790    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1791        self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1792    }
1793    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1794        self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1795    }
1796    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1797        self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1798    }
1799    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1800        self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1801    }
1802    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1803        self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1804    }
1805    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1806        self.call_intrinsic(
1807            if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1808            &[self.val_ty(src)],
1809            &[src],
1810        )
1811    }
1812    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1813        self.call_intrinsic(
1814            if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1815            &[self.val_ty(src)],
1816            &[src],
1817        )
1818    }
1819}
1820impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1821    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1822        unsafe {
1823            llvm::LLVMAddClause(landing_pad, clause);
1824        }
1825    }
1826
1827    pub(crate) fn catch_ret(
1828        &mut self,
1829        funclet: &Funclet<'ll>,
1830        unwind: &'ll BasicBlock,
1831    ) -> &'ll Value {
1832        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1833        ret.expect("LLVM does not have support for catchret")
1834    }
1835
1836    pub(crate) fn check_call<'b>(
1837        &mut self,
1838        typ: &str,
1839        fn_ty: &'ll Type,
1840        llfn: &'ll Value,
1841        args: &'b [&'ll Value],
1842    ) -> Cow<'b, [&'ll Value]> {
1843        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!(
1844            self.cx.type_kind(fn_ty) == TypeKind::Function,
1845            "builder::{typ} not passed a function, but {fn_ty:?}"
1846        );
1847
1848        let param_tys = self.cx.func_params_types(fn_ty);
1849
1850        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1851            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1852
1853        if all_args_match {
1854            return Cow::Borrowed(args);
1855        }
1856
1857        let casted_args: Vec<_> = iter::zip(param_tys, args)
1858            .enumerate()
1859            .map(|(i, (expected_ty, &actual_val))| {
1860                let actual_ty = self.cx.val_ty(actual_val);
1861                if expected_ty != actual_ty {
1862                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:1862",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1862u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1863                        "type mismatch in function call of {:?}. \
1864                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1865                        llfn, expected_ty, i, actual_ty
1866                    );
1867                    self.bitcast(actual_val, expected_ty)
1868                } else {
1869                    actual_val
1870                }
1871            })
1872            .collect();
1873
1874        Cow::Owned(casted_args)
1875    }
1876
1877    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1878        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1879    }
1880}
1881
1882impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1883    pub(crate) fn call_intrinsic(
1884        &mut self,
1885        base_name: impl Into<Cow<'static, str>>,
1886        type_params: &[&'ll Type],
1887        args: &[&'ll Value],
1888    ) -> &'ll Value {
1889        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1890        // No LLVM intrinsic returns its data indirectly (via `sret`).
1891        self.call(ty, None, None, f, ReturnSlot::Direct, args, None, None)
1892    }
1893
1894    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1895        let size = size.bytes();
1896        if size == 0 {
1897            return;
1898        }
1899
1900        if !self.cx().sess().emit_lifetime_markers() {
1901            return;
1902        }
1903
1904        // LLVM 22 requires the lifetime intrinsic to act directly on the alloca,
1905        // there can't be an addrspacecast in between.
1906        let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1907        self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1908    }
1909}
1910impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1911    pub(crate) fn phi(
1912        &mut self,
1913        ty: &'ll Type,
1914        vals: &[&'ll Value],
1915        bbs: &[&'ll BasicBlock],
1916    ) -> &'ll Value {
1917        {
    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());
1918        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1919        unsafe {
1920            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1921            phi
1922        }
1923    }
1924
1925    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1926        unsafe {
1927            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1928        }
1929    }
1930}
1931impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1932    pub(crate) fn landing_pad(
1933        &mut self,
1934        ty: &'ll Type,
1935        pers_fn: &'ll Value,
1936        num_clauses: usize,
1937    ) -> &'ll Value {
1938        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1939        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1940        // personality lives on the parent function anyway.
1941        self.set_personality_fn(pers_fn);
1942        unsafe {
1943            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1944        }
1945    }
1946
1947    pub(crate) fn callbr(
1948        &mut self,
1949        llty: &'ll Type,
1950        fn_attrs: Option<&CodegenFnAttrs>,
1951        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1952        llfn: &'ll Value,
1953        args: &[&'ll Value],
1954        default_dest: &'ll BasicBlock,
1955        indirect_dest: &[&'ll BasicBlock],
1956        funclet: Option<&Funclet<'ll>>,
1957        instance: Option<Instance<'tcx>>,
1958    ) -> &'ll Value {
1959        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs:1959",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1959u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1960
1961        let args = self.check_call("callbr", llty, llfn, args);
1962        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1963        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1964        if let Some(funclet_bundle) = funclet_bundle {
1965            bundles.push(funclet_bundle);
1966        }
1967
1968        // Emit CFI pointer type membership test
1969        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1970
1971        // Emit KCFI operand bundle
1972        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1973        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|bundle| bundle.as_ref()) {
1974            bundles.push(kcfi_bundle);
1975        }
1976
1977        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1978        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1979            bundles.push(p);
1980        }
1981
1982        let callbr = unsafe {
1983            llvm::LLVMBuildCallBr(
1984                self.llbuilder,
1985                llty,
1986                llfn,
1987                default_dest,
1988                indirect_dest.as_ptr(),
1989                indirect_dest.len() as c_uint,
1990                args.as_ptr(),
1991                args.len() as c_uint,
1992                bundles.as_ptr(),
1993                bundles.len() as c_uint,
1994                UNNAMED,
1995            )
1996        };
1997        if let Some(fn_abi) = fn_abi {
1998            fn_abi.apply_attrs_callsite(self, callbr);
1999        }
2000        callbr
2001    }
2002
2003    // Emits CFI pointer type membership tests.
2004    fn cfi_type_test(
2005        &mut self,
2006        fn_attrs: Option<&CodegenFnAttrs>,
2007        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2008        instance: Option<Instance<'tcx>>,
2009        llfn: &'ll Value,
2010    ) {
2011        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2012        if self.tcx.sess.is_sanitizer_cfi_enabled()
2013            && let Some(fn_abi) = fn_abi
2014            && is_indirect_call
2015        {
2016            if let Some(fn_attrs) = fn_attrs
2017                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
2018            {
2019                return;
2020            }
2021            if crate::llvm::HasStringAttribute(self.llfn(), "no-sanitize-cfi") {
2022                return;
2023            }
2024
2025            let mut options = cfi::TypeIdOptions::empty();
2026            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2027                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
2028            }
2029            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2030                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
2031            }
2032
2033            if self.cx.is_sanitizer_type_ignored(c"cfi", fn_abi) {
2034                return;
2035            }
2036
2037            let typeid = if let Some(instance) = instance {
2038                cfi::typeid_for_instance(self.tcx, instance, options)
2039            } else {
2040                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2041            };
2042            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
2043            let dbg_loc = self.get_dbg_loc();
2044
2045            // Test whether the function pointer is associated with the type identifier using the
2046            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
2047            // calls to this intrinsic with code to test type membership.
2048            let typeid = self.get_metadata_value(typeid_metadata);
2049            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
2050            let bb_pass = self.append_sibling_block("type_test.pass");
2051            let bb_fail = self.append_sibling_block("type_test.fail");
2052            self.cond_br(cond, bb_pass, bb_fail);
2053
2054            self.switch_to_block(bb_fail);
2055            if let Some(dbg_loc) = dbg_loc {
2056                self.set_dbg_loc(dbg_loc);
2057            }
2058
2059            let is_diag = self.tcx.sess.opts.unstable_opts.sanitizer_cfi_diag.unwrap_or(false);
2060            let is_recover =
2061                self.tcx.sess.opts.unstable_opts.sanitizer_cfi_recover.unwrap_or(false);
2062            let is_minimal =
2063                self.tcx.sess.opts.unstable_opts.sanitizer_cfi_minimal_runtime.unwrap_or(false);
2064
2065            if is_diag || is_recover {
2066                let fty = if is_minimal {
2067                    self.cx.type_func(&[], self.cx.type_void())
2068                } else {
2069                    self.cx.type_func(
2070                        &[self.cx.type_ptr(), self.cx.type_isize(), self.cx.type_isize()],
2071                        self.cx.type_void(),
2072                    )
2073                };
2074                let ubsan_handler = self.declare_cfn(
2075                    match (is_minimal, is_recover) {
2076                        (true, true) => "__ubsan_handle_cfi_check_fail_minimal",
2077                        (true, false) => "__ubsan_handle_cfi_check_fail_minimal_abort",
2078                        (false, true) => "__ubsan_handle_cfi_check_fail",
2079                        (false, false) => "__ubsan_handle_cfi_check_fail_abort",
2080                    },
2081                    llvm::UnnamedAddr::Global,
2082                    fty,
2083                );
2084
2085                let mut expected_ty = String::from("fn(");
2086                for (i, arg) in fn_abi.args.iter().enumerate() {
2087                    if i > 0 {
2088                        expected_ty.push_str(", ");
2089                    }
2090                    use std::fmt::Write;
2091                    (&mut expected_ty).write_fmt(format_args!("{0}", arg.layout.ty))write!(&mut expected_ty, "{}", arg.layout.ty).unwrap();
2092                }
2093                expected_ty.push(')');
2094                if !fn_abi.ret.layout.ty.is_unit() {
2095                    use std::fmt::Write;
2096                    (&mut expected_ty).write_fmt(format_args!(" -> {0}", fn_abi.ret.layout.ty))write!(&mut expected_ty, " -> {}", fn_abi.ret.layout.ty).unwrap();
2097                }
2098
2099                // 4 for cfi-icall (indirect call)
2100                let check_kind = 4;
2101                let diag_data =
2102                    self.generate_ubsan_cfi_diag_data(self.span, expected_ty, check_kind);
2103
2104                let function_address = self.ptrtoint(llfn, self.cx.type_isize());
2105                let arguments: &[_] = if is_minimal {
2106                    &[]
2107                } else {
2108                    &[diag_data, function_address, self.const_usize(0)]
2109                };
2110                self.call(
2111                    fty,
2112                    None,
2113                    None,
2114                    ubsan_handler,
2115                    ReturnSlot::Direct,
2116                    arguments,
2117                    None,
2118                    None,
2119                );
2120                if is_recover {
2121                    self.br(bb_pass);
2122                } else {
2123                    self.unreachable();
2124                }
2125            } else {
2126                self.abort_immediate();
2127                self.unreachable();
2128            }
2129
2130            self.switch_to_block(bb_pass);
2131            if let Some(dbg_loc) = dbg_loc {
2132                self.set_dbg_loc(dbg_loc);
2133            }
2134        }
2135    }
2136
2137    // Emits KCFI operand bundles.
2138    fn kcfi_operand_bundle(
2139        &mut self,
2140        fn_attrs: Option<&CodegenFnAttrs>,
2141        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2142        instance: Option<Instance<'tcx>>,
2143        llfn: &'ll Value,
2144    ) -> Option<llvm::OperandBundleBox<'ll>> {
2145        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2146        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
2147            && let Some(fn_abi) = fn_abi
2148            && is_indirect_call
2149        {
2150            if let Some(fn_attrs) = fn_attrs
2151                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
2152            {
2153                return None;
2154            }
2155            if crate::llvm::HasStringAttribute(self.llfn(), "no-sanitize-kcfi") {
2156                return None;
2157            }
2158
2159            let mut options = kcfi::TypeIdOptions::empty();
2160            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2161                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2162            }
2163            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2164                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2165            }
2166
2167            if self.cx.is_sanitizer_type_ignored(c"kcfi", fn_abi) {
2168                return None;
2169            }
2170
2171            let kcfi_typeid = if let Some(instance) = instance {
2172                kcfi::typeid_for_instance(self.tcx, instance, options)
2173            } else {
2174                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2175            };
2176
2177            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2178        } else {
2179            None
2180        };
2181        kcfi_bundle
2182    }
2183
2184    // Emits pauth operand bundle.
2185    fn ptrauth_operand_bundle(
2186        &mut self,
2187        llfn: &'ll Value,
2188        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2189    ) -> Option<llvm::OperandBundleBox<'ll>> {
2190        if self.sess().pointer_authentication_functions().is_none() {
2191            return None;
2192        }
2193        // Pointer authentication support is currently limited to extern "C" calls; filter out other
2194        // ABIs.
2195        if fn_abi?.conv != CanonAbi::C {
2196            return None;
2197        }
2198        // Filter out LLVM intrinsics.
2199        if llvm::get_value_name(llfn).starts_with(b"llvm.") {
2200            return None;
2201        }
2202
2203        // FIXME(jchlanda) Operand bundles should only be attached to indirect function calls.
2204        // However, function pointer signing is currently performed in `get_fn_addr`, which causes
2205        // the logic to be applied too broadly, including to function values (not just pointers).
2206        // As a result, direct calls using signed function values must also receive operand
2207        // bundles.
2208        // Once this is resolved, we should analyze each call and skip direct calls. See the
2209        // discussion in the rust-lang issue: <https://github.com/rust-lang/rust/issues/152532>
2210        let key: u32 = 0;
2211        let discriminator: u64 = 0;
2212        Some(llvm::OperandBundleBox::new(
2213            "ptrauth",
2214            &[self.const_u32(key), self.const_u64(discriminator)],
2215        ))
2216    }
2217
2218    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
2219    {}
#[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("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2219u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hash")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hash");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("num_counters")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("num_counters");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("index");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
                                                            as &dyn ::tracing::field::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))]
2220    pub(crate) fn instrprof_increment(
2221        &mut self,
2222        fn_name: &'ll Value,
2223        hash: &'ll Value,
2224        num_counters: &'ll Value,
2225        index: &'ll Value,
2226    ) {
2227        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2228    }
2229}