rustc_codegen_llvm/
builder.rs

1use std::borrow::{Borrow, Cow};
2use std::ops::Deref;
3use std::{iter, ptr};
4
5pub(crate) mod autodiff;
6pub(crate) mod gpu_offload;
7
8use libc::{c_char, c_uint, size_t};
9use rustc_abi as abi;
10use rustc_abi::{Align, Size, WrappingRange};
11use rustc_codegen_ssa::MemFlags;
12use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::PlaceRef;
15use rustc_codegen_ssa::traits::*;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::def_id::DefId;
18use rustc_middle::bug;
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::{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, GEPNoWrapFlags, Metadata, TRUE, ToLlvmBool,
39};
40use crate::type_::Type;
41use crate::type_of::LayoutLlvmExt;
42use crate::value::Value;
43
44#[must_use]
45pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
46    pub llbuilder: &'ll mut llvm::Builder<'ll>,
47    pub cx: &'a GenericCx<'ll, CX>,
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        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 }
99    }
100
101    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
102        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
103    }
104
105    pub(crate) fn ret_void(&mut self) {
106        llvm::LLVMBuildRetVoid(self.llbuilder);
107    }
108
109    pub(crate) fn ret(&mut self, v: &'ll Value) {
110        unsafe {
111            llvm::LLVMBuildRet(self.llbuilder, v);
112        }
113    }
114
115    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
116        let bx = Self::with_cx(cx);
117        unsafe {
118            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
119        }
120        bx
121    }
122
123    // The generic builder has less functionality and thus (unlike the other alloca) we can not
124    // easily jump to the beginning of the function to place our allocas there. We trust the user
125    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
126    // handle this.
127    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
128        let val = unsafe {
129            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
130            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
131            // Cast to default addrspace if necessary
132            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
133        };
134        if name != "" {
135            let name = std::ffi::CString::new(name).unwrap();
136            llvm::set_value_name(val, &name.as_bytes());
137        }
138        val
139    }
140
141    pub(crate) fn inbounds_gep(
142        &mut self,
143        ty: &'ll Type,
144        ptr: &'ll Value,
145        indices: &[&'ll Value],
146    ) -> &'ll Value {
147        unsafe {
148            llvm::LLVMBuildGEPWithNoWrapFlags(
149                self.llbuilder,
150                ty,
151                ptr,
152                indices.as_ptr(),
153                indices.len() as c_uint,
154                UNNAMED,
155                GEPNoWrapFlags::InBounds,
156            )
157        }
158    }
159
160    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
161        debug!("Store {:?} -> {:?}", val, ptr);
162        assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
163        unsafe {
164            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
165            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
166            store
167        }
168    }
169
170    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
171        unsafe {
172            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
173            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
174            load
175        }
176    }
177
178    fn memset(&mut self, ptr: &'ll Value, fill_byte: &'ll Value, size: &'ll Value, align: Align) {
179        unsafe {
180            llvm::LLVMRustBuildMemSet(
181                self.llbuilder,
182                ptr,
183                align.bytes() as c_uint,
184                fill_byte,
185                size,
186                false,
187            );
188        }
189    }
190}
191
192/// Empty string, to be used where LLVM expects an instruction name, indicating
193/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
194// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
195pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
196
197impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
198    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
199    type Metadata = <GenericCx<'ll, CX> as BackendTypes>::Metadata;
200    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
201    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
202    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
203    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
204
205    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
206    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
207    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
208}
209
210impl abi::HasDataLayout for Builder<'_, '_, '_> {
211    fn data_layout(&self) -> &abi::TargetDataLayout {
212        self.cx.data_layout()
213    }
214}
215
216impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
217    #[inline]
218    fn tcx(&self) -> TyCtxt<'tcx> {
219        self.cx.tcx
220    }
221}
222
223impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
224    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
225        self.cx.typing_env()
226    }
227}
228
229impl HasTargetSpec for Builder<'_, '_, '_> {
230    #[inline]
231    fn target_spec(&self) -> &Target {
232        self.cx.target_spec()
233    }
234}
235
236impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
237    #[inline]
238    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
239        self.cx.handle_layout_err(err, span, ty)
240    }
241}
242
243impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
244    #[inline]
245    fn handle_fn_abi_err(
246        &self,
247        err: FnAbiError<'tcx>,
248        span: Span,
249        fn_abi_request: FnAbiRequest<'tcx>,
250    ) -> ! {
251        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
252    }
253}
254
255impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
256    type Target = CodegenCx<'ll, 'tcx>;
257
258    #[inline]
259    fn deref(&self) -> &Self::Target {
260        self.cx
261    }
262}
263
264macro_rules! math_builder_methods {
265    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
266        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
267            unsafe {
268                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
269            }
270        })+
271    }
272}
273
274macro_rules! set_math_builder_methods {
275    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
276        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
277            unsafe {
278                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
279                llvm::$llvm_set_math(instr);
280                instr
281            }
282        })+
283    }
284}
285
286impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
287    type CodegenCx = CodegenCx<'ll, 'tcx>;
288
289    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
290        let bx = Builder::with_cx(cx);
291        unsafe {
292            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
293        }
294        bx
295    }
296
297    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
298        self.cx
299    }
300
301    fn llbb(&self) -> &'ll BasicBlock {
302        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
303    }
304
305    fn set_span(&mut self, _span: Span) {}
306
307    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
308        unsafe {
309            let name = SmallCStr::new(name);
310            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
311        }
312    }
313
314    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
315        Self::append_block(self.cx, self.llfn(), name)
316    }
317
318    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
319        *self = Self::build(self.cx, llbb)
320    }
321
322    fn ret_void(&mut self) {
323        llvm::LLVMBuildRetVoid(self.llbuilder);
324    }
325
326    fn ret(&mut self, v: &'ll Value) {
327        unsafe {
328            llvm::LLVMBuildRet(self.llbuilder, v);
329        }
330    }
331
332    fn br(&mut self, dest: &'ll BasicBlock) {
333        unsafe {
334            llvm::LLVMBuildBr(self.llbuilder, dest);
335        }
336    }
337
338    fn cond_br(
339        &mut self,
340        cond: &'ll Value,
341        then_llbb: &'ll BasicBlock,
342        else_llbb: &'ll BasicBlock,
343    ) {
344        unsafe {
345            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
346        }
347    }
348
349    fn switch(
350        &mut self,
351        v: &'ll Value,
352        else_llbb: &'ll BasicBlock,
353        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
354    ) {
355        let switch =
356            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
357        for (on_val, dest) in cases {
358            let on_val = self.const_uint_big(self.val_ty(v), on_val);
359            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
360        }
361    }
362
363    fn switch_with_weights(
364        &mut self,
365        v: Self::Value,
366        else_llbb: Self::BasicBlock,
367        else_is_cold: bool,
368        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
369    ) {
370        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
371            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
372            return;
373        }
374
375        let id = self.cx.create_metadata(b"branch_weights");
376
377        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
378        // This function handles switch instructions with more than 2 targets and it needs to
379        // emit branch weights metadata instead of using the intrinsic.
380        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
381        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
382        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
383        let weight =
384            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
385
386        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
387        md.push(id);
388        md.push(weight(else_is_cold));
389
390        let switch =
391            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
392        for (on_val, dest, is_cold) in cases {
393            let on_val = self.const_uint_big(self.val_ty(v), on_val);
394            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
395            md.push(weight(is_cold));
396        }
397
398        unsafe {
399            let md_node = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len() as size_t);
400            self.cx.set_metadata(switch, llvm::MD_prof, md_node);
401        }
402    }
403
404    fn invoke(
405        &mut self,
406        llty: &'ll Type,
407        fn_attrs: Option<&CodegenFnAttrs>,
408        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
409        llfn: &'ll Value,
410        args: &[&'ll Value],
411        then: &'ll BasicBlock,
412        catch: &'ll BasicBlock,
413        funclet: Option<&Funclet<'ll>>,
414        instance: Option<Instance<'tcx>>,
415    ) -> &'ll Value {
416        debug!("invoke {:?} with args ({:?})", llfn, args);
417
418        let args = self.check_call("invoke", llty, llfn, args);
419        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
420        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
421        if let Some(funclet_bundle) = funclet_bundle {
422            bundles.push(funclet_bundle);
423        }
424
425        // Emit CFI pointer type membership test
426        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
427
428        // Emit KCFI operand bundle
429        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
430        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
431            bundles.push(kcfi_bundle);
432        }
433
434        let invoke = unsafe {
435            llvm::LLVMBuildInvokeWithOperandBundles(
436                self.llbuilder,
437                llty,
438                llfn,
439                args.as_ptr(),
440                args.len() as c_uint,
441                then,
442                catch,
443                bundles.as_ptr(),
444                bundles.len() as c_uint,
445                UNNAMED,
446            )
447        };
448        if let Some(fn_abi) = fn_abi {
449            fn_abi.apply_attrs_callsite(self, invoke);
450        }
451        invoke
452    }
453
454    fn unreachable(&mut self) {
455        unsafe {
456            llvm::LLVMBuildUnreachable(self.llbuilder);
457        }
458    }
459
460    math_builder_methods! {
461        add(a, b) => LLVMBuildAdd,
462        fadd(a, b) => LLVMBuildFAdd,
463        sub(a, b) => LLVMBuildSub,
464        fsub(a, b) => LLVMBuildFSub,
465        mul(a, b) => LLVMBuildMul,
466        fmul(a, b) => LLVMBuildFMul,
467        udiv(a, b) => LLVMBuildUDiv,
468        exactudiv(a, b) => LLVMBuildExactUDiv,
469        sdiv(a, b) => LLVMBuildSDiv,
470        exactsdiv(a, b) => LLVMBuildExactSDiv,
471        fdiv(a, b) => LLVMBuildFDiv,
472        urem(a, b) => LLVMBuildURem,
473        srem(a, b) => LLVMBuildSRem,
474        frem(a, b) => LLVMBuildFRem,
475        shl(a, b) => LLVMBuildShl,
476        lshr(a, b) => LLVMBuildLShr,
477        ashr(a, b) => LLVMBuildAShr,
478        and(a, b) => LLVMBuildAnd,
479        or(a, b) => LLVMBuildOr,
480        xor(a, b) => LLVMBuildXor,
481        neg(x) => LLVMBuildNeg,
482        fneg(x) => LLVMBuildFNeg,
483        not(x) => LLVMBuildNot,
484        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
485        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
486        unchecked_ssub(x, y) => LLVMBuildNSWSub,
487        unchecked_usub(x, y) => LLVMBuildNUWSub,
488        unchecked_smul(x, y) => LLVMBuildNSWMul,
489        unchecked_umul(x, y) => LLVMBuildNUWMul,
490    }
491
492    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
493        unsafe {
494            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
495            if llvm::LLVMIsAInstruction(add).is_some() {
496                llvm::LLVMSetNUW(add, TRUE);
497                llvm::LLVMSetNSW(add, TRUE);
498            }
499            add
500        }
501    }
502    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
503        unsafe {
504            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
505            if llvm::LLVMIsAInstruction(sub).is_some() {
506                llvm::LLVMSetNUW(sub, TRUE);
507                llvm::LLVMSetNSW(sub, TRUE);
508            }
509            sub
510        }
511    }
512    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
513        unsafe {
514            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
515            if llvm::LLVMIsAInstruction(mul).is_some() {
516                llvm::LLVMSetNUW(mul, TRUE);
517                llvm::LLVMSetNSW(mul, TRUE);
518            }
519            mul
520        }
521    }
522
523    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
524        unsafe {
525            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
526
527            // If a and b are both values, then `or` is a value, rather than
528            // an instruction, so we need to check before setting the flag.
529            // (See also `LLVMBuildNUWNeg` which also needs a check.)
530            if llvm::LLVMIsAInstruction(or).is_some() {
531                llvm::LLVMSetIsDisjoint(or, TRUE);
532            }
533            or
534        }
535    }
536
537    set_math_builder_methods! {
538        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
539        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
540        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
541        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
542        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
543        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
544        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
545        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
546        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
547        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
548    }
549
550    fn checked_binop(
551        &mut self,
552        oop: OverflowOp,
553        ty: Ty<'tcx>,
554        lhs: Self::Value,
555        rhs: Self::Value,
556    ) -> (Self::Value, Self::Value) {
557        let (size, signed) = ty.int_size_and_signed(self.tcx);
558        let width = size.bits();
559
560        if !signed {
561            match oop {
562                OverflowOp::Sub => {
563                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
564                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
565                    // in the backend if profitable.
566                    let sub = self.sub(lhs, rhs);
567                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
568                    return (sub, cmp);
569                }
570                OverflowOp::Add => {
571                    // Like with sub above, using icmp is the preferred form. See
572                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
573                    let add = self.add(lhs, rhs);
574                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
575                    return (add, cmp);
576                }
577                OverflowOp::Mul => {}
578            }
579        }
580
581        let oop_str = match oop {
582            OverflowOp::Add => "add",
583            OverflowOp::Sub => "sub",
584            OverflowOp::Mul => "mul",
585        };
586
587        let name = format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
588
589        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
590        (self.extract_value(res, 0), self.extract_value(res, 1))
591    }
592
593    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
594        if self.cx().val_ty(val) == self.cx().type_i1() {
595            self.zext(val, self.cx().type_i8())
596        } else {
597            val
598        }
599    }
600
601    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
602        if scalar.is_bool() {
603            return self.unchecked_utrunc(val, self.cx().type_i1());
604        }
605        val
606    }
607
608    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
609        let mut bx = Builder::with_cx(self.cx);
610        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
611        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
612        unsafe {
613            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
614            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
615            // Cast to default addrspace if necessary
616            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
617        }
618    }
619
620    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
621        unsafe {
622            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
623            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
624            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
625            load
626        }
627    }
628
629    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
630        unsafe {
631            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
632            llvm::LLVMSetVolatile(load, llvm::TRUE);
633            load
634        }
635    }
636
637    fn atomic_load(
638        &mut self,
639        ty: &'ll Type,
640        ptr: &'ll Value,
641        order: rustc_middle::ty::AtomicOrdering,
642        size: Size,
643    ) -> &'ll Value {
644        unsafe {
645            let load = llvm::LLVMRustBuildAtomicLoad(
646                self.llbuilder,
647                ty,
648                ptr,
649                UNNAMED,
650                AtomicOrdering::from_generic(order),
651            );
652            // LLVM requires the alignment of atomic loads to be at least the size of the type.
653            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
654            load
655        }
656    }
657
658    #[instrument(level = "trace", skip(self))]
659    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
660        if place.layout.is_unsized() {
661            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
662            if matches!(tail.kind(), ty::Foreign(..)) {
663                // Unsized locals and, at least conceptually, even unsized arguments must be copied
664                // around, which requires dynamically determining their size. Therefore, we cannot
665                // allow `extern` types here. Consult t-opsem before removing this check.
666                panic!("unsized locals must not be `extern` types");
667            }
668        }
669        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
670
671        if place.layout.is_zst() {
672            return OperandRef::zero_sized(place.layout);
673        }
674
675        #[instrument(level = "trace", skip(bx))]
676        fn scalar_load_metadata<'a, 'll, 'tcx>(
677            bx: &mut Builder<'a, 'll, 'tcx>,
678            load: &'ll Value,
679            scalar: abi::Scalar,
680            layout: TyAndLayout<'tcx>,
681            offset: Size,
682        ) {
683            if bx.cx.sess().opts.optimize == OptLevel::No {
684                // Don't emit metadata we're not going to use
685                return;
686            }
687
688            if !scalar.is_uninit_valid() {
689                bx.noundef_metadata(load);
690            }
691
692            match scalar.primitive() {
693                abi::Primitive::Int(..) => {
694                    if !scalar.is_always_valid(bx) {
695                        bx.range_metadata(load, scalar.valid_range(bx));
696                    }
697                }
698                abi::Primitive::Pointer(_) => {
699                    if !scalar.valid_range(bx).contains(0) {
700                        bx.nonnull_metadata(load);
701                    }
702
703                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
704                        && let Some(_) = pointee.safe
705                    {
706                        bx.align_metadata(load, pointee.align);
707                    }
708                }
709                abi::Primitive::Float(_) => {}
710            }
711        }
712
713        let val = if let Some(_) = place.val.llextra {
714            // FIXME: Merge with the `else` below?
715            OperandValue::Ref(place.val)
716        } else if place.layout.is_llvm_immediate() {
717            let mut const_llval = None;
718            let llty = place.layout.llvm_type(self);
719            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
720                if llvm::LLVMIsGlobalConstant(global).is_true() {
721                    if let Some(init) = llvm::LLVMGetInitializer(global) {
722                        if self.val_ty(init) == llty {
723                            const_llval = Some(init);
724                        }
725                    }
726                }
727            }
728
729            let llval = const_llval.unwrap_or_else(|| {
730                let load = self.load(llty, place.val.llval, place.val.align);
731                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
732                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
733                    self.to_immediate_scalar(load, scalar)
734                } else {
735                    load
736                }
737            });
738            OperandValue::Immediate(llval)
739        } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
740            let b_offset = a.size(self).align_to(b.align(self).abi);
741
742            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
743                let llptr = if i == 0 {
744                    place.val.llval
745                } else {
746                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
747                };
748                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
749                let load = self.load(llty, llptr, align);
750                scalar_load_metadata(self, load, scalar, layout, offset);
751                self.to_immediate_scalar(load, scalar)
752            };
753
754            OperandValue::Pair(
755                load(0, a, place.layout, place.val.align, Size::ZERO),
756                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
757            )
758        } else {
759            OperandValue::Ref(place.val)
760        };
761
762        OperandRef { val, layout: place.layout }
763    }
764
765    fn write_operand_repeatedly(
766        &mut self,
767        cg_elem: OperandRef<'tcx, &'ll Value>,
768        count: u64,
769        dest: PlaceRef<'tcx, &'ll Value>,
770    ) {
771        let zero = self.const_usize(0);
772        let count = self.const_usize(count);
773
774        let header_bb = self.append_sibling_block("repeat_loop_header");
775        let body_bb = self.append_sibling_block("repeat_loop_body");
776        let next_bb = self.append_sibling_block("repeat_loop_next");
777
778        self.br(header_bb);
779
780        let mut header_bx = Self::build(self.cx, header_bb);
781        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
782
783        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
784        header_bx.cond_br(keep_going, body_bb, next_bb);
785
786        let mut body_bx = Self::build(self.cx, body_bb);
787        let dest_elem = dest.project_index(&mut body_bx, i);
788        cg_elem.val.store(&mut body_bx, dest_elem);
789
790        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
791        body_bx.br(header_bb);
792        header_bx.add_incoming_to_phi(i, next, body_bb);
793
794        *self = Self::build(self.cx, next_bb);
795    }
796
797    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
798        if self.cx.sess().opts.optimize == OptLevel::No {
799            // Don't emit metadata we're not going to use
800            return;
801        }
802
803        unsafe {
804            let llty = self.cx.val_ty(load);
805            let md = [
806                llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
807                llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
808            ];
809            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len());
810            self.set_metadata(load, llvm::MD_range, md);
811        }
812    }
813
814    fn nonnull_metadata(&mut self, load: &'ll Value) {
815        unsafe {
816            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
817            self.set_metadata(load, llvm::MD_nonnull, md);
818        }
819    }
820
821    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
822        self.store_with_flags(val, ptr, align, MemFlags::empty())
823    }
824
825    fn store_with_flags(
826        &mut self,
827        val: &'ll Value,
828        ptr: &'ll Value,
829        align: Align,
830        flags: MemFlags,
831    ) -> &'ll Value {
832        debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
833        assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
834        unsafe {
835            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
836            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
837            let align =
838                if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
839            llvm::LLVMSetAlignment(store, align);
840            if flags.contains(MemFlags::VOLATILE) {
841                llvm::LLVMSetVolatile(store, llvm::TRUE);
842            }
843            if flags.contains(MemFlags::NONTEMPORAL) {
844                // Make sure that the current target architectures supports "sane" non-temporal
845                // stores, i.e., non-temporal stores that are equivalent to regular stores except
846                // for performance. LLVM doesn't seem to care about this, and will happily treat
847                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
848                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
849                // regular stores but require special fences. So we keep a list of architectures
850                // where `!nontemporal` is known to be truly just a hint, and use regular stores
851                // everywhere else. (In the future, we could alternatively ensure that an sfence
852                // gets emitted after a sequence of movnt before any kind of synchronizing
853                // operation. But it's not clear how to do that with LLVM.)
854                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
855                // <https://github.com/llvm/llvm-project/issues/64521>.
856                const WELL_BEHAVED_NONTEMPORAL_ARCHS: &[&str] =
857                    &["aarch64", "arm", "riscv32", "riscv64"];
858
859                let use_nontemporal =
860                    WELL_BEHAVED_NONTEMPORAL_ARCHS.contains(&&*self.cx.tcx.sess.target.arch);
861                if use_nontemporal {
862                    // According to LLVM [1] building a nontemporal store must
863                    // *always* point to a metadata value of the integer 1.
864                    //
865                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
866                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
867                    let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, &one, 1);
868                    self.set_metadata(store, llvm::MD_nontemporal, md);
869                }
870            }
871            store
872        }
873    }
874
875    fn atomic_store(
876        &mut self,
877        val: &'ll Value,
878        ptr: &'ll Value,
879        order: rustc_middle::ty::AtomicOrdering,
880        size: Size,
881    ) {
882        debug!("Store {:?} -> {:?}", val, ptr);
883        assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
884        unsafe {
885            let store = llvm::LLVMRustBuildAtomicStore(
886                self.llbuilder,
887                val,
888                ptr,
889                AtomicOrdering::from_generic(order),
890            );
891            // LLVM requires the alignment of atomic stores to be at least the size of the type.
892            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
893        }
894    }
895
896    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
897        unsafe {
898            llvm::LLVMBuildGEPWithNoWrapFlags(
899                self.llbuilder,
900                ty,
901                ptr,
902                indices.as_ptr(),
903                indices.len() as c_uint,
904                UNNAMED,
905                GEPNoWrapFlags::default(),
906            )
907        }
908    }
909
910    fn inbounds_gep(
911        &mut self,
912        ty: &'ll Type,
913        ptr: &'ll Value,
914        indices: &[&'ll Value],
915    ) -> &'ll Value {
916        unsafe {
917            llvm::LLVMBuildGEPWithNoWrapFlags(
918                self.llbuilder,
919                ty,
920                ptr,
921                indices.as_ptr(),
922                indices.len() as c_uint,
923                UNNAMED,
924                GEPNoWrapFlags::InBounds,
925            )
926        }
927    }
928
929    fn inbounds_nuw_gep(
930        &mut self,
931        ty: &'ll Type,
932        ptr: &'ll Value,
933        indices: &[&'ll Value],
934    ) -> &'ll Value {
935        unsafe {
936            llvm::LLVMBuildGEPWithNoWrapFlags(
937                self.llbuilder,
938                ty,
939                ptr,
940                indices.as_ptr(),
941                indices.len() as c_uint,
942                UNNAMED,
943                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
944            )
945        }
946    }
947
948    /* Casts */
949    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
950        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
951    }
952
953    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
954        debug_assert_ne!(self.val_ty(val), dest_ty);
955
956        let trunc = self.trunc(val, dest_ty);
957        unsafe {
958            if llvm::LLVMIsAInstruction(trunc).is_some() {
959                llvm::LLVMSetNUW(trunc, TRUE);
960            }
961        }
962        trunc
963    }
964
965    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
966        debug_assert_ne!(self.val_ty(val), dest_ty);
967
968        let trunc = self.trunc(val, dest_ty);
969        unsafe {
970            if llvm::LLVMIsAInstruction(trunc).is_some() {
971                llvm::LLVMSetNSW(trunc, TRUE);
972            }
973        }
974        trunc
975    }
976
977    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
978        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
979    }
980
981    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
982        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
983    }
984
985    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
986        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
987    }
988
989    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
990        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
991        // poor codegen. The reason for this is that the corresponding wasm
992        // instructions, `i32.trunc_f32_s` for example, will trap when the float
993        // is out-of-bounds, infinity, or nan. This means that LLVM
994        // automatically inserts control flow around `fptoui` and `fptosi`
995        // because the LLVM instruction `fptoui` is defined as producing a
996        // poison value, not having UB on out-of-bounds values.
997        //
998        // This method, however, is only used with non-saturating casts that
999        // have UB on out-of-bounds values. This means that it's ok if we use
1000        // the raw wasm instruction since out-of-bounds values can do whatever
1001        // we like. To ensure that LLVM picks the right instruction we choose
1002        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1003        // other control flow automatically.
1004        if self.sess().target.is_like_wasm {
1005            let src_ty = self.cx.val_ty(val);
1006            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1007                let float_width = self.cx.float_width(src_ty);
1008                let int_width = self.cx.int_width(dest_ty);
1009                if matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1010                    return self.call_intrinsic(
1011                        "llvm.wasm.trunc.unsigned",
1012                        &[dest_ty, src_ty],
1013                        &[val],
1014                    );
1015                }
1016            }
1017        }
1018        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1019    }
1020
1021    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1022        // see `fptoui` above for why wasm is different here
1023        if self.sess().target.is_like_wasm {
1024            let src_ty = self.cx.val_ty(val);
1025            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1026                let float_width = self.cx.float_width(src_ty);
1027                let int_width = self.cx.int_width(dest_ty);
1028                if matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1029                    return self.call_intrinsic(
1030                        "llvm.wasm.trunc.signed",
1031                        &[dest_ty, src_ty],
1032                        &[val],
1033                    );
1034                }
1035            }
1036        }
1037        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1038    }
1039
1040    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1041        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1042    }
1043
1044    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1045        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1046    }
1047
1048    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1049        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1050    }
1051
1052    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1053        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1054    }
1055
1056    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1057        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1058    }
1059
1060    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1061        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1062    }
1063
1064    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1065        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1066    }
1067
1068    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1069        unsafe {
1070            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1071        }
1072    }
1073
1074    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1075        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1076    }
1077
1078    /* Comparisons */
1079    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1080        let op = llvm::IntPredicate::from_generic(op);
1081        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1082    }
1083
1084    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1085        let op = llvm::RealPredicate::from_generic(op);
1086        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1087    }
1088
1089    fn three_way_compare(
1090        &mut self,
1091        ty: Ty<'tcx>,
1092        lhs: Self::Value,
1093        rhs: Self::Value,
1094    ) -> Self::Value {
1095        let size = ty.primitive_size(self.tcx);
1096        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1097
1098        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1099    }
1100
1101    /* Miscellaneous instructions */
1102    fn memcpy(
1103        &mut self,
1104        dst: &'ll Value,
1105        dst_align: Align,
1106        src: &'ll Value,
1107        src_align: Align,
1108        size: &'ll Value,
1109        flags: MemFlags,
1110    ) {
1111        assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1112        let size = self.intcast(size, self.type_isize(), false);
1113        let is_volatile = flags.contains(MemFlags::VOLATILE);
1114        unsafe {
1115            llvm::LLVMRustBuildMemCpy(
1116                self.llbuilder,
1117                dst,
1118                dst_align.bytes() as c_uint,
1119                src,
1120                src_align.bytes() as c_uint,
1121                size,
1122                is_volatile,
1123            );
1124        }
1125    }
1126
1127    fn memmove(
1128        &mut self,
1129        dst: &'ll Value,
1130        dst_align: Align,
1131        src: &'ll Value,
1132        src_align: Align,
1133        size: &'ll Value,
1134        flags: MemFlags,
1135    ) {
1136        assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1137        let size = self.intcast(size, self.type_isize(), false);
1138        let is_volatile = flags.contains(MemFlags::VOLATILE);
1139        unsafe {
1140            llvm::LLVMRustBuildMemMove(
1141                self.llbuilder,
1142                dst,
1143                dst_align.bytes() as c_uint,
1144                src,
1145                src_align.bytes() as c_uint,
1146                size,
1147                is_volatile,
1148            );
1149        }
1150    }
1151
1152    fn memset(
1153        &mut self,
1154        ptr: &'ll Value,
1155        fill_byte: &'ll Value,
1156        size: &'ll Value,
1157        align: Align,
1158        flags: MemFlags,
1159    ) {
1160        assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1161        let is_volatile = flags.contains(MemFlags::VOLATILE);
1162        unsafe {
1163            llvm::LLVMRustBuildMemSet(
1164                self.llbuilder,
1165                ptr,
1166                align.bytes() as c_uint,
1167                fill_byte,
1168                size,
1169                is_volatile,
1170            );
1171        }
1172    }
1173
1174    fn select(
1175        &mut self,
1176        cond: &'ll Value,
1177        then_val: &'ll Value,
1178        else_val: &'ll Value,
1179    ) -> &'ll Value {
1180        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1181    }
1182
1183    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1184        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1185    }
1186
1187    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1188        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1189    }
1190
1191    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1192        unsafe {
1193            let elt_ty = self.cx.val_ty(elt);
1194            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1195            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1196            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1197            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1198        }
1199    }
1200
1201    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1202        assert_eq!(idx as c_uint as u64, idx);
1203        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1204    }
1205
1206    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1207        assert_eq!(idx as c_uint as u64, idx);
1208        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1209    }
1210
1211    fn set_personality_fn(&mut self, personality: &'ll Value) {
1212        unsafe {
1213            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1214        }
1215    }
1216
1217    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1218        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1219        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1220        unsafe {
1221            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1222        }
1223        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1224    }
1225
1226    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1227        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1228        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1229        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1230    }
1231
1232    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1233        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1234        let mut exn = self.const_poison(ty);
1235        exn = self.insert_value(exn, exn0, 0);
1236        exn = self.insert_value(exn, exn1, 1);
1237        unsafe {
1238            llvm::LLVMBuildResume(self.llbuilder, exn);
1239        }
1240    }
1241
1242    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1243        let ret = unsafe {
1244            llvm::LLVMBuildCleanupPad(
1245                self.llbuilder,
1246                parent,
1247                args.as_ptr(),
1248                args.len() as c_uint,
1249                c"cleanuppad".as_ptr(),
1250            )
1251        };
1252        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1253    }
1254
1255    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1256        unsafe {
1257            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1258                .expect("LLVM does not have support for cleanupret");
1259        }
1260    }
1261
1262    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1263        let ret = unsafe {
1264            llvm::LLVMBuildCatchPad(
1265                self.llbuilder,
1266                parent,
1267                args.as_ptr(),
1268                args.len() as c_uint,
1269                c"catchpad".as_ptr(),
1270            )
1271        };
1272        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1273    }
1274
1275    fn catch_switch(
1276        &mut self,
1277        parent: Option<&'ll Value>,
1278        unwind: Option<&'ll BasicBlock>,
1279        handlers: &[&'ll BasicBlock],
1280    ) -> &'ll Value {
1281        let ret = unsafe {
1282            llvm::LLVMBuildCatchSwitch(
1283                self.llbuilder,
1284                parent,
1285                unwind,
1286                handlers.len() as c_uint,
1287                c"catchswitch".as_ptr(),
1288            )
1289        };
1290        let ret = ret.expect("LLVM does not have support for catchswitch");
1291        for handler in handlers {
1292            unsafe {
1293                llvm::LLVMAddHandler(ret, handler);
1294            }
1295        }
1296        ret
1297    }
1298
1299    // Atomic Operations
1300    fn atomic_cmpxchg(
1301        &mut self,
1302        dst: &'ll Value,
1303        cmp: &'ll Value,
1304        src: &'ll Value,
1305        order: rustc_middle::ty::AtomicOrdering,
1306        failure_order: rustc_middle::ty::AtomicOrdering,
1307        weak: bool,
1308    ) -> (&'ll Value, &'ll Value) {
1309        unsafe {
1310            let value = llvm::LLVMBuildAtomicCmpXchg(
1311                self.llbuilder,
1312                dst,
1313                cmp,
1314                src,
1315                AtomicOrdering::from_generic(order),
1316                AtomicOrdering::from_generic(failure_order),
1317                llvm::FALSE, // SingleThreaded
1318            );
1319            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1320            let val = self.extract_value(value, 0);
1321            let success = self.extract_value(value, 1);
1322            (val, success)
1323        }
1324    }
1325
1326    fn atomic_rmw(
1327        &mut self,
1328        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1329        dst: &'ll Value,
1330        src: &'ll Value,
1331        order: rustc_middle::ty::AtomicOrdering,
1332        ret_ptr: bool,
1333    ) -> &'ll Value {
1334        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1335        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1336        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1337        let mut res = unsafe {
1338            llvm::LLVMBuildAtomicRMW(
1339                self.llbuilder,
1340                AtomicRmwBinOp::from_generic(op),
1341                dst,
1342                src,
1343                AtomicOrdering::from_generic(order),
1344                llvm::FALSE, // SingleThreaded
1345            )
1346        };
1347        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1348            res = self.inttoptr(res, self.type_ptr());
1349        }
1350        res
1351    }
1352
1353    fn atomic_fence(
1354        &mut self,
1355        order: rustc_middle::ty::AtomicOrdering,
1356        scope: SynchronizationScope,
1357    ) {
1358        let single_threaded = match scope {
1359            SynchronizationScope::SingleThread => true,
1360            SynchronizationScope::CrossThread => false,
1361        };
1362        unsafe {
1363            llvm::LLVMBuildFence(
1364                self.llbuilder,
1365                AtomicOrdering::from_generic(order),
1366                single_threaded.to_llvm_bool(),
1367                UNNAMED,
1368            );
1369        }
1370    }
1371
1372    fn set_invariant_load(&mut self, load: &'ll Value) {
1373        unsafe {
1374            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1375            self.set_metadata(load, llvm::MD_invariant_load, md);
1376        }
1377    }
1378
1379    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1380        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1381    }
1382
1383    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1384        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1385    }
1386
1387    fn call(
1388        &mut self,
1389        llty: &'ll Type,
1390        fn_call_attrs: Option<&CodegenFnAttrs>,
1391        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1392        llfn: &'ll Value,
1393        args: &[&'ll Value],
1394        funclet: Option<&Funclet<'ll>>,
1395        instance: Option<Instance<'tcx>>,
1396    ) -> &'ll Value {
1397        debug!("call {:?} with args ({:?})", llfn, args);
1398
1399        let args = self.check_call("call", llty, llfn, args);
1400        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1401        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1402        if let Some(funclet_bundle) = funclet_bundle {
1403            bundles.push(funclet_bundle);
1404        }
1405
1406        // Emit CFI pointer type membership test
1407        self.cfi_type_test(fn_call_attrs, fn_abi, instance, llfn);
1408
1409        // Emit KCFI operand bundle
1410        let kcfi_bundle = self.kcfi_operand_bundle(fn_call_attrs, fn_abi, instance, llfn);
1411        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1412            bundles.push(kcfi_bundle);
1413        }
1414
1415        let call = unsafe {
1416            llvm::LLVMBuildCallWithOperandBundles(
1417                self.llbuilder,
1418                llty,
1419                llfn,
1420                args.as_ptr() as *const &llvm::Value,
1421                args.len() as c_uint,
1422                bundles.as_ptr(),
1423                bundles.len() as c_uint,
1424                c"".as_ptr(),
1425            )
1426        };
1427
1428        if let Some(instance) = instance {
1429            // Attributes on the function definition being called
1430            let fn_defn_attrs = self.cx.tcx.codegen_fn_attrs(instance.def_id());
1431            if let Some(fn_call_attrs) = fn_call_attrs
1432                && !fn_call_attrs.target_features.is_empty()
1433                // If there is an inline attribute and a target feature that matches
1434                // we will add the attribute to the callsite otherwise we'll omit
1435                // this and not add the attribute to prevent soundness issues.
1436                && let Some(inlining_rule) = attributes::inline_attr(&self.cx, instance)
1437                && self.cx.tcx.is_target_feature_call_safe(
1438                    &fn_call_attrs.target_features,
1439                    &fn_defn_attrs.target_features,
1440                )
1441            {
1442                attributes::apply_to_callsite(
1443                    call,
1444                    llvm::AttributePlace::Function,
1445                    &[inlining_rule],
1446                );
1447            }
1448        }
1449
1450        if let Some(fn_abi) = fn_abi {
1451            fn_abi.apply_attrs_callsite(self, call);
1452        }
1453        call
1454    }
1455
1456    fn tail_call(
1457        &mut self,
1458        llty: Self::Type,
1459        fn_attrs: Option<&CodegenFnAttrs>,
1460        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1461        llfn: Self::Value,
1462        args: &[Self::Value],
1463        funclet: Option<&Self::Funclet>,
1464        instance: Option<Instance<'tcx>>,
1465    ) {
1466        let call = self.call(llty, fn_attrs, Some(fn_abi), llfn, args, funclet, instance);
1467        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1468
1469        match &fn_abi.ret.mode {
1470            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1471            PassMode::Direct(_) | PassMode::Pair { .. } => self.ret(call),
1472            mode @ PassMode::Cast { .. } => {
1473                bug!("Encountered `PassMode::{mode:?}` during codegen")
1474            }
1475        }
1476    }
1477
1478    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1479        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1480    }
1481
1482    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1483        // Cleanup is always the cold path.
1484        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1485        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1486    }
1487}
1488
1489impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1490    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1491        // Forward to the `get_static` method of `CodegenCx`
1492        let global = self.cx().get_static(def_id);
1493        if self.cx().tcx.is_thread_local_static(def_id) {
1494            let pointer =
1495                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1496            // Cast to default address space if globals are in a different addrspace
1497            self.pointercast(pointer, self.type_ptr())
1498        } else {
1499            // Cast to default address space if globals are in a different addrspace
1500            self.cx().const_pointercast(global, self.type_ptr())
1501        }
1502    }
1503}
1504
1505impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1506    pub(crate) fn llfn(&self) -> &'ll Value {
1507        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1508    }
1509}
1510
1511impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1512    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1513        unsafe {
1514            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1515        }
1516    }
1517}
1518impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1519    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1520        unsafe {
1521            let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1522            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len());
1523            self.set_metadata(load, llvm::MD_align, md);
1524        }
1525    }
1526
1527    fn noundef_metadata(&mut self, load: &'ll Value) {
1528        unsafe {
1529            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1530            self.set_metadata(load, llvm::MD_noundef, md);
1531        }
1532    }
1533
1534    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1535        unsafe {
1536            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1537            self.set_metadata(inst, llvm::MD_unpredictable, md);
1538        }
1539    }
1540}
1541impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1542    pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1543        unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1544    }
1545
1546    pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1547        unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1548    }
1549
1550    pub(crate) fn insert_element(
1551        &mut self,
1552        vec: &'ll Value,
1553        elt: &'ll Value,
1554        idx: &'ll Value,
1555    ) -> &'ll Value {
1556        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1557    }
1558
1559    pub(crate) fn shuffle_vector(
1560        &mut self,
1561        v1: &'ll Value,
1562        v2: &'ll Value,
1563        mask: &'ll Value,
1564    ) -> &'ll Value {
1565        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1566    }
1567
1568    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1569        unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1570    }
1571    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1572        unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1573    }
1574    pub(crate) fn vector_reduce_fadd_reassoc(
1575        &mut self,
1576        acc: &'ll Value,
1577        src: &'ll Value,
1578    ) -> &'ll Value {
1579        unsafe {
1580            let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1581            llvm::LLVMRustSetAllowReassoc(instr);
1582            instr
1583        }
1584    }
1585    pub(crate) fn vector_reduce_fmul_reassoc(
1586        &mut self,
1587        acc: &'ll Value,
1588        src: &'ll Value,
1589    ) -> &'ll Value {
1590        unsafe {
1591            let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1592            llvm::LLVMRustSetAllowReassoc(instr);
1593            instr
1594        }
1595    }
1596    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1597        unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1598    }
1599    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1600        unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1601    }
1602    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1603        unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1604    }
1605    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1606        unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1607    }
1608    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1609        unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1610    }
1611    pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1612        unsafe {
1613            llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
1614        }
1615    }
1616    pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1617        unsafe {
1618            llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
1619        }
1620    }
1621    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1622        unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1623    }
1624    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1625        unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1626    }
1627
1628    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1629        unsafe {
1630            llvm::LLVMAddClause(landing_pad, clause);
1631        }
1632    }
1633
1634    pub(crate) fn catch_ret(
1635        &mut self,
1636        funclet: &Funclet<'ll>,
1637        unwind: &'ll BasicBlock,
1638    ) -> &'ll Value {
1639        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1640        ret.expect("LLVM does not have support for catchret")
1641    }
1642
1643    fn check_call<'b>(
1644        &mut self,
1645        typ: &str,
1646        fn_ty: &'ll Type,
1647        llfn: &'ll Value,
1648        args: &'b [&'ll Value],
1649    ) -> Cow<'b, [&'ll Value]> {
1650        assert!(
1651            self.cx.type_kind(fn_ty) == TypeKind::Function,
1652            "builder::{typ} not passed a function, but {fn_ty:?}"
1653        );
1654
1655        let param_tys = self.cx.func_params_types(fn_ty);
1656
1657        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1658            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1659
1660        if all_args_match {
1661            return Cow::Borrowed(args);
1662        }
1663
1664        let casted_args: Vec<_> = iter::zip(param_tys, args)
1665            .enumerate()
1666            .map(|(i, (expected_ty, &actual_val))| {
1667                let actual_ty = self.cx.val_ty(actual_val);
1668                if expected_ty != actual_ty {
1669                    debug!(
1670                        "type mismatch in function call of {:?}. \
1671                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1672                        llfn, expected_ty, i, actual_ty
1673                    );
1674                    self.bitcast(actual_val, expected_ty)
1675                } else {
1676                    actual_val
1677                }
1678            })
1679            .collect();
1680
1681        Cow::Owned(casted_args)
1682    }
1683
1684    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1685        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1686    }
1687}
1688
1689impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1690    pub(crate) fn call_intrinsic(
1691        &mut self,
1692        base_name: impl Into<Cow<'static, str>>,
1693        type_params: &[&'ll Type],
1694        args: &[&'ll Value],
1695    ) -> &'ll Value {
1696        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1697        self.call(ty, None, None, f, args, None, None)
1698    }
1699
1700    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1701        let size = size.bytes();
1702        if size == 0 {
1703            return;
1704        }
1705
1706        if !self.cx().sess().emit_lifetime_markers() {
1707            return;
1708        }
1709
1710        if crate::llvm_util::get_version() >= (22, 0, 0) {
1711            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1712        } else {
1713            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1714        }
1715    }
1716}
1717impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1718    pub(crate) fn phi(
1719        &mut self,
1720        ty: &'ll Type,
1721        vals: &[&'ll Value],
1722        bbs: &[&'ll BasicBlock],
1723    ) -> &'ll Value {
1724        assert_eq!(vals.len(), bbs.len());
1725        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1726        unsafe {
1727            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1728            phi
1729        }
1730    }
1731
1732    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1733        unsafe {
1734            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1735        }
1736    }
1737}
1738impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1739    pub(crate) fn landing_pad(
1740        &mut self,
1741        ty: &'ll Type,
1742        pers_fn: &'ll Value,
1743        num_clauses: usize,
1744    ) -> &'ll Value {
1745        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1746        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1747        // personality lives on the parent function anyway.
1748        self.set_personality_fn(pers_fn);
1749        unsafe {
1750            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1751        }
1752    }
1753
1754    pub(crate) fn callbr(
1755        &mut self,
1756        llty: &'ll Type,
1757        fn_attrs: Option<&CodegenFnAttrs>,
1758        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1759        llfn: &'ll Value,
1760        args: &[&'ll Value],
1761        default_dest: &'ll BasicBlock,
1762        indirect_dest: &[&'ll BasicBlock],
1763        funclet: Option<&Funclet<'ll>>,
1764        instance: Option<Instance<'tcx>>,
1765    ) -> &'ll Value {
1766        debug!("invoke {:?} with args ({:?})", llfn, args);
1767
1768        let args = self.check_call("callbr", llty, llfn, args);
1769        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1770        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1771        if let Some(funclet_bundle) = funclet_bundle {
1772            bundles.push(funclet_bundle);
1773        }
1774
1775        // Emit CFI pointer type membership test
1776        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1777
1778        // Emit KCFI operand bundle
1779        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1780        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1781            bundles.push(kcfi_bundle);
1782        }
1783
1784        let callbr = unsafe {
1785            llvm::LLVMBuildCallBr(
1786                self.llbuilder,
1787                llty,
1788                llfn,
1789                default_dest,
1790                indirect_dest.as_ptr(),
1791                indirect_dest.len() as c_uint,
1792                args.as_ptr(),
1793                args.len() as c_uint,
1794                bundles.as_ptr(),
1795                bundles.len() as c_uint,
1796                UNNAMED,
1797            )
1798        };
1799        if let Some(fn_abi) = fn_abi {
1800            fn_abi.apply_attrs_callsite(self, callbr);
1801        }
1802        callbr
1803    }
1804
1805    // Emits CFI pointer type membership tests.
1806    fn cfi_type_test(
1807        &mut self,
1808        fn_attrs: Option<&CodegenFnAttrs>,
1809        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1810        instance: Option<Instance<'tcx>>,
1811        llfn: &'ll Value,
1812    ) {
1813        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1814        if self.tcx.sess.is_sanitizer_cfi_enabled()
1815            && let Some(fn_abi) = fn_abi
1816            && is_indirect_call
1817        {
1818            if let Some(fn_attrs) = fn_attrs
1819                && fn_attrs.no_sanitize.contains(SanitizerSet::CFI)
1820            {
1821                return;
1822            }
1823
1824            let mut options = cfi::TypeIdOptions::empty();
1825            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1826                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1827            }
1828            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1829                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1830            }
1831
1832            let typeid = if let Some(instance) = instance {
1833                cfi::typeid_for_instance(self.tcx, instance, options)
1834            } else {
1835                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1836            };
1837            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1838            let dbg_loc = self.get_dbg_loc();
1839
1840            // Test whether the function pointer is associated with the type identifier using the
1841            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
1842            // calls to this intrinsic with code to test type membership.
1843            let typeid = self.get_metadata_value(typeid_metadata);
1844            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1845            let bb_pass = self.append_sibling_block("type_test.pass");
1846            let bb_fail = self.append_sibling_block("type_test.fail");
1847            self.cond_br(cond, bb_pass, bb_fail);
1848
1849            self.switch_to_block(bb_fail);
1850            if let Some(dbg_loc) = dbg_loc {
1851                self.set_dbg_loc(dbg_loc);
1852            }
1853            self.abort();
1854            self.unreachable();
1855
1856            self.switch_to_block(bb_pass);
1857            if let Some(dbg_loc) = dbg_loc {
1858                self.set_dbg_loc(dbg_loc);
1859            }
1860        }
1861    }
1862
1863    // Emits KCFI operand bundles.
1864    fn kcfi_operand_bundle(
1865        &mut self,
1866        fn_attrs: Option<&CodegenFnAttrs>,
1867        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1868        instance: Option<Instance<'tcx>>,
1869        llfn: &'ll Value,
1870    ) -> Option<llvm::OperandBundleBox<'ll>> {
1871        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1872        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1873            && let Some(fn_abi) = fn_abi
1874            && is_indirect_call
1875        {
1876            if let Some(fn_attrs) = fn_attrs
1877                && fn_attrs.no_sanitize.contains(SanitizerSet::KCFI)
1878            {
1879                return None;
1880            }
1881
1882            let mut options = kcfi::TypeIdOptions::empty();
1883            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1884                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
1885            }
1886            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1887                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
1888            }
1889
1890            let kcfi_typeid = if let Some(instance) = instance {
1891                kcfi::typeid_for_instance(self.tcx, instance, options)
1892            } else {
1893                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1894            };
1895
1896            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
1897        } else {
1898            None
1899        };
1900        kcfi_bundle
1901    }
1902
1903    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
1904    #[instrument(level = "debug", skip(self))]
1905    pub(crate) fn instrprof_increment(
1906        &mut self,
1907        fn_name: &'ll Value,
1908        hash: &'ll Value,
1909        num_counters: &'ll Value,
1910        index: &'ll Value,
1911    ) {
1912        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
1913    }
1914}