Skip to main content

rustc_codegen_llvm/
va_arg.rs

1use rustc_abi::{
2    Align, BackendRepr, CVariadicStatus, Endian, Float, HasDataLayout, Integer, Primitive, Size,
3};
4use rustc_codegen_ssa::common::IntPredicate;
5use rustc_codegen_ssa::mir::operand::OperandRef;
6use rustc_codegen_ssa::traits::{
7    BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, LayoutTypeCodegenMethods,
8};
9use rustc_middle::ty::Ty;
10use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
11use rustc_span::bug;
12use rustc_target::spec::{Arch, Env, LlvmAbi, RustcAbi, Target};
13
14use crate::builder::Builder;
15use crate::llvm::{Type, Value};
16
17fn round_up_to_alignment<'ll>(
18    bx: &mut Builder<'_, 'll, '_>,
19    mut value: Value<'ll>,
20    align: Align,
21) -> Value<'ll> {
22    value = bx.add(value, bx.cx().const_i32(align.bytes() as i32 - 1));
23    bx.and(value, bx.cx().const_i32(-(align.bytes() as i32)))
24}
25
26fn round_pointer_up_to_alignment<'ll>(
27    bx: &mut Builder<'_, 'll, '_>,
28    addr: Value<'ll>,
29    align: Align,
30) -> Value<'ll> {
31    let ptr = bx.inbounds_ptradd(addr, bx.const_i32(align.bytes() as i32 - 1));
32    let pointer_width = bx.tcx().sess.target.pointer_width;
33    let mask = align.bytes().wrapping_neg() & (u64::MAX >> (64 - pointer_width));
34    bx.call_intrinsic(
35        "llvm.ptrmask",
36        &[bx.type_ptr(), bx.type_isize()],
37        &[ptr, bx.const_usize(mask)],
38    )
39}
40
41/// A helper for backend_type that ensures we don't call it on non-primitive types.
42///
43/// Doing so is risky because LLVM and rustc's idea of how big or aligned the type
44/// is might be different.
45fn to_backend_type<'ll, 'tcx>(
46    bx: &Builder<'_, 'll, 'tcx>,
47    ty_and_layout: TyAndLayout<'tcx>,
48) -> Type<'ll> {
49    if ty_and_layout.is_x87_f80(bx.cx) {
50        bx.type_x87_f80()
51    } else {
52        if !ty_and_layout.backend_repr.is_scalar() {
    ::core::panicking::panic("assertion failed: ty_and_layout.backend_repr.is_scalar()")
};assert!(ty_and_layout.backend_repr.is_scalar());
53        bx.backend_type(ty_and_layout)
54    }
55}
56
57fn emit_direct_ptr_va_arg<'ll, 'tcx>(
58    bx: &mut Builder<'_, 'll, 'tcx>,
59    list: OperandRef<'tcx, Value<'ll>>,
60    size: Size,
61    align: Align,
62    slot_size: Align,
63    allow_higher_align: bool,
64    force_right_adjust: bool,
65) -> (Value<'ll>, Align) {
66    let va_list_ty = bx.type_ptr();
67    let va_list_addr = list.immediate();
68
69    let ptr_align_abi = bx.tcx().data_layout.pointer_align();
70    let ptr = bx.load(va_list_ty, va_list_addr, ptr_align_abi);
71
72    let (addr, addr_align) = if allow_higher_align && align > slot_size {
73        (round_pointer_up_to_alignment(bx, ptr, align), align)
74    } else {
75        (ptr, slot_size)
76    };
77
78    let aligned_size = size.align_to(slot_size).bytes() as i32;
79    let full_direct_size = bx.cx().const_i32(aligned_size);
80    let next = bx.inbounds_ptradd(addr, full_direct_size);
81    bx.store(next, va_list_addr, ptr_align_abi);
82
83    if size.bytes() < slot_size.bytes()
84        && bx.tcx().sess.target.endian == Endian::Big
85        && force_right_adjust
86    {
87        let adjusted_size = bx.cx().const_i32((slot_size.bytes() - size.bytes()) as i32);
88        let adjusted = bx.inbounds_ptradd(addr, adjusted_size);
89        // We're in the middle of a slot now, so use the type's alignment, not the slot's.
90        (adjusted, align)
91    } else {
92        (addr, addr_align)
93    }
94}
95
96/// Some backends apply special alignment rules to c-variadic arguments.
97fn get_param_type_alignment<'ll, 'tcx>(
98    bx: &mut Builder<'_, 'll, 'tcx>,
99    layout: TyAndLayout<'tcx>,
100) -> Align {
101    if layout.is_x87_f80(bx) {
102        return layout.align;
103    }
104
105    let BackendRepr::Scalar(scalar) = layout.backend_repr else {
106        ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected backend repr {0:?}", layout.backend_repr),
    Location::caller());bug!("unexpected backend repr {:?}", layout.backend_repr);
107    };
108
109    match bx.cx.tcx.sess.target.arch {
110        Arch::PowerPC | Arch::PowerPC64 => match scalar.primitive() {
111            Primitive::Bool => ::core::panicking::unreachable_default_msg()unreachable!(),
112            Primitive::Int(integer, _) => match integer {
113                Integer::I8 | Integer::I16 => ::core::panicking::unreachable_default_msg()unreachable!(),
114                Integer::I32 | Integer::I64 => { /* fall through */ }
115                Integer::I128 => return Align::EIGHT,
116            },
117            Primitive::Float(float) => match float {
118                Float::F16 | Float::F16B | Float::F32 | Float::X87F80 => ::core::panicking::unreachable_default_msg()unreachable!(),
119                Float::F64 | Float::F128 => { /* fall through */ }
120                Float::PpcF128 => {
121                    return if is_powerpc_softfloat_abi(&bx.cx.tcx.sess.target) {
122                        Align::FOUR
123                    } else {
124                        Align::EIGHT
125                    };
126                }
127            },
128            Primitive::Pointer(_) => { /* fall through */ }
129        },
130        _ => { /* fall through */ }
131    }
132
133    layout.align
134}
135
136enum PassMode {
137    Direct,
138    Indirect,
139}
140
141enum SlotSize {
142    Bytes8 = 8,
143    Bytes4 = 4,
144    Bytes1 = 1,
145}
146
147/// Whether to respect a value alignment that is higher than the slot alignment.
148///
149/// When `No` the argument is in the next slot, when `Yes` there will be empty slots
150/// until a slot's starting address has the required alignment.
151enum AllowHigherAlign {
152    No,
153    Yes,
154}
155
156/// Determines where in the slot the value is located. Only takes effect on big-endian targets.
157///
158/// with 8-byte slots, a 32-bit integer is either stored right-adjusted:
159///
160/// ```text
161/// [0x0, 0x0, 0x0, 0x0, 0xaa, 0xaa, 0xaa, 0xaa]
162/// ```
163///
164/// or left-adjusted:
165///
166/// ```text
167/// [0xaa, 0xaa, 0xaa, 0xaa, 0x0, 0x0, 0x0, 0x0]
168/// ```
169///
170/// Most big-endian targets store values as right-adjusted.
171enum ForceRightAdjust {
172    No,
173    Yes,
174}
175
176fn emit_ptr_va_arg<'ll, 'tcx>(
177    bx: &mut Builder<'_, 'll, 'tcx>,
178    list: OperandRef<'tcx, Value<'ll>>,
179    layout: TyAndLayout<'tcx>,
180    pass_mode: PassMode,
181    slot_size: SlotSize,
182    allow_higher_align: AllowHigherAlign,
183    force_right_adjust: ForceRightAdjust,
184) -> Value<'ll> {
185    let indirect = #[allow(non_exhaustive_omitted_patterns)] match pass_mode {
    PassMode::Indirect => true,
    _ => false,
}matches!(pass_mode, PassMode::Indirect);
186    let allow_higher_align = #[allow(non_exhaustive_omitted_patterns)] match allow_higher_align {
    AllowHigherAlign::Yes => true,
    _ => false,
}matches!(allow_higher_align, AllowHigherAlign::Yes);
187    let force_right_adjust = #[allow(non_exhaustive_omitted_patterns)] match force_right_adjust {
    ForceRightAdjust::Yes => true,
    _ => false,
}matches!(force_right_adjust, ForceRightAdjust::Yes);
188    let slot_size = Align::from_bytes(slot_size as u64).unwrap();
189
190    let (llty, size, align) = if indirect {
191        (
192            to_backend_type(bx, bx.cx.layout_of(Ty::new_imm_ptr(bx.cx.tcx, layout.ty))),
193            bx.cx.data_layout().pointer_size(),
194            bx.cx.data_layout().pointer_align(),
195        )
196    } else {
197        (to_backend_type(bx, layout), layout.size, get_param_type_alignment(bx, layout))
198    };
199    let (addr, addr_align) = emit_direct_ptr_va_arg(
200        bx,
201        list,
202        size,
203        align,
204        slot_size,
205        allow_higher_align,
206        force_right_adjust,
207    );
208    if indirect {
209        let tmp_ret = bx.load(llty, addr, addr_align);
210        bx.load(to_backend_type(bx, layout), tmp_ret, align)
211    } else {
212        bx.load(llty, addr, addr_align)
213    }
214}
215
216fn emit_aapcs_va_arg<'ll, 'tcx>(
217    bx: &mut Builder<'_, 'll, 'tcx>,
218    list: OperandRef<'tcx, Value<'ll>>,
219    layout: TyAndLayout<'tcx>,
220) -> Value<'ll> {
221    let dl = bx.cx.data_layout();
222
223    // Implementation of the AAPCS64 calling convention for va_args see
224    // https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst
225    //
226    // typedef struct  va_list {
227    //     void * stack; // next stack param
228    //     void * gr_top; // end of GP arg reg save area
229    //     void * vr_top; // end of FP/SIMD arg reg save area
230    //     int gr_offs; // offset from  gr_top to next GP register arg
231    //     int vr_offs; // offset from  vr_top to next FP/SIMD register arg
232    // } va_list;
233    let va_list_addr = list.immediate();
234
235    // There is no padding between fields since `void*` is size=8 align=8, `int` is size=4 align=4.
236    // See https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst
237    // Table 1, Byte size and byte alignment of fundamental data types
238    // Table 3, Mapping of C & C++ built-in data types
239    let ptr_offset = 8;
240    let i32_offset = 4;
241    let gr_top = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(ptr_offset));
242    let vr_top = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * ptr_offset));
243    let gr_offs = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(3 * ptr_offset));
244    let vr_offs = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(3 * ptr_offset + i32_offset));
245
246    let maybe_reg = bx.append_sibling_block("va_arg.maybe_reg");
247    let in_reg = bx.append_sibling_block("va_arg.in_reg");
248    let on_stack = bx.append_sibling_block("va_arg.on_stack");
249    let end = bx.append_sibling_block("va_arg.end");
250    let zero = bx.const_i32(0);
251    let offset_align = Align::FOUR;
252
253    let gr_type = layout.ty.is_any_ptr() || layout.ty.is_integral();
254    let (reg_off, reg_top, slot_size) = if gr_type {
255        let nreg = layout.size.bytes().div_ceil(8);
256        (gr_offs, gr_top, nreg * 8)
257    } else {
258        let nreg = layout.size.bytes().div_ceil(16);
259        (vr_offs, vr_top, nreg * 16)
260    };
261
262    // if the offset >= 0 then the value will be on the stack
263    let mut reg_off_v = bx.load(bx.type_i32(), reg_off, offset_align);
264    let use_stack = bx.icmp(IntPredicate::IntSGE, reg_off_v, zero);
265    bx.cond_br(use_stack, on_stack, maybe_reg);
266
267    // The value at this point might be in a register, but there is a chance that
268    // it could be on the stack so we have to update the offset and then check
269    // the offset again.
270
271    bx.switch_to_block(maybe_reg);
272    if gr_type && layout.align.bytes() > 8 {
273        reg_off_v = bx.add(reg_off_v, bx.const_i32(15));
274        reg_off_v = bx.and(reg_off_v, bx.const_i32(-16));
275    }
276    let new_reg_off_v = bx.add(reg_off_v, bx.const_i32(slot_size as i32));
277
278    bx.store(new_reg_off_v, reg_off, offset_align);
279
280    // Check to see if we have overflowed the registers as a result of this.
281    // If we have then we need to use the stack for this value
282    let use_stack = bx.icmp(IntPredicate::IntSGT, new_reg_off_v, zero);
283    bx.cond_br(use_stack, on_stack, in_reg);
284
285    bx.switch_to_block(in_reg);
286    let top_type = bx.type_ptr();
287    let top = bx.load(top_type, reg_top, dl.pointer_align());
288
289    // reg_value = *(@top + reg_off_v);
290    let mut reg_addr = bx.ptradd(top, reg_off_v);
291    if bx.tcx().sess.target.endian == Endian::Big && layout.size.bytes() != slot_size {
292        // On big-endian systems the value is right-aligned in its slot.
293        let offset = bx.const_i32((slot_size - layout.size.bytes()) as i32);
294        reg_addr = bx.ptradd(reg_addr, offset);
295    }
296    let reg_type = to_backend_type(bx, layout);
297    let reg_value = bx.load(reg_type, reg_addr, layout.align);
298    bx.br(end);
299
300    // On Stack block
301    bx.switch_to_block(on_stack);
302    let stack_value = emit_ptr_va_arg(
303        bx,
304        list,
305        layout,
306        PassMode::Direct,
307        SlotSize::Bytes8,
308        AllowHigherAlign::Yes,
309        match bx.tcx().sess.target.endian {
310            Endian::Big => ForceRightAdjust::Yes,
311            Endian::Little => ForceRightAdjust::No,
312        },
313    );
314    bx.br(end);
315
316    bx.switch_to_block(end);
317    bx.phi(to_backend_type(bx, layout), &[reg_value, stack_value], &[in_reg, on_stack])
318}
319
320fn is_powerpc_softfloat_abi(target: &Target) -> bool {
321    if target.arch != Arch::PowerPC {
322        return false;
323    }
324
325    match target.rustc_abi {
326        Some(RustcAbi::Softfloat) => ::rustc_span::macros::bug_impl(None,
    format_args!("there are currently no powerpc softfloat targets"),
    Location::caller())bug!("there are currently no powerpc softfloat targets"),
327        Some(RustcAbi::PowerPcSpe) => true, // SPE is like softfloat in terms of ABI
328        None => false,
329        Some(other) => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected powerpc abi {0:?}", other), Location::caller())bug!("unexpected powerpc abi {other:?}"),
330    }
331}
332
333fn emit_powerpc_va_arg<'ll, 'tcx>(
334    bx: &mut Builder<'_, 'll, 'tcx>,
335    list: OperandRef<'tcx, Value<'ll>>,
336    layout: TyAndLayout<'tcx>,
337) -> Value<'ll> {
338    let dl = bx.cx.data_layout();
339
340    // struct __va_list_tag {
341    //   unsigned char gpr;
342    //   unsigned char fpr;
343    //   unsigned short reserved;
344    //   void *overflow_arg_area;
345    //   void *reg_save_area;
346    // };
347    let va_list_addr = list.immediate();
348
349    // Peel off any newtype wrappers.
350    let layout = layout.peel_transparent_wrappers_from_non_1zst(bx.cx);
351
352    // All instances of VaArgSafe are passed directly.
353    let is_indirect = false;
354
355    let is_int = match layout.layout.backend_repr() {
356        BackendRepr::Scalar(scalar) => match scalar.primitive() {
357            rustc_abi::Primitive::Bool
358            | rustc_abi::Primitive::Int(_, _)
359            | rustc_abi::Primitive::Pointer(_) => true,
360            rustc_abi::Primitive::Float(_) => false,
361        },
362        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("all instances of VaArgSafe are represented as scalars")));
}unreachable!("all instances of VaArgSafe are represented as scalars"),
363    };
364
365    let is_passed_in_fprs = !(is_int || is_powerpc_softfloat_abi(&bx.cx.tcx.sess.target));
366
367    let num_regs_addr = if !is_passed_in_fprs {
368        va_list_addr // gpr
369    } else {
370        bx.inbounds_ptradd(va_list_addr, bx.const_usize(1)) // fpr
371    };
372
373    let mut num_regs = bx.load(bx.type_i8(), num_regs_addr, Align::ONE);
374
375    // "Align" the register count when the type is passed as `i64`.
376    if layout.size.bytes() == 8 && !is_passed_in_fprs {
377        num_regs = bx.add(num_regs, bx.const_u8(1));
378        num_regs = bx.and(num_regs, bx.const_u8(0b1111_1110));
379    }
380
381    let max_regs = 8u8;
382    let reg_size = if is_passed_in_fprs { 8 } else { 4 };
383    let reg_incr = layout.size.bytes().div_ceil(u64::from(reg_size)) as u8;
384    let use_regs = bx.icmp(IntPredicate::IntULE, num_regs, bx.const_u8(max_regs - reg_incr));
385
386    let ptr_align_abi = bx.tcx().data_layout.pointer_align();
387
388    let in_reg = bx.append_sibling_block("va_arg.in_reg");
389    let in_mem = bx.append_sibling_block("va_arg.in_mem");
390    let end = bx.append_sibling_block("va_arg.end");
391
392    bx.cond_br(use_regs, in_reg, in_mem);
393
394    let reg_addr = {
395        bx.switch_to_block(in_reg);
396
397        let reg_save_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(1 + 1 + 2 + 4));
398        let mut reg_addr = bx.load(bx.type_ptr(), reg_save_area_ptr, ptr_align_abi);
399
400        // Floating-point registers start after the general-purpose registers.
401        if is_passed_in_fprs {
402            reg_addr = bx.inbounds_ptradd(reg_addr, bx.cx.const_usize(32))
403        }
404
405        // Get the address of the saved value by scaling the number of
406        // registers we've used by the number of.
407        let reg_offset = bx.mul(num_regs, bx.cx().const_u8(reg_size));
408        let reg_addr = bx.inbounds_ptradd(reg_addr, reg_offset);
409
410        // Increase the used-register count.
411        let new_num_regs = bx.add(num_regs, bx.cx.const_u8(reg_incr));
412        bx.store(new_num_regs, num_regs_addr, Align::ONE);
413
414        bx.br(end);
415
416        reg_addr
417    };
418
419    let mem_addr = {
420        bx.switch_to_block(in_mem);
421
422        bx.store(bx.const_u8(max_regs), num_regs_addr, Align::ONE);
423
424        // Everything in the overflow area is rounded up to a size of at least 4.
425        let overflow_area_align = Align::FOUR;
426
427        let size = if !is_indirect {
428            layout.layout.size.align_to(overflow_area_align)
429        } else {
430            dl.pointer_size()
431        };
432
433        let overflow_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(1 + 1 + 2));
434        let mut overflow_area = bx.load(bx.type_ptr(), overflow_area_ptr, ptr_align_abi);
435
436        // Round up address of argument to alignment
437        let align = get_param_type_alignment(bx, layout);
438        if align > overflow_area_align {
439            overflow_area = round_pointer_up_to_alignment(bx, overflow_area, align);
440        }
441
442        let mem_addr = overflow_area;
443
444        // Increase the overflow area.
445        overflow_area = bx.inbounds_ptradd(overflow_area, bx.const_usize(size.bytes()));
446        bx.store(overflow_area, overflow_area_ptr, ptr_align_abi);
447
448        bx.br(end);
449
450        mem_addr
451    };
452
453    // Return the appropriate result.
454    bx.switch_to_block(end);
455    let val_addr = bx.phi(bx.type_ptr(), &[reg_addr, mem_addr], &[in_reg, in_mem]);
456    let val_type = to_backend_type(bx, layout);
457    let val_addr =
458        if is_indirect { bx.load(bx.cx.type_ptr(), val_addr, ptr_align_abi) } else { val_addr };
459    let align = get_param_type_alignment(bx, layout);
460    bx.load(val_type, val_addr, align)
461}
462
463fn emit_s390x_va_arg<'ll, 'tcx>(
464    bx: &mut Builder<'_, 'll, 'tcx>,
465    list: OperandRef<'tcx, Value<'ll>>,
466    layout: TyAndLayout<'tcx>,
467) -> Value<'ll> {
468    let dl = bx.cx.data_layout();
469
470    // Implementation of the s390x ELF ABI calling convention for va_args see
471    // https://github.com/IBM/s390x-abi (chapter 1.2.4)
472    //
473    // typedef struct __va_list_tag {
474    //     long __gpr;
475    //     long __fpr;
476    //     void *__overflow_arg_area;
477    //     void *__reg_save_area;
478    // } va_list[1];
479    let va_list_addr = list.immediate();
480
481    // There is no padding between fields since `long` and `void*` both have size=8 align=8.
482    // https://github.com/IBM/s390x-abi (Table 1.1.: Scalar types)
483    let i64_offset = 8;
484    let ptr_offset = 8;
485    let gpr = va_list_addr;
486    let fpr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(i64_offset));
487    let overflow_arg_area = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * i64_offset));
488    let reg_save_area =
489        bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * i64_offset + ptr_offset));
490
491    let in_reg = bx.append_sibling_block("va_arg.in_reg");
492    let in_mem = bx.append_sibling_block("va_arg.in_mem");
493    let end = bx.append_sibling_block("va_arg.end");
494    let ptr_align_abi = dl.pointer_align();
495
496    // FIXME: vector ABI not yet supported.
497    let target_ty_size = layout.size.bytes();
498    let indirect: bool = target_ty_size > 8 || !target_ty_size.is_power_of_two();
499    let unpadded_size = if indirect { 8 } else { target_ty_size };
500    let padded_size = 8;
501    let padding = padded_size - unpadded_size;
502
503    // NOTE: if we ever allow aggregate types, this should handle structs with a single fp element.
504    let is_single_fp_element = |layout: TyAndLayout<'_>| -> bool {
505        match layout.layout.backend_repr() {
506            BackendRepr::Scalar(scalar) => match scalar.primitive() {
507                Primitive::Float(Float::F16 | Float::F32 | Float::F64) => true,
508                Primitive::Float(Float::F128) => false,
509                Primitive::Bool | Primitive::Int(_, _) | Primitive::Pointer(_) => false,
510                Primitive::Float(Float::F16B) => {
511                    ::rustc_span::macros::bug_impl(None,
    format_args!("`f16b` use in varadics unsupported on s390x"),
    Location::caller())bug!("`f16b` use in varadics unsupported on s390x")
512                }
513                Primitive::Float(Float::PpcF128) => {
514                    ::rustc_span::macros::bug_impl(None,
    format_args!("`ppcf128` use in varadics unsupported on s390x"),
    Location::caller())bug!("`ppcf128` use in varadics unsupported on s390x")
515                }
516                Primitive::Float(Float::X87F80) => {
517                    ::rustc_span::macros::bug_impl(None,
    format_args!("`x87_f80` use in varadics unsupported on s390x"),
    Location::caller())bug!("`x87_f80` use in varadics unsupported on s390x")
518                }
519            },
520
521            _ => false,
522        }
523    };
524
525    let gpr_type = indirect || !is_single_fp_element(layout);
526    let (max_regs, reg_count, reg_save_index, reg_padding) =
527        if gpr_type { (5, gpr, 2, padding) } else { (4, fpr, 16, 0) };
528
529    // Check whether the value was passed in a register or in memory.
530    let reg_count_v = bx.load(bx.type_i64(), reg_count, Align::from_bytes(8).unwrap());
531    let use_regs = bx.icmp(IntPredicate::IntULT, reg_count_v, bx.const_u64(max_regs));
532    bx.cond_br(use_regs, in_reg, in_mem);
533
534    // Emit code to load the value if it was passed in a register.
535    bx.switch_to_block(in_reg);
536
537    // Work out the address of the value in the register save area.
538    let reg_ptr_v = bx.load(bx.type_ptr(), reg_save_area, ptr_align_abi);
539    let scaled_reg_count = bx.mul(reg_count_v, bx.const_u64(8));
540    let reg_off = bx.add(scaled_reg_count, bx.const_u64(reg_save_index * 8 + reg_padding));
541    let reg_addr = bx.ptradd(reg_ptr_v, reg_off);
542
543    // Update the register count.
544    let new_reg_count_v = bx.add(reg_count_v, bx.const_u64(1));
545    bx.store(new_reg_count_v, reg_count, Align::from_bytes(8).unwrap());
546    bx.br(end);
547
548    // Emit code to load the value if it was passed in memory.
549    bx.switch_to_block(in_mem);
550
551    // Work out the address of the value in the argument overflow area.
552    let arg_ptr_v = bx.load(bx.type_ptr(), overflow_arg_area, ptr_align_abi);
553    let arg_off = bx.const_u64(padding);
554    let mem_addr = bx.ptradd(arg_ptr_v, arg_off);
555
556    // Update the argument overflow area pointer.
557    let arg_size = bx.cx().const_u64(padded_size);
558    let new_arg_ptr_v = bx.inbounds_ptradd(arg_ptr_v, arg_size);
559    bx.store(new_arg_ptr_v, overflow_arg_area, ptr_align_abi);
560    bx.br(end);
561
562    // Return the appropriate result.
563    bx.switch_to_block(end);
564    let val_addr = bx.phi(bx.type_ptr(), &[reg_addr, mem_addr], &[in_reg, in_mem]);
565    let val_type = to_backend_type(bx, layout);
566    let val_addr =
567        if indirect { bx.load(bx.cx.type_ptr(), val_addr, ptr_align_abi) } else { val_addr };
568    bx.load(val_type, val_addr, layout.align)
569}
570
571fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>(
572    bx: &mut Builder<'_, 'll, 'tcx>,
573    list: OperandRef<'tcx, Value<'ll>>,
574    layout: TyAndLayout<'tcx>,
575) -> Value<'ll> {
576    let dl = bx.cx.data_layout();
577
578    // Implementation of the systemv x86_64 ABI calling convention for va_args, see
579    // https://gitlab.com/x86-psABIs/x86-64-ABI (section 3.5.7). This implementation is heavily
580    // based on the one in clang.
581
582    // We're able to take some shortcuts because the return type of `va_arg` must implement the
583    // `VaArgSafe` trait. Currently, only pointers, f64, i32, u32, i64 and u64 implement this trait.
584
585    // typedef struct __va_list_tag {
586    //     unsigned int gp_offset;
587    //     unsigned int fp_offset;
588    //     void *overflow_arg_area;
589    //     void *reg_save_area;
590    // } va_list[1];
591    let va_list_addr = list.immediate();
592
593    // Peel off any newtype wrappers.
594    //
595    // The "C" ABI does not unwrap newtypes (see `ReprOptions::inhibit_newtype_abi_optimization`).
596    // Here, we do actually want the unwrapped representation, because that is how LLVM/Clang
597    // pass such types to variadic functions.
598    //
599    // An example of a type that must be unwrapped is `Foo` below. Without the unwrapping, it has
600    // `BackendRepr::Memory`, but we need it to be `BackendRepr::Scalar` to generate correct code.
601    //
602    // ```
603    // #[repr(C)]
604    // struct Empty;
605    //
606    // #[repr(C)]
607    // struct Foo([Empty; 8], i32);
608    // ```
609    let layout = layout.peel_transparent_wrappers_from_non_1zst(bx.cx);
610
611    // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
612    // in the registers. If not go to step 7.
613
614    // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
615    // general purpose registers needed to pass type and num_fp to hold
616    // the number of floating point registers needed.
617
618    let mut num_gp_registers = 0;
619    let mut num_fp_registers = 0;
620
621    let mut registers_for_primitive = |p| match p {
622        Primitive::Int(integer, _is_signed) => {
623            num_gp_registers += integer.size().bytes().div_ceil(8) as u32;
624        }
625        Primitive::Float(float) => {
626            num_fp_registers += float.size().bytes().div_ceil(16) as u32;
627        }
628        Primitive::Pointer(_) => {
629            num_gp_registers += 1;
630        }
631        Primitive::Bool => ::rustc_span::macros::bug_impl(None,
    format_args!("bool should not be allowed in va_arg"), Location::caller())bug!("bool should not be allowed in va_arg"),
632    };
633
634    match layout.layout.backend_repr() {
635        BackendRepr::Scalar(scalar) => {
636            registers_for_primitive(scalar.primitive());
637        }
638        BackendRepr::ScalarPair { a: scalar1, b: scalar2, b_offset: _ } => {
639            registers_for_primitive(scalar1.primitive());
640            registers_for_primitive(scalar2.primitive());
641        }
642        BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {
643            // Because no instance of VaArgSafe uses a non-scalar `BackendRepr`.
644            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("No x86-64 SysV va_arg implementation for {0:?}",
                layout.layout.backend_repr())));
}unreachable!(
645                "No x86-64 SysV va_arg implementation for {:?}",
646                layout.layout.backend_repr()
647            )
648        }
649        BackendRepr::Memory { .. } => {
650            let mem_addr = x86_64_sysv64_va_arg_from_memory(bx, va_list_addr, layout);
651            return bx.load(to_backend_type(bx, layout), mem_addr, layout.align);
652        }
653    };
654
655    // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
656    // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
657    // l->fp_offset > 176 - num_fp * 16 go to step 7.
658
659    // We support x86_64-unknown-linux-gnux32 which uses 4-byte pointers.
660    let unsigned_int_offset = 4;
661    let ptr_offset = bx.tcx().data_layout.pointer_size().bytes();
662
663    let gp_offset_ptr = va_list_addr;
664    let fp_offset_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(unsigned_int_offset));
665
666    let gp_offset_v = bx.load(bx.type_i32(), gp_offset_ptr, Align::EIGHT);
667    let fp_offset_v = bx.load(bx.type_i32(), fp_offset_ptr, Align::FOUR);
668
669    let mut use_regs = bx.const_bool(false);
670
671    if num_gp_registers > 0 {
672        let max_offset_val = 48u32 - num_gp_registers * 8;
673        let fits_in_gp = bx.icmp(IntPredicate::IntULE, gp_offset_v, bx.const_u32(max_offset_val));
674        use_regs = fits_in_gp;
675    }
676
677    if num_fp_registers > 0 {
678        let max_offset_val = 176u32 - num_fp_registers * 16;
679        let fits_in_fp = bx.icmp(IntPredicate::IntULE, fp_offset_v, bx.const_u32(max_offset_val));
680        use_regs = if num_gp_registers > 0 { bx.and(use_regs, fits_in_fp) } else { fits_in_fp };
681    }
682
683    let in_reg = bx.append_sibling_block("va_arg.in_reg");
684    let in_mem = bx.append_sibling_block("va_arg.in_mem");
685    let end = bx.append_sibling_block("va_arg.end");
686
687    bx.cond_br(use_regs, in_reg, in_mem);
688
689    // Emit code to load the value if it was passed in a register.
690    bx.switch_to_block(in_reg);
691
692    // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
693    // an offset of l->gp_offset and/or l->fp_offset. This may require
694    // copying to a temporary location in case the parameter is passed
695    // in different register classes or requires an alignment greater
696    // than 8 for general purpose registers and 16 for XMM registers.
697    //
698    // FIXME(llvm): This really results in shameful code when we end up needing to
699    // collect arguments from different places; often what should result in a
700    // simple assembling of a structure from scattered addresses has many more
701    // loads than necessary. Can we clean this up?
702    let reg_save_area_ptr =
703        bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * unsigned_int_offset + ptr_offset));
704    let reg_save_area_v = bx.load(bx.type_ptr(), reg_save_area_ptr, dl.pointer_align());
705
706    let reg_addr = match layout.layout.backend_repr() {
707        BackendRepr::Scalar(scalar) => match scalar.primitive() {
708            Primitive::Int(_, _) | Primitive::Pointer(_) => {
709                let reg_addr = bx.inbounds_ptradd(reg_save_area_v, gp_offset_v);
710
711                // Copy into a temporary if the type is more aligned than the register save area.
712                let gp_align = Align::from_bytes(8).unwrap();
713                copy_to_temporary_if_more_aligned(bx, reg_addr, layout, gp_align)
714            }
715            Primitive::Float(_) => bx.inbounds_ptradd(reg_save_area_v, fp_offset_v),
716            Primitive::Bool => ::rustc_span::macros::bug_impl(None,
    format_args!("bool should not be allowed in va_arg"), Location::caller())bug!("bool should not be allowed in va_arg"),
717        },
718        BackendRepr::ScalarPair { a: scalar1, b: scalar2, b_offset: offset } => {
719            let ty_lo = bx.cx().scalar_pair_element_backend_type(layout, 0, false);
720            let ty_hi = bx.cx().scalar_pair_element_backend_type(layout, 1, false);
721
722            let align_lo = layout.field(bx.cx, 0).layout.align();
723            let align_hi = layout.field(bx.cx, 1).layout.align();
724
725            match (scalar1.primitive(), scalar2.primitive()) {
726                (Primitive::Float(_), Primitive::Float(_)) => {
727                    // SSE registers are spaced 16 bytes apart in the register save
728                    // area, we need to collect the two eightbytes together.
729                    // The ABI isn't explicit about this, but it seems reasonable
730                    // to assume that the slots are 16-byte aligned, since the stack is
731                    // naturally 16-byte aligned and the prologue is expected to store
732                    // all the SSE registers to the RSA.
733                    let reg_lo_addr = bx.inbounds_ptradd(reg_save_area_v, fp_offset_v);
734                    let reg_hi_addr = bx.inbounds_ptradd(reg_lo_addr, bx.const_i32(16));
735
736                    let align = layout.layout.align();
737                    let tmp = bx.alloca(layout.size, layout.align);
738
739                    let reg_lo = bx.load(ty_lo, reg_lo_addr, align_lo);
740                    let reg_hi = bx.load(ty_hi, reg_hi_addr, align_hi);
741
742                    let field0 = tmp;
743                    let field1 = bx.inbounds_ptradd(tmp, bx.const_u32(offset.bytes() as u32));
744
745                    bx.store(reg_lo, field0, align);
746                    bx.store(reg_hi, field1, align);
747
748                    tmp
749                }
750                (Primitive::Float(_), _) | (_, Primitive::Float(_)) => {
751                    let gp_addr = bx.inbounds_ptradd(reg_save_area_v, gp_offset_v);
752                    let fp_addr = bx.inbounds_ptradd(reg_save_area_v, fp_offset_v);
753
754                    let (reg_lo_addr, reg_hi_addr) = match scalar1.primitive() {
755                        Primitive::Float(_) => (fp_addr, gp_addr),
756                        Primitive::Int(_, _) | Primitive::Pointer(_) => (gp_addr, fp_addr),
757                        Primitive::Bool => ::rustc_span::macros::bug_impl(None,
    format_args!("bool should not be allowed in va_arg"), Location::caller())bug!("bool should not be allowed in va_arg"),
758                    };
759
760                    let tmp = bx.alloca(layout.size, layout.align);
761
762                    let reg_lo = bx.load(ty_lo, reg_lo_addr, align_lo);
763                    let reg_hi = bx.load(ty_hi, reg_hi_addr, align_hi);
764
765                    let field0 = tmp;
766                    let field1 = bx.inbounds_ptradd(tmp, bx.const_u32(offset.bytes() as u32));
767
768                    bx.store(reg_lo, field0, align_lo);
769                    bx.store(reg_hi, field1, align_hi);
770
771                    tmp
772                }
773                (_, _) => {
774                    // Two integer/pointer values are just contiguous in memory.
775                    let reg_addr = bx.inbounds_ptradd(reg_save_area_v, gp_offset_v);
776
777                    // Copy into a temporary if the type is more aligned than the register save area.
778                    let gp_align = Align::from_bytes(8).unwrap();
779                    copy_to_temporary_if_more_aligned(bx, reg_addr, layout, gp_align)
780                }
781            }
782        }
783        // The Previous match on `BackendRepr` means control flow already escaped.
784        BackendRepr::SimdVector { .. }
785        | BackendRepr::SimdScalableVector { .. }
786        | BackendRepr::Memory { .. } => ::core::panicking::unreachable_default_msg()unreachable!(),
787    };
788
789    // AMD64-ABI 3.5.7p5: Step 5. Set:
790    // l->gp_offset = l->gp_offset + num_gp * 8
791    if num_gp_registers > 0 {
792        let offset = bx.const_u32(num_gp_registers * 8);
793        let sum = bx.add(gp_offset_v, offset);
794        // An alignment of 8 because `__va_list_tag` is 8-aligned and this is its first field.
795        bx.store(sum, gp_offset_ptr, Align::from_bytes(8).unwrap());
796    }
797
798    // l->fp_offset = l->fp_offset + num_fp * 16.
799    if num_fp_registers > 0 {
800        let offset = bx.const_u32(num_fp_registers * 16);
801        let sum = bx.add(fp_offset_v, offset);
802        bx.store(sum, fp_offset_ptr, Align::FOUR);
803    }
804
805    bx.br(end);
806
807    bx.switch_to_block(in_mem);
808    let mem_addr = x86_64_sysv64_va_arg_from_memory(bx, va_list_addr, layout);
809    bx.br(end);
810
811    bx.switch_to_block(end);
812
813    let val_type = to_backend_type(bx, layout);
814    let val_addr = bx.phi(bx.type_ptr(), &[reg_addr, mem_addr], &[in_reg, in_mem]);
815
816    bx.load(val_type, val_addr, layout.align)
817}
818
819/// Copy into a temporary if the type is more aligned than the register save area.
820fn copy_to_temporary_if_more_aligned<'ll, 'tcx>(
821    bx: &mut Builder<'_, 'll, 'tcx>,
822    reg_addr: Value<'ll>,
823    layout: TyAndLayout<'tcx>,
824    src_align: Align,
825) -> Value<'ll> {
826    if layout.layout.align > src_align {
827        if !layout.ty.is_integral() {
    ::core::panicking::panic("assertion failed: layout.ty.is_integral()")
};assert!(layout.ty.is_integral());
828
829        // A memcpy below optimizes poorly for 128-bit integers.
830        let tmp = bx.alloca(layout.size, layout.align);
831        let val = bx.load(to_backend_type(bx, layout), reg_addr, src_align);
832        bx.store(val, tmp, layout.align);
833        tmp
834    } else {
835        reg_addr
836    }
837}
838
839fn x86_64_sysv64_va_arg_from_memory<'ll, 'tcx>(
840    bx: &mut Builder<'_, 'll, 'tcx>,
841    va_list_addr: Value<'ll>,
842    layout: TyAndLayout<'tcx>,
843) -> Value<'ll> {
844    let dl = bx.cx.data_layout();
845    let ptr_align_abi = dl.data_layout().pointer_align();
846
847    let overflow_arg_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(8));
848
849    let overflow_arg_area_v = bx.load(bx.type_ptr(), overflow_arg_area_ptr, ptr_align_abi);
850    // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
851    // byte boundary if alignment needed by type exceeds 8 byte boundary.
852    // It isn't stated explicitly in the standard, but in practice we use
853    // alignment greater than 16 where necessary.
854    // The AMD64 psABI leaves unspecified what to do for alignments above 16, but
855    // this behavior for 32+ alignment matches clang.
856    // It currently (2026 July) can only occur for 16-byte-aligned types.
857    let overflow_arg_area_v = if layout.layout.align.bytes() > 8 {
858        round_pointer_up_to_alignment(bx, overflow_arg_area_v, layout.layout.align)
859    } else {
860        overflow_arg_area_v
861    };
862
863    // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
864    let mem_addr = overflow_arg_area_v;
865
866    // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
867    // l->overflow_arg_area + sizeof(type).
868    // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
869    // an 8 byte boundary.
870    let size_in_bytes = layout.layout.size().bytes();
871    let offset = bx.const_i32(size_in_bytes.next_multiple_of(8) as i32);
872    let overflow_arg_area = bx.inbounds_ptradd(overflow_arg_area_v, offset);
873    bx.store(overflow_arg_area, overflow_arg_area_ptr, ptr_align_abi);
874
875    mem_addr
876}
877
878fn emit_hexagon_va_arg_musl<'ll, 'tcx>(
879    bx: &mut Builder<'_, 'll, 'tcx>,
880    list: OperandRef<'tcx, Value<'ll>>,
881    layout: TyAndLayout<'tcx>,
882) -> Value<'ll> {
883    // Implementation of va_arg for Hexagon musl target.
884    // Based on LLVM's HexagonBuiltinVaList implementation.
885    //
886    // struct __va_list_tag {
887    //   void *__current_saved_reg_area_pointer;
888    //   void *__saved_reg_area_end_pointer;
889    //   void *__overflow_area_pointer;
890    // };
891    //
892    // All variadic arguments are passed on the stack, but the musl implementation
893    //  uses a register save area for compatibility.
894    let va_list_addr = list.immediate();
895    let ptr_align_abi = bx.tcx().data_layout.pointer_align();
896    let ptr_size = bx.tcx().data_layout.pointer_size().bytes();
897
898    // Check if argument fits in register save area
899    let maybe_reg = bx.append_sibling_block("va_arg.maybe_reg");
900    let from_overflow = bx.append_sibling_block("va_arg.from_overflow");
901    let end = bx.append_sibling_block("va_arg.end");
902
903    // Load the three pointers from va_list
904    let current_ptr_addr = va_list_addr;
905    let end_ptr_addr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(ptr_size));
906    let overflow_ptr_addr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(2 * ptr_size));
907
908    let current_ptr = bx.load(bx.type_ptr(), current_ptr_addr, ptr_align_abi);
909    let end_ptr = bx.load(bx.type_ptr(), end_ptr_addr, ptr_align_abi);
910    let overflow_ptr = bx.load(bx.type_ptr(), overflow_ptr_addr, ptr_align_abi);
911
912    // Align current pointer based on argument type size (following LLVM's implementation)
913    // Arguments <= 32 bits (4 bytes) use 4-byte alignment, > 32 bits use 8-byte alignment
914    let type_size_bits = layout.size.bits();
915    let arg_align = if type_size_bits > 32 { Align::EIGHT } else { Align::FOUR };
916    let aligned_current = round_pointer_up_to_alignment(bx, current_ptr, arg_align);
917
918    // Calculate next pointer position (following LLVM's logic)
919    // Arguments <= 32 bits take 4 bytes, > 32 bits take 8 bytes
920    let arg_size = if type_size_bits > 32 { 8 } else { 4 };
921    let next_ptr = bx.inbounds_ptradd(aligned_current, bx.const_usize(arg_size));
922
923    // Check if argument fits in register save area
924    let fits_in_regs = bx.icmp(IntPredicate::IntULE, next_ptr, end_ptr);
925    bx.cond_br(fits_in_regs, maybe_reg, from_overflow);
926
927    // Load from register save area
928    bx.switch_to_block(maybe_reg);
929    let reg_value_addr = aligned_current;
930    // Update current pointer
931    bx.store(next_ptr, current_ptr_addr, ptr_align_abi);
932    bx.br(end);
933
934    // Load from overflow area (stack)
935    bx.switch_to_block(from_overflow);
936
937    // Align overflow pointer using the same alignment rules
938    let aligned_overflow = round_pointer_up_to_alignment(bx, overflow_ptr, arg_align);
939
940    let overflow_value_addr = aligned_overflow;
941    // Update overflow pointer - use the same size calculation
942    let next_overflow = bx.inbounds_ptradd(aligned_overflow, bx.const_usize(arg_size));
943    bx.store(next_overflow, overflow_ptr_addr, ptr_align_abi);
944
945    // IMPORTANT: Also update the current saved register area pointer to match
946    // This synchronizes the pointers when switching to overflow area
947    bx.store(next_overflow, current_ptr_addr, ptr_align_abi);
948    bx.br(end);
949
950    // Return the value
951    bx.switch_to_block(end);
952    let value_addr =
953        bx.phi(bx.type_ptr(), &[reg_value_addr, overflow_value_addr], &[maybe_reg, from_overflow]);
954    bx.load(to_backend_type(bx, layout), value_addr, layout.align)
955}
956
957fn emit_hexagon_va_arg_bare_metal<'ll, 'tcx>(
958    bx: &mut Builder<'_, 'll, 'tcx>,
959    list: OperandRef<'tcx, Value<'ll>>,
960    layout: TyAndLayout<'tcx>,
961) -> Value<'ll> {
962    // Implementation of va_arg for Hexagon bare-metal (non-musl) targets.
963    // Based on LLVM's EmitVAArgForHexagon implementation.
964    //
965    // va_list is a simple pointer (char *)
966    let va_list_addr = list.immediate();
967    let ptr_align_abi = bx.tcx().data_layout.pointer_align();
968
969    // Load current pointer from va_list
970    let current_ptr = bx.load(bx.type_ptr(), va_list_addr, ptr_align_abi);
971
972    // Handle address alignment for types with alignment > 4 bytes
973    let ty_align = layout.align;
974    let aligned_ptr = if ty_align.bytes() > 4 {
975        // Ensure alignment is a power of 2
976        if true {
    if !ty_align.bytes().is_power_of_two() {
        {
            ::core::panicking::panic_fmt(format_args!("Alignment is not power of 2!"));
        }
    };
};debug_assert!(ty_align.bytes().is_power_of_two(), "Alignment is not power of 2!");
977        round_pointer_up_to_alignment(bx, current_ptr, ty_align)
978    } else {
979        current_ptr
980    };
981
982    // Calculate offset: round up type size to 4-byte boundary (minimum stack slot size)
983    let type_size = layout.size.bytes();
984    let offset = type_size.next_multiple_of(4); // align to 4 bytes
985
986    // Update va_list to point to next argument
987    let next_ptr = bx.inbounds_ptradd(aligned_ptr, bx.const_usize(offset));
988    bx.store(next_ptr, va_list_addr, ptr_align_abi);
989
990    // Load and return the argument value
991    bx.load(to_backend_type(bx, layout), aligned_ptr, layout.align)
992}
993
994fn emit_xtensa_va_arg<'ll, 'tcx>(
995    bx: &mut Builder<'_, 'll, 'tcx>,
996    list: OperandRef<'tcx, Value<'ll>>,
997    layout: TyAndLayout<'tcx>,
998) -> Value<'ll> {
999    // Implementation of va_arg for Xtensa. There doesn't seem to be an authoritative source for
1000    // this, other than "what GCC does".
1001    //
1002    // The va_list type has three fields:
1003    // struct __va_list_tag {
1004    //   int32_t *va_stk; // Arguments passed on the stack
1005    //   int32_t *va_reg; // Arguments passed in registers, saved to memory by the prologue.
1006    //   int32_t va_ndx; // Offset into the arguments, in bytes
1007    // };
1008    //
1009    // The first 24 bytes (equivalent to 6 registers) come from va_reg, the rest from va_stk.
1010    // Thus if va_ndx is less than 24, the next va_arg *may* read from va_reg,
1011    // otherwise it must come from va_stk.
1012    //
1013    // Primitive arguments are never split between registers and the stack. For example, if loading an 8 byte
1014    // primitive value and va_ndx = 20, we instead bump the offset and read everything from va_stk.
1015    let va_list_addr = list.immediate();
1016    // FIXME: handle multi-field structs that split across regsave/stack?
1017    let from_stack = bx.append_sibling_block("va_arg.from_stack");
1018    let from_regsave = bx.append_sibling_block("va_arg.from_regsave");
1019    let end = bx.append_sibling_block("va_arg.end");
1020    let ptr_align_abi = bx.tcx().data_layout.pointer_align();
1021
1022    // (*va).va_ndx
1023    let va_reg_offset = 4;
1024    let va_ndx_offset = va_reg_offset + 4;
1025    let offset_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(va_ndx_offset));
1026
1027    let offset = bx.load(bx.type_i32(), offset_ptr, bx.tcx().data_layout.i32_align);
1028    let offset = round_up_to_alignment(bx, offset, layout.align);
1029
1030    let slot_size = layout.size.align_to(Align::FOUR).bytes() as i32;
1031
1032    // Update the offset in va_list, by adding the slot's size.
1033    let offset_next = bx.add(offset, bx.const_i32(slot_size));
1034
1035    // Figure out where to look for our value. We do that by checking the end of our slot (offset_next).
1036    // If that is within the regsave area, then load from there. Otherwise load from the stack area.
1037    let regsave_size = bx.const_i32(24);
1038    let use_regsave = bx.icmp(IntPredicate::IntULE, offset_next, regsave_size);
1039    bx.cond_br(use_regsave, from_regsave, from_stack);
1040
1041    bx.switch_to_block(from_regsave);
1042    // update va_ndx
1043    bx.store(offset_next, offset_ptr, ptr_align_abi);
1044
1045    // (*va).va_reg
1046    let regsave_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(va_reg_offset));
1047    let regsave_area = bx.load(bx.type_ptr(), regsave_area_ptr, ptr_align_abi);
1048    let regsave_value_ptr = bx.inbounds_ptradd(regsave_area, offset);
1049    bx.br(end);
1050
1051    bx.switch_to_block(from_stack);
1052
1053    // The first time we switch from regsave to stack we needs to adjust our offsets a bit.
1054    // va_stk is set up such that the first stack argument is always at va_stk + 32.
1055    // The corrected offset is written back into the va_list struct.
1056
1057    // let offset_corrected = cmp::max(offset, 32);
1058    let stack_offset_start = bx.const_i32(32);
1059    let needs_correction = bx.icmp(IntPredicate::IntULE, offset, stack_offset_start);
1060    let offset_corrected = bx.select(needs_correction, stack_offset_start, offset);
1061
1062    // let offset_next_corrected = offset_corrected + slot_size;
1063    // va_ndx = offset_next_corrected;
1064    let offset_next_corrected = bx.add(offset_corrected, bx.const_i32(slot_size));
1065    // update va_ndx
1066    bx.store(offset_next_corrected, offset_ptr, ptr_align_abi);
1067
1068    // let stack_value_ptr = unsafe { (*va).va_stk.byte_add(offset_corrected) };
1069    let stack_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(0));
1070    let stack_area = bx.load(bx.type_ptr(), stack_area_ptr, ptr_align_abi);
1071    let stack_value_ptr = bx.inbounds_ptradd(stack_area, offset_corrected);
1072    bx.br(end);
1073
1074    bx.switch_to_block(end);
1075
1076    // On big-endian, for values smaller than the slot size we'd have to align the read to the end
1077    // of the slot rather than the start. While the ISA and GCC support big-endian, all the Xtensa
1078    // targets supported by rustc are little-endian so don't worry about it.
1079
1080    // if from_regsave {
1081    //     unsafe { *regsave_value_ptr }
1082    // } else {
1083    //     unsafe { *stack_value_ptr }
1084    // }
1085    if !(bx.tcx().sess.target.endian == Endian::Little) {
    ::core::panicking::panic("assertion failed: bx.tcx().sess.target.endian == Endian::Little")
};assert!(bx.tcx().sess.target.endian == Endian::Little);
1086    let value_ptr =
1087        bx.phi(bx.type_ptr(), &[regsave_value_ptr, stack_value_ptr], &[from_regsave, from_stack]);
1088    bx.load(to_backend_type(bx, layout), value_ptr, layout.align)
1089}
1090
1091/// Determine the va_arg implementation to use. The LLVM va_arg instruction
1092/// is lacking in some instances, so we should only use it as a fallback.
1093///
1094/// <https://llvm.org/docs/LangRef.html#va-arg-instruction>
1095pub(super) fn emit_va_arg<'ll, 'tcx>(
1096    bx: &mut Builder<'_, 'll, 'tcx>,
1097    addr: OperandRef<'tcx, Value<'ll>>,
1098    layout: TyAndLayout<'tcx>,
1099) -> Value<'ll> {
1100    // Some ABIs have special behavior for zero-sized types. currently `VaArgSafe` is not
1101    // implemented for any zero-sized types, so this assert should always hold.
1102    if !!layout.is_zst() {
    ::core::panicking::panic("assertion failed: !layout.is_zst()")
};assert!(!layout.is_zst());
1103
1104    let target = &bx.cx.tcx.sess.target;
1105    let stability = target.supports_c_variadic_definitions();
1106
1107    match target.arch {
1108        Arch::X86 => {
1109            // A small deviation from clang to get the right behavior for f128.
1110            //
1111            // Note that i64 and f64 have an alignment of only 4 on this architecture.
1112            // We need to be careful when adding future types with an alignment bigger
1113            // than 4 (e.g. i128), clang has a bunch of custom logic for them.
1114            let allow_higher_align = if layout.ty == bx.tcx().types.f128 {
1115                AllowHigherAlign::Yes
1116            } else {
1117                AllowHigherAlign::No
1118            };
1119
1120            emit_ptr_va_arg(
1121                bx,
1122                addr,
1123                layout,
1124                PassMode::Direct,
1125                SlotSize::Bytes4,
1126                allow_higher_align,
1127                ForceRightAdjust::No,
1128            )
1129        }
1130        Arch::Arm64EC => emit_ptr_va_arg(
1131            bx,
1132            addr,
1133            layout,
1134            // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
1135            // not 1, 2, 4, or 8 bytes, must be passed by reference."
1136            if layout.size.bytes() > 8 || !layout.size.bytes().is_power_of_two() {
1137                PassMode::Indirect
1138            } else {
1139                PassMode::Direct
1140            },
1141            SlotSize::Bytes8,
1142            AllowHigherAlign::No,
1143            ForceRightAdjust::No,
1144        ),
1145        Arch::AArch64 if target.is_like_windows || target.is_like_darwin => emit_ptr_va_arg(
1146            bx,
1147            addr,
1148            layout,
1149            PassMode::Direct,
1150            SlotSize::Bytes8,
1151            AllowHigherAlign::Yes,
1152            ForceRightAdjust::No,
1153        ),
1154        Arch::AArch64 => emit_aapcs_va_arg(bx, addr, layout),
1155        Arch::Arm => {
1156            // Types wider than 16 bytes are not currently supported. Clang has special logic for
1157            // such types, but `VaArgSafe` is not implemented for any type that is this large on
1158            // arm (i.e. 32-bit) targets.
1159            if !(layout.size.bytes() <= 16) {
    ::core::panicking::panic("assertion failed: layout.size.bytes() <= 16")
};assert!(layout.size.bytes() <= 16);
1160
1161            emit_ptr_va_arg(
1162                bx,
1163                addr,
1164                layout,
1165                PassMode::Direct,
1166                SlotSize::Bytes4,
1167                AllowHigherAlign::Yes,
1168                ForceRightAdjust::No,
1169            )
1170        }
1171        Arch::S390x => emit_s390x_va_arg(bx, addr, layout),
1172        Arch::PowerPC => emit_powerpc_va_arg(bx, addr, layout),
1173        Arch::PowerPC64 => emit_ptr_va_arg(
1174            bx,
1175            addr,
1176            layout,
1177            PassMode::Direct,
1178            SlotSize::Bytes8,
1179            AllowHigherAlign::Yes,
1180            // ForceRightAdjust only takes effect on big-endian architectures.
1181            ForceRightAdjust::Yes,
1182        ),
1183        Arch::RiscV32 if target.llvm_abiname == LlvmAbi::Ilp32e => {
1184            {
    match stability {
        CVariadicStatus::Unstable { .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "CVariadicStatus::Unstable { .. }",
                ::core::option::Option::None);
        }
    }
};std::assert_matches!(stability, CVariadicStatus::Unstable { .. });
1185            // FIXME: clang manually adjusts the alignment for this ABI. It notes:
1186            //
1187            // > To be compatible with GCC's behaviors, we force arguments with
1188            // > 2×XLEN-bit alignment and size at most 2×XLEN bits like `long long`,
1189            // > `unsigned long long` and `double` to have 4-byte alignment. This
1190            // > behavior may be changed when RV32E/ILP32E is ratified.
1191            ::rustc_span::macros::bug_impl(None,
    format_args!("c-variadic calls with ilp32e use a custom ABI and are not currently implemented"),
    Location::caller());bug!("c-variadic calls with ilp32e use a custom ABI and are not currently implemented");
1192        }
1193        Arch::RiscV32 | Arch::LoongArch32 => emit_ptr_va_arg(
1194            bx,
1195            addr,
1196            layout,
1197            if layout.size.bytes() > 2 * 4 { PassMode::Indirect } else { PassMode::Direct },
1198            SlotSize::Bytes4,
1199            AllowHigherAlign::Yes,
1200            ForceRightAdjust::No,
1201        ),
1202        Arch::RiscV64 | Arch::LoongArch64 => emit_ptr_va_arg(
1203            bx,
1204            addr,
1205            layout,
1206            if layout.size.bytes() > 2 * 8 { PassMode::Indirect } else { PassMode::Direct },
1207            SlotSize::Bytes8,
1208            AllowHigherAlign::Yes,
1209            ForceRightAdjust::No,
1210        ),
1211        Arch::AmdGpu => emit_ptr_va_arg(
1212            bx,
1213            addr,
1214            layout,
1215            PassMode::Direct,
1216            SlotSize::Bytes4,
1217            AllowHigherAlign::No,
1218            ForceRightAdjust::No,
1219        ),
1220        Arch::Nvptx64 => emit_ptr_va_arg(
1221            bx,
1222            addr,
1223            layout,
1224            PassMode::Direct,
1225            SlotSize::Bytes1,
1226            AllowHigherAlign::Yes,
1227            ForceRightAdjust::No,
1228        ),
1229        Arch::Wasm32 | Arch::Wasm64 => emit_ptr_va_arg(
1230            bx,
1231            addr,
1232            layout,
1233            if layout.is_aggregate() || layout.is_zst() || layout.is_1zst() {
1234                PassMode::Indirect
1235            } else {
1236                PassMode::Direct
1237            },
1238            SlotSize::Bytes4,
1239            AllowHigherAlign::Yes,
1240            ForceRightAdjust::No,
1241        ),
1242        Arch::CSky => emit_ptr_va_arg(
1243            bx,
1244            addr,
1245            layout,
1246            PassMode::Direct,
1247            SlotSize::Bytes4,
1248            AllowHigherAlign::Yes,
1249            ForceRightAdjust::No,
1250        ),
1251        // Windows x86_64
1252        Arch::X86_64 if target.is_like_windows => emit_ptr_va_arg(
1253            bx,
1254            addr,
1255            layout,
1256            if layout.size.bytes() > 8 || !layout.size.bytes().is_power_of_two() {
1257                PassMode::Indirect
1258            } else {
1259                PassMode::Direct
1260            },
1261            SlotSize::Bytes8,
1262            AllowHigherAlign::No,
1263            ForceRightAdjust::No,
1264        ),
1265        // This includes `target.is_like_darwin`, which on x86_64 targets is like sysv64.
1266        Arch::X86_64 => emit_x86_64_sysv64_va_arg(bx, addr, layout),
1267        Arch::Xtensa => emit_xtensa_va_arg(bx, addr, layout),
1268        Arch::Hexagon => match target.env {
1269            Env::Musl => emit_hexagon_va_arg_musl(bx, addr, layout),
1270            _ => emit_hexagon_va_arg_bare_metal(bx, addr, layout),
1271        },
1272        Arch::Sparc64 => emit_ptr_va_arg(
1273            bx,
1274            addr,
1275            layout,
1276            if layout.size.bytes() > 2 * 8 { PassMode::Indirect } else { PassMode::Direct },
1277            SlotSize::Bytes8,
1278            AllowHigherAlign::Yes,
1279            // sparc64 is a big-endian target and stores variable arguments right-adjusted.
1280            ForceRightAdjust::Yes,
1281        ),
1282        Arch::Sparc => {
1283            {
    match stability {
        CVariadicStatus::Unstable { .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "CVariadicStatus::Unstable { .. }",
                ::core::option::Option::None);
        }
    }
};std::assert_matches!(stability, CVariadicStatus::Unstable { .. });
1284
1285            // f128 is passed indirectly.
1286            let pass_mode = match layout.layout.backend_repr() {
1287                BackendRepr::Scalar(scalar) => match scalar.primitive() {
1288                    Primitive::Float(Float::F128) => PassMode::Indirect,
1289                    _ => PassMode::Direct,
1290                },
1291                _ => PassMode::Direct,
1292            };
1293
1294            emit_ptr_va_arg(
1295                bx,
1296                addr,
1297                layout,
1298                pass_mode,
1299                SlotSize::Bytes4,
1300                AllowHigherAlign::No,
1301                ForceRightAdjust::Yes,
1302            )
1303        }
1304        Arch::Mips | Arch::Mips32r6 | Arch::Mips64 | Arch::Mips64r6 => emit_ptr_va_arg(
1305            bx,
1306            addr,
1307            layout,
1308            PassMode::Direct,
1309            match &target.llvm_abiname {
1310                LlvmAbi::N32 | LlvmAbi::N64 => SlotSize::Bytes8,
1311                LlvmAbi::O32 => SlotSize::Bytes4,
1312                other => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected LLVM ABI {0}", other), Location::caller())bug!("unexpected LLVM ABI {other}"),
1313            },
1314            AllowHigherAlign::Yes,
1315            // In big-endian mode the actual value is stored in the right side of the slot, meaning
1316            // that when the value is smaller than a slot, we need to adjust the pointer we read
1317            // to somewhere in the middle of the slot.
1318            match bx.tcx().sess.target.endian {
1319                Endian::Big => ForceRightAdjust::Yes,
1320                Endian::Little => ForceRightAdjust::No,
1321            },
1322        ),
1323        Arch::Msp430 => emit_ptr_va_arg(
1324            bx,
1325            addr,
1326            layout,
1327            PassMode::Direct,
1328            SlotSize::Bytes1,
1329            AllowHigherAlign::Yes,
1330            ForceRightAdjust::No,
1331        ),
1332        Arch::Avr => emit_ptr_va_arg(
1333            bx,
1334            addr,
1335            layout,
1336            PassMode::Direct,
1337            SlotSize::Bytes1,
1338            AllowHigherAlign::No,
1339            ForceRightAdjust::No,
1340        ),
1341        Arch::M68k => emit_ptr_va_arg(
1342            bx,
1343            addr,
1344            layout,
1345            PassMode::Direct,
1346            SlotSize::Bytes4,
1347            AllowHigherAlign::No,
1348            ForceRightAdjust::Yes,
1349        ),
1350
1351        Arch::Bpf => ::rustc_span::macros::bug_impl(None,
    format_args!("bpf does not support c-variadic functions"),
    Location::caller())bug!("bpf does not support c-variadic functions"),
1352        Arch::SpirV => ::rustc_span::macros::bug_impl(None,
    format_args!("spirv does not support c-variadic functions"),
    Location::caller())bug!("spirv does not support c-variadic functions"),
1353
1354        Arch::Other(ref arch) => {
1355            {
    match stability {
        CVariadicStatus::Unstable { .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "CVariadicStatus::Unstable { .. }",
                ::core::option::Option::None);
        }
    }
};std::assert_matches!(stability, CVariadicStatus::Unstable { .. });
1356
1357            // Just to be safe we error out explicitly here, instead of crossing our fingers that
1358            // the default LLVM implementation has the correct behavior for this target.
1359            ::rustc_span::macros::bug_impl(None,
    format_args!("c-variadic functions are not currently implemented for custom target {0}",
        arch), Location::caller())bug!("c-variadic functions are not currently implemented for custom target {arch}")
1360        }
1361    }
1362}