diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index 531ff0da6922b..57a48c5d4db32 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -4,8 +4,8 @@ use std::convert::TryFrom; use std::ops::Deref; use gccjit::{ - BinaryOp, Block, CType, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, - Type, UnaryOp, + BinaryOp, Block, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, Type, + UnaryOp, }; use rustc_abi as abi; use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout, WrappingRange}; @@ -35,9 +35,9 @@ use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi}; use crate::abi::FnAbiGccExt; use crate::builder; use crate::common::{SignType, TypeReflection, type_is_pointer}; -use crate::context::CodegenCx; #[cfg(feature = "master")] use crate::context::PendingCleanup; +use crate::context::{CodegenCx, PhiBuilder}; use crate::intrinsic::llvm; use crate::type_of::LayoutGccExt; @@ -510,6 +510,7 @@ impl<'gcc, 'tcx> BackendTypes for Builder<'_, 'gcc, 'tcx> { type Function = as BackendTypes>::Function; type BasicBlock = as BackendTypes>::BasicBlock; type Funclet = as BackendTypes>::Funclet; + type PhiBuilder = as BackendTypes>::PhiBuilder; type Value = as BackendTypes>::Value; type Type = as BackendTypes>::Type; @@ -592,6 +593,33 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { self.llbb().end_with_jump(self.location, dest) } + fn br_with_phi( + &mut self, + dest: Block<'gcc>, + phi_builders: [(&mut PhiBuilder<'gcc>, RValue<'gcc>); N], + ) { + for (builder, value) in phi_builders { + match builder.var { + None => { + let typ = value.get_type(); + let var = self.new_temp(self.llbb().get_function(), self.location, typ); + self.assign(var, value); + builder.var = Some((var, typ)); + } + Some((var, typ)) => { + // Multiple GCC types can correspond to the same SSA type (e.g. pointers). + let value = if value.get_type() != typ { + self.context.new_bitcast(self.location, value, typ) + } else { + value + }; + self.assign(var, value); + } + } + } + self.br(dest); + } + fn cond_br(&mut self, cond: RValue<'gcc>, then_block: Block<'gcc>, else_block: Block<'gcc>) { self.llbb().end_with_conditional(self.location, cond, then_block, else_block) } @@ -1262,6 +1290,15 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { ); } + fn ptr_mask(&mut self, ptr: RValue<'gcc>, mask: RValue<'gcc>) -> RValue<'gcc> { + let usize_type = self.context.new_type::(); + let void_ptr_type = self.context.new_type::<*const ()>(); + + let addr = self.bitcast(ptr, usize_type); + let masked = self.and(addr, mask); + self.bitcast(masked, void_ptr_type) + } + fn gep(&mut self, stride: Size, ptr: RValue<'gcc>, index: RValue<'gcc>) -> RValue<'gcc> { let ptr_type = ptr.get_type(); // NOTE: we cannot use array indexing here like in inbounds_gep because array indexing is @@ -1542,12 +1579,6 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { variable.to_rvalue() } - fn va_arg(&mut self, list: RValue<'gcc>, ty: Type<'gcc>) -> RValue<'gcc> { - let va_list_type = self.context.new_c_type(CType::VaList); - let list = self.context.new_cast(self.location, list, va_list_type.make_pointer()); - self.context.new_va_arg(self.location, list, ty) - } - #[cfg(feature = "master")] fn extract_element(&mut self, vec: RValue<'gcc>, idx: RValue<'gcc>) -> RValue<'gcc> { self.context.new_vector_access(self.location, vec, idx).to_rvalue() @@ -1918,6 +1949,14 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn fptosi_sat(&mut self, val: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> { self.fptoint_sat(true, val, dest_ty) } + + fn new_phi(&mut self) -> PhiBuilder<'gcc> { + PhiBuilder { var: None } + } + + fn phi_output(&mut self, phi: PhiBuilder<'gcc>) -> RValue<'gcc> { + self.assign_to_var(phi.var.expect("empty phi builder").0.to_rvalue()) + } } impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 2811057bab1bd..795edab4b7035 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -427,10 +427,15 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { } } +pub struct PhiBuilder<'gcc> { + pub(crate) var: Option<(LValue<'gcc>, Type<'gcc>)>, +} + impl<'gcc, 'tcx> BackendTypes for CodegenCx<'gcc, 'tcx> { type Function = Function<'gcc>; type BasicBlock = Block<'gcc>; type Funclet = (); // FIXME(antoyo) + type PhiBuilder = PhiBuilder<'gcc>; type Value = RValue<'gcc>; type Type = Type<'gcc>; diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 32ed80437ed95..a52f0c4140a2e 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -16,7 +16,7 @@ use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue}; use rustc_codegen_ssa::traits::MiscCodegenMethods; use rustc_codegen_ssa::traits::{ ArgAbiBuilderMethods, BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, - IntrinsicCallBuilderMethods, LayoutTypeCodegenMethods, ReturnSlot, + IntrinsicCallBuilderMethods, ReturnSlot, }; use rustc_codegen_ssa::{MemFlags, RetagInfo}; use rustc_data_structures::fx::FxHashSet; @@ -162,11 +162,6 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc sym::breakpoint | sym::resumable_breakpoint => { unimplemented!(); } - sym::va_arg => { - let va_list = args[0].immediate(); - let gcc_type = self.immediate_backend_type(result.layout); - self.va_arg(va_list, gcc_type) - } sym::volatile_load | sym::unaligned_volatile_load => { let ptr = args[0].immediate(); @@ -465,18 +460,6 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc return IntrinsicResult::WroteIntoPlace; } - sym::ptr_mask => { - let usize_type = self.context.new_type::(); - let void_ptr_type = self.context.new_type::<*const ()>(); - - let ptr = args[0].immediate(); - let mask = args[1].immediate(); - - let addr = self.bitcast(ptr, usize_type); - let masked = self.and(addr, mask); - self.bitcast(masked, void_ptr_type) - } - _ if name_str.starts_with("simd_") => { match generic_simd_intrinsic( self, diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index 2d88731ef781b..62c37907b6286 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -436,11 +436,7 @@ impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { if let Some(dbg_loc) = dbg_loc { self.set_dbg_loc(dbg_loc); } - self.phi( - self.type_x87_f80(), - &[is_nan_res, is_not_nan_res], - &[is_nan_block, is_not_nan_block], - ) + self.phi(&[is_nan_res, is_not_nan_res], &[is_nan_block, is_not_nan_block]) } fn x87_lossless_fp_stack_to_float( @@ -527,7 +523,7 @@ impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { if let Some(dbg_loc) = dbg_loc { self.set_dbg_loc(dbg_loc); } - self.phi(float_type, &[is_nan_res, is_not_nan_res], &[is_nan_block, is_not_nan_block]) + self.phi(&[is_nan_res, is_not_nan_res], &[is_nan_block, is_not_nan_block]) } } diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index ebaeb8895e4d4..63ac3f78acda5 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -27,18 +27,18 @@ use rustc_session::config::OptLevel; use rustc_span::{Span, bug}; use rustc_target::callconv::{FnAbi, PassMode}; use rustc_target::spec::{Arch, HasTargetSpec, SanitizerSet, Target}; -use smallvec::SmallVec; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use crate::abi::FnAbiLlvmExt; -use crate::attributes; -use crate::common::Funclet; +use crate::common::{Funclet, PhiBuilder}; use crate::context::{CodegenCx, FullCx, GenericCx, SCx}; use crate::llvm::{ self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE, ToLlvmBool, Type, TypeKind, Value, }; use crate::type_of::LayoutLlvmExt; +use crate::{attributes, common}; #[must_use] pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow>> { @@ -214,6 +214,7 @@ impl<'ll, CX: Borrow>> BackendTypes for GenericBuilder<'_, 'll, CX> { type Function = as BackendTypes>::Function; type BasicBlock = as BackendTypes>::BasicBlock; type Funclet = as BackendTypes>::Funclet; + type PhiBuilder = as BackendTypes>::PhiBuilder; type Value = as BackendTypes>::Value; type Type = as BackendTypes>::Type; @@ -396,6 +397,18 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { } } + fn br_with_phi( + &mut self, + dest: &'ll BasicBlock, + phi_builders: [(&mut PhiBuilder<'ll>, Value<'ll>); N], + ) { + for (builder, value) in phi_builders { + builder.values.push(value); + builder.blocks.push(self.llbb()); + } + self.br(dest); + } + fn cond_br( &mut self, cond: Value<'ll>, @@ -959,6 +972,10 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { } } + fn ptr_mask(&mut self, ptr: Self::Value, mask: Self::Value) -> Self::Value { + self.call_intrinsic("llvm.ptrmask", &[self.val_ty(ptr), self.type_isize()], &[ptr, mask]) + } + fn gep(&mut self, stride: Size, ptr: Value<'ll>, index: Value<'ll>) -> Value<'ll> { self.build_gep(stride, ptr, index, GEPNoWrapFlags::default()) } @@ -1224,10 +1241,6 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { unsafe { llvm::LLVMBuildSelect(self.llbuilder(), cond, then_val, else_val, UNNAMED) } } - fn va_arg(&mut self, list: Value<'ll>, ty: Type<'ll>) -> Value<'ll> { - unsafe { llvm::LLVMBuildVAArg(self.llbuilder(), list, ty, UNNAMED) } - } - fn extract_element(&mut self, vec: Value<'ll>, idx: Value<'ll>) -> Value<'ll> { unsafe { llvm::LLVMBuildExtractElement(self.llbuilder(), vec, idx, UNNAMED) } } @@ -1532,6 +1545,15 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx); attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]); } + + fn new_phi(&mut self) -> PhiBuilder<'ll> { + PhiBuilder { values: smallvec![], blocks: smallvec![] } + } + + fn phi_output(&mut self, phi: PhiBuilder<'ll>) -> Value<'ll> { + assert!(!phi.values.is_empty()); + self.phi(&phi.values, &phi.blocks) + } } impl<'ll> Builder<'_, 'll, '_> { @@ -1643,7 +1665,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { self.br(header_bb); let mut header_bx = Self::build(self.cx, header_bb); - let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]); + let i = header_bx.phi(&[zero], &[self.llbb()]); let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count); header_bx.cond_br(keep_going, body_bb, next_bb); @@ -1677,7 +1699,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { self.br(header_bb); let mut header_bx = Self::build(self.cx, header_bb); - let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]); + let current = header_bx.phi(&[start], &[self.llbb()]); let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end); header_bx.cond_br(keep_going, body_bb, next_bb); @@ -1873,13 +1895,9 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { } } impl<'a, 'll, CX: Borrow>> GenericBuilder<'a, 'll, CX> { - pub(crate) fn phi( - &mut self, - ty: Type<'ll>, - vals: &[Value<'ll>], - bbs: &[&'ll BasicBlock], - ) -> Value<'ll> { + pub(crate) fn phi(&mut self, vals: &[Value<'ll>], bbs: &[&'ll BasicBlock]) -> Value<'ll> { assert_eq!(vals.len(), bbs.len()); + let ty = common::val_ty(vals[0]); let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder(), ty, UNNAMED) }; unsafe { llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint); diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index c6f2ea0f82ab3..6744056430d27 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -16,6 +16,7 @@ use rustc_middle::mir::interpret::{GlobalAlloc, PointerArithmetic, Scalar}; use rustc_middle::ty::{Instance, TyCtxt}; use rustc_session::{PointerAuthAddressDiscriminator, PointerAuthSchema}; use rustc_span::bug; +use smallvec::SmallVec; use tracing::debug; use crate::consts::{IsInitOrFini, IsStatic, const_alloc_to_llvm}; @@ -124,11 +125,17 @@ impl<'ll> Funclet<'ll> { } } +pub(crate) struct PhiBuilder<'ll> { + pub(crate) values: SmallVec<[Value<'ll>; 2]>, + pub(crate) blocks: SmallVec<[&'ll BasicBlock; 2]>, +} + impl<'ll, CX: Borrow>> BackendTypes for GenericCx<'ll, CX> { // FIXME(eddyb) replace this with a `Function` "subclass" of `Value`. type Function = Value<'ll>; type BasicBlock = &'ll BasicBlock; type Funclet = Funclet<'ll>; + type PhiBuilder = PhiBuilder<'ll>; type Value = Value<'ll>; type Type = Type<'ll>; diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index e40991a39790e..59b2f1f558193 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -2,10 +2,7 @@ use std::cmp::Ordering; use std::ffi::c_uint; use std::{assert_matches, iter, ptr}; -use rustc_abi::{ - AddressSpace, Align, BackendRepr, CVariadicStatus, Float, HasDataLayout, NumScalableVectors, - Primitive, Size, -}; +use rustc_abi::{AddressSpace, Align, BackendRepr, HasDataLayout, NumScalableVectors, Size}; use rustc_attr_ir::find_attr; use rustc_codegen_ssa::RetagInfo; use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh}; @@ -23,7 +20,6 @@ use rustc_middle::mir::{self, BinOp}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout}; use rustc_middle::ty::offload_meta::OffloadMetadata; use rustc_middle::ty::{self, GenericArgs, Instance, Intrinsic, SimdAlign, Ty, TyCtxt}; -use rustc_session::diagnostics::feature_err; use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug, sym}; use rustc_structures::CrateType; use rustc_symbol_mangling::{ @@ -46,7 +42,6 @@ use crate::diagnostics::{ use crate::intrinsic::ty::typetree::fnc_typetrees; use crate::llvm::{self, Attribute, AttributePlace, Metadata, Type, TypeKind, Value}; use crate::type_of::LayoutLlvmExt; -use crate::va_arg::emit_va_arg; impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { fn black_box(&mut self, result: PlaceRef<'tcx, Value<'ll>>, span: Span) { @@ -115,14 +110,6 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { unsafe { llvm::LLVMRustSetNoSignedZeros(call) }; call } - sym::ptr_mask => { - let ptr = args[0].immediate(); - self.call_intrinsic( - "llvm.ptrmask", - &[self.val_ty(ptr), self.type_isize()], - &[ptr, args[1].immediate()], - ) - } sym::autodiff => { return codegen_autodiff(self, instance, args, result_layout, result_place); } @@ -199,88 +186,6 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { sym::breakpoint | sym::resumable_breakpoint => { self.call_intrinsic("llvm.debugtrap", &[], &[]) } - sym::va_arg => { - let target = &self.cx.tcx.sess.target; - let stability = target.supports_c_variadic_definitions(); - if let CVariadicStatus::Unstable { feature } = stability - && !self.tcx.features().enabled(feature) - { - let msg = "C-variadic function definitions on this target are unstable"; - feature_err(self.sess(), feature, span, msg).emit(); - } - - 'blk: { - // The backend_repr of x87_f80 is not a scalar, so it needs special-casing. - if result_layout.is_x87_f80(self) { - break 'blk; - } - - let BackendRepr::Scalar(scalar) = result_layout.backend_repr else { - bug!("the va_arg intrinsic does not support non-scalar types") - }; - - // We reject types that would never be passed as varargs in C because - // they get promoted to a larger type, specifically integers smaller than - // c_int and float type smaller than c_double. - match scalar.primitive() { - Primitive::Pointer(_) => { - // Pointers are always OK. - } - Primitive::Bool => { - let target_c_int_width = self.cx().sess().target.options.c_int_width; - if 1 < u64::from(target_c_int_width) { - // Smaller integer types are automatically promototed and `va_arg` - // should not be called on them. - bug!( - "va_arg got i{} but needs at least c_int (an i{})", - 1, - target_c_int_width - ); - } - } - Primitive::Int(..) => { - let int_width = self.cx().size_of(result_layout.ty).bits(); - let target_c_int_width = self.cx().sess().target.options.c_int_width; - if int_width < u64::from(target_c_int_width) { - // Smaller integer types are automatically promototed and `va_arg` - // should not be called on them. - bug!( - "va_arg got i{} but needs at least c_int (an i{})", - int_width, - target_c_int_width - ); - } - } - Primitive::Float(Float::F16) => { - bug!("the va_arg intrinsic does not support `f16`") - } - Primitive::Float(Float::F16B) => { - bug!("the va_arg intrinsic does not support `f16b`") - } - Primitive::Float(Float::F32) => { - // c_double is actually f32 on avr. - if self.cx().sess().target.arch != Arch::Avr { - bug!("the va_arg intrinsic does not support `f32` on this target") - } - } - Primitive::Float(Float::F64) => { - // 64-bit floats are always OK. - } - Primitive::Float(Float::F128) => { - // Supported on some targets, especially where long double is IEEE f128. - } - Primitive::Float(Float::PpcF128) => { - // Supported on powerpc and powerpc64 targets. - } - Primitive::Float(Float::X87F80) => { - // The user-facing x87_f80 type is accepted above. - bug!("the va_arg intrinsic does not support `x87_f80_raw`") - } - } - } - - emit_va_arg(self, args[0], result_layout) - } sym::volatile_load | sym::unaligned_volatile_load => { // Note that we cannot just load the `llvm_type` because we should never load non-scalars. diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 019567e834776..458175977e380 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -43,5 +43,4 @@ mod mono_item; mod type_; mod type_of; mod typetree; -mod va_arg; mod value; diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 57844d24f2be5..22b920e8bede2 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1632,12 +1632,6 @@ unsafe extern "C" { Else: Value<'ll>, Name: *const c_char, ) -> Value<'ll>; - pub(crate) fn LLVMBuildVAArg<'ll>( - B: &Builder<'ll>, - list: Value<'ll>, - Ty: Type<'ll>, - Name: *const c_char, - ) -> Value<'ll>; pub(crate) fn LLVMBuildExtractElement<'ll>( B: &Builder<'ll>, VecVal: Value<'ll>, diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index 1bfd977c2fce3..a95a081f88267 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -1,7 +1,8 @@ -use rustc_abi::{Align, FieldIdx, WrappingRange}; +use rustc_abi::{Align, BackendRepr, CVariadicStatus, FieldIdx, Float, Primitive, WrappingRange}; use rustc_middle::mir::SourceInfo; use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; use rustc_session::config::OptLevel; +use rustc_session::diagnostics::feature_err; use rustc_span::{ErrorGuaranteed, bug, span_bug, sym}; use rustc_target::spec::Arch; @@ -613,11 +614,98 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { }) } + sym::ptr_mask => { + OperandValue::Immediate(bx.ptr_mask(args[0].immediate(), args[1].immediate())) + } + sym::cold_path => { // This is a no-op. The intrinsic is just a hint to the optimizer. OperandValue::ZeroSized } + sym::va_arg => { + let target = &bx.tcx().sess.target; + let stability = target.supports_c_variadic_definitions(); + if let CVariadicStatus::Unstable { feature } = stability + && !bx.tcx().features().enabled(feature) + { + let msg = "C-variadic function definitions on this target are unstable"; + feature_err(bx.sess(), feature, span, msg).emit(); + } + + 'blk: { + // The backend_repr of x87_f80 is not a scalar, so it needs special-casing. + if result_layout.is_x87_f80(bx) { + break 'blk; + } + + let BackendRepr::Scalar(scalar) = result_layout.backend_repr else { + bug!("the va_arg intrinsic does not support non-scalar types") + }; + + // We reject types that would never be passed as varargs in C because + // they get promoted to a larger type, specifically integers smaller than + // c_int and float type smaller than c_double. + match scalar.primitive() { + Primitive::Pointer(_) => { + // Pointers are always OK. + } + Primitive::Bool => { + // Smaller integer types are automatically promototed and `va_arg` + // should not be called on them. + bug!("the va_arg intrinsic does not support `bool`"); + } + Primitive::Int(..) => { + let int_width = result_layout.size.bits(); + let target_c_int_width = bx.sess().target.options.c_int_width; + if int_width < u64::from(target_c_int_width) { + // Smaller integer types are automatically promototed and `va_arg` + // should not be called on them. + bug!( + "va_arg got i{} but needs at least c_int (an i{})", + int_width, + target_c_int_width + ); + } + } + Primitive::Float(Float::F16) => { + bug!("the va_arg intrinsic does not support `f16`") + } + Primitive::Float(Float::F16B) => { + bug!("the va_arg intrinsic does not support `f16b`") + } + Primitive::Float(Float::F32) => { + // c_double is actually f32 on avr. + if bx.sess().target.arch != Arch::Avr { + bug!("the va_arg intrinsic does not support `f32` on this target") + } + } + Primitive::Float(Float::F64) => { + // 64-bit floats are always OK. + } + Primitive::Float(Float::F128) => { + // Supported on some targets, especially where long double is IEEE f128. + } + Primitive::Float(Float::PpcF128) => { + // Supported on powerpc and powerpc64 targets. + } + Primitive::Float(Float::X87F80) => { + // The user-facing x87_f80 type is accepted above. + bug!("the va_arg intrinsic does not support `x87_f80_raw`") + } + } + } + + let res = super::va_arg::emit_va_arg(bx, args[0], result_layout); + if result_layout.is_aggregate() { + // Needed for `x87_f80`. + bx.store_to_place(res, result_place.expect("aggregate with no result place")); + return IntrinsicResult::WroteIntoPlace; + } else { + OperandValue::Immediate(res) + } + } + _ => { // Need to use backend-specific things in the implementation. let result = diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index a43afd176d81f..26e832aef2793 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -27,6 +27,7 @@ pub mod place; mod retag; mod rvalue; mod statement; +mod va_arg; pub use self::block::{intrinsic_return_struct_fields, store_cast, store_intrinsic_return_struct}; use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo}; diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_ssa/src/mir/va_arg.rs similarity index 87% rename from compiler/rustc_codegen_llvm/src/va_arg.rs rename to compiler/rustc_codegen_ssa/src/mir/va_arg.rs index 5213ffb7b4fe4..37fc73d169cf1 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_ssa/src/mir/va_arg.rs @@ -1,52 +1,47 @@ use rustc_abi::{ Align, BackendRepr, CVariadicStatus, Endian, Float, HasDataLayout, Integer, Primitive, Size, }; -use rustc_codegen_ssa::common::IntPredicate; -use rustc_codegen_ssa::mir::operand::OperandRef; -use rustc_codegen_ssa::traits::{ - BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, LayoutTypeCodegenMethods, -}; -use rustc_middle::ty::Ty; -use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_span::bug; use rustc_target::spec::{Arch, Env, LlvmAbi, RustcAbi, Target}; -use crate::builder::Builder; -use crate::llvm::{Type, Value}; +use crate::common::IntPredicate; +use crate::mir::operand::OperandRef; +use crate::traits::{ + BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, LayoutTypeCodegenMethods, + MiscCodegenMethods, +}; -fn round_up_to_alignment<'ll>( - bx: &mut Builder<'_, 'll, '_>, - mut value: Value<'ll>, +fn round_up_to_alignment<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + mut value: Bx::Value, align: Align, -) -> Value<'ll> { - value = bx.add(value, bx.cx().const_i32(align.bytes() as i32 - 1)); - bx.and(value, bx.cx().const_i32(-(align.bytes() as i32))) +) -> Bx::Value { + value = bx.add(value, bx.const_i32(align.bytes() as i32 - 1)); + bx.and(value, bx.const_i32(-(align.bytes() as i32))) } -fn round_pointer_up_to_alignment<'ll>( - bx: &mut Builder<'_, 'll, '_>, - addr: Value<'ll>, +fn round_pointer_up_to_alignment<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + addr: Bx::Value, align: Align, -) -> Value<'ll> { +) -> Bx::Value { let ptr = bx.inbounds_ptradd(addr, bx.const_i32(align.bytes() as i32 - 1)); - let pointer_width = bx.tcx().sess.target.pointer_width; + let pointer_width = bx.sess().target.pointer_width; let mask = align.bytes().wrapping_neg() & (u64::MAX >> (64 - pointer_width)); - bx.call_intrinsic( - "llvm.ptrmask", - &[bx.type_ptr(), bx.type_isize()], - &[ptr, bx.const_usize(mask)], - ) + + bx.ptr_mask(ptr, bx.const_usize(mask)) } /// A helper for backend_type that ensures we don't call it on non-primitive types. /// -/// Doing so is risky because LLVM and rustc's idea of how big or aligned the type +/// Doing so is risky because the backend's and rustc's idea of how big or aligned the type /// is might be different. -fn to_backend_type<'ll, 'tcx>( - bx: &Builder<'_, 'll, 'tcx>, +fn to_backend_type<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &Bx, ty_and_layout: TyAndLayout<'tcx>, -) -> Type<'ll> { - if ty_and_layout.is_x87_f80(bx.cx) { +) -> Bx::Type { + if ty_and_layout.is_x87_f80(bx) { bx.type_x87_f80() } else { assert!(ty_and_layout.backend_repr.is_scalar()); @@ -54,19 +49,19 @@ fn to_backend_type<'ll, 'tcx>( } } -fn emit_direct_ptr_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_direct_ptr_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, size: Size, align: Align, slot_size: Align, allow_higher_align: bool, force_right_adjust: bool, -) -> (Value<'ll>, Align) { +) -> (Bx::Value, Align) { let va_list_ty = bx.type_ptr(); let va_list_addr = list.immediate(); - let ptr_align_abi = bx.tcx().data_layout.pointer_align(); + let ptr_align_abi = bx.data_layout().pointer_align(); let ptr = bx.load(va_list_ty, va_list_addr, ptr_align_abi); let (addr, addr_align) = if allow_higher_align && align > slot_size { @@ -76,15 +71,15 @@ fn emit_direct_ptr_va_arg<'ll, 'tcx>( }; let aligned_size = size.align_to(slot_size).bytes() as i32; - let full_direct_size = bx.cx().const_i32(aligned_size); + let full_direct_size = bx.const_i32(aligned_size); let next = bx.inbounds_ptradd(addr, full_direct_size); bx.store(next, va_list_addr, ptr_align_abi); if size.bytes() < slot_size.bytes() - && bx.tcx().sess.target.endian == Endian::Big + && bx.sess().target.endian == Endian::Big && force_right_adjust { - let adjusted_size = bx.cx().const_i32((slot_size.bytes() - size.bytes()) as i32); + let adjusted_size = bx.const_i32((slot_size.bytes() - size.bytes()) as i32); let adjusted = bx.inbounds_ptradd(addr, adjusted_size); // We're in the middle of a slot now, so use the type's alignment, not the slot's. (adjusted, align) @@ -94,8 +89,8 @@ fn emit_direct_ptr_va_arg<'ll, 'tcx>( } /// Some backends apply special alignment rules to c-variadic arguments. -fn get_param_type_alignment<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, +fn get_param_type_alignment<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, layout: TyAndLayout<'tcx>, ) -> Align { if layout.is_x87_f80(bx) { @@ -106,7 +101,7 @@ fn get_param_type_alignment<'ll, 'tcx>( bug!("unexpected backend repr {:?}", layout.backend_repr); }; - match bx.cx.tcx.sess.target.arch { + match bx.sess().target.arch { Arch::PowerPC | Arch::PowerPC64 => match scalar.primitive() { Primitive::Bool => unreachable!(), Primitive::Int(integer, _) => match integer { @@ -118,7 +113,7 @@ fn get_param_type_alignment<'ll, 'tcx>( Float::F16 | Float::F16B | Float::F32 | Float::X87F80 => unreachable!(), Float::F64 | Float::F128 => { /* fall through */ } Float::PpcF128 => { - return if is_powerpc_softfloat_abi(&bx.cx.tcx.sess.target) { + return if is_powerpc_softfloat_abi(&bx.sess().target) { Align::FOUR } else { Align::EIGHT @@ -173,26 +168,22 @@ enum ForceRightAdjust { Yes, } -fn emit_ptr_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_ptr_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, pass_mode: PassMode, slot_size: SlotSize, allow_higher_align: AllowHigherAlign, force_right_adjust: ForceRightAdjust, -) -> Value<'ll> { +) -> Bx::Value { let indirect = matches!(pass_mode, PassMode::Indirect); let allow_higher_align = matches!(allow_higher_align, AllowHigherAlign::Yes); let force_right_adjust = matches!(force_right_adjust, ForceRightAdjust::Yes); let slot_size = Align::from_bytes(slot_size as u64).unwrap(); let (llty, size, align) = if indirect { - ( - to_backend_type(bx, bx.cx.layout_of(Ty::new_imm_ptr(bx.cx.tcx, layout.ty))), - bx.cx.data_layout().pointer_size(), - bx.cx.data_layout().pointer_align(), - ) + (bx.type_ptr(), bx.data_layout().pointer_size(), bx.data_layout().pointer_align()) } else { (to_backend_type(bx, layout), layout.size, get_param_type_alignment(bx, layout)) }; @@ -213,12 +204,12 @@ fn emit_ptr_va_arg<'ll, 'tcx>( } } -fn emit_aapcs_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_aapcs_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { - let dl = bx.cx.data_layout(); +) -> Bx::Value { + let dl = &bx.tcx().data_layout; // Implementation of the AAPCS64 calling convention for va_args see // https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst @@ -238,10 +229,10 @@ fn emit_aapcs_va_arg<'ll, 'tcx>( // Table 3, Mapping of C & C++ built-in data types let ptr_offset = 8; let i32_offset = 4; - let gr_top = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(ptr_offset)); - let vr_top = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * ptr_offset)); - let gr_offs = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(3 * ptr_offset)); - let vr_offs = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(3 * ptr_offset + i32_offset)); + let gr_top = bx.inbounds_ptradd(va_list_addr, bx.const_usize(ptr_offset)); + let vr_top = bx.inbounds_ptradd(va_list_addr, bx.const_usize(2 * ptr_offset)); + let gr_offs = bx.inbounds_ptradd(va_list_addr, bx.const_usize(3 * ptr_offset)); + let vr_offs = bx.inbounds_ptradd(va_list_addr, bx.const_usize(3 * ptr_offset + i32_offset)); let maybe_reg = bx.append_sibling_block("va_arg.maybe_reg"); let in_reg = bx.append_sibling_block("va_arg.in_reg"); @@ -288,14 +279,15 @@ fn emit_aapcs_va_arg<'ll, 'tcx>( // reg_value = *(@top + reg_off_v); let mut reg_addr = bx.ptradd(top, reg_off_v); - if bx.tcx().sess.target.endian == Endian::Big && layout.size.bytes() != slot_size { + if bx.sess().target.endian == Endian::Big && layout.size.bytes() != slot_size { // On big-endian systems the value is right-aligned in its slot. let offset = bx.const_i32((slot_size - layout.size.bytes()) as i32); reg_addr = bx.ptradd(reg_addr, offset); } let reg_type = to_backend_type(bx, layout); let reg_value = bx.load(reg_type, reg_addr, layout.align); - bx.br(end); + let mut phi = bx.new_phi(); + bx.br_with_phi(end, [(&mut phi, reg_value)]); // On Stack block bx.switch_to_block(on_stack); @@ -306,15 +298,15 @@ fn emit_aapcs_va_arg<'ll, 'tcx>( PassMode::Direct, SlotSize::Bytes8, AllowHigherAlign::Yes, - match bx.tcx().sess.target.endian { + match bx.sess().target.endian { Endian::Big => ForceRightAdjust::Yes, Endian::Little => ForceRightAdjust::No, }, ); - bx.br(end); + bx.br_with_phi(end, [(&mut phi, stack_value)]); bx.switch_to_block(end); - bx.phi(to_backend_type(bx, layout), &[reg_value, stack_value], &[in_reg, on_stack]) + bx.phi_output(phi) } fn is_powerpc_softfloat_abi(target: &Target) -> bool { @@ -330,12 +322,12 @@ fn is_powerpc_softfloat_abi(target: &Target) -> bool { } } -fn emit_powerpc_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_powerpc_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { - let dl = bx.cx.data_layout(); +) -> Bx::Value { + let dl = &bx.tcx().data_layout; // struct __va_list_tag { // unsigned char gpr; @@ -347,7 +339,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( let va_list_addr = list.immediate(); // Peel off any newtype wrappers. - let layout = layout.peel_transparent_wrappers_from_non_1zst(bx.cx); + let layout = layout.peel_transparent_wrappers_from_non_1zst(bx); // All instances of VaArgSafe are passed directly. let is_indirect = false; @@ -362,7 +354,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( _ => unreachable!("all instances of VaArgSafe are represented as scalars"), }; - let is_passed_in_fprs = !(is_int || is_powerpc_softfloat_abi(&bx.cx.tcx.sess.target)); + let is_passed_in_fprs = !(is_int || is_powerpc_softfloat_abi(&bx.sess().target)); let num_regs_addr = if !is_passed_in_fprs { va_list_addr // gpr @@ -383,7 +375,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( let reg_incr = layout.size.bytes().div_ceil(u64::from(reg_size)) as u8; let use_regs = bx.icmp(IntPredicate::IntULE, num_regs, bx.const_u8(max_regs - reg_incr)); - let ptr_align_abi = bx.tcx().data_layout.pointer_align(); + let ptr_align_abi = bx.data_layout().pointer_align(); let in_reg = bx.append_sibling_block("va_arg.in_reg"); let in_mem = bx.append_sibling_block("va_arg.in_mem"); @@ -391,32 +383,32 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( bx.cond_br(use_regs, in_reg, in_mem); - let reg_addr = { + let mut phi = bx.new_phi(); + + { bx.switch_to_block(in_reg); - let reg_save_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(1 + 1 + 2 + 4)); + let reg_save_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(1 + 1 + 2 + 4)); let mut reg_addr = bx.load(bx.type_ptr(), reg_save_area_ptr, ptr_align_abi); // Floating-point registers start after the general-purpose registers. if is_passed_in_fprs { - reg_addr = bx.inbounds_ptradd(reg_addr, bx.cx.const_usize(32)) + reg_addr = bx.inbounds_ptradd(reg_addr, bx.const_usize(32)) } // Get the address of the saved value by scaling the number of // registers we've used by the number of. - let reg_offset = bx.mul(num_regs, bx.cx().const_u8(reg_size)); + let reg_offset = bx.mul(num_regs, bx.const_u8(reg_size)); let reg_addr = bx.inbounds_ptradd(reg_addr, reg_offset); // Increase the used-register count. - let new_num_regs = bx.add(num_regs, bx.cx.const_u8(reg_incr)); + let new_num_regs = bx.add(num_regs, bx.const_u8(reg_incr)); bx.store(new_num_regs, num_regs_addr, Align::ONE); - bx.br(end); - - reg_addr - }; + bx.br_with_phi(end, [(&mut phi, reg_addr)]); + } - let mem_addr = { + { bx.switch_to_block(in_mem); bx.store(bx.const_u8(max_regs), num_regs_addr, Align::ONE); @@ -430,7 +422,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( dl.pointer_size() }; - let overflow_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(1 + 1 + 2)); + let overflow_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(1 + 1 + 2)); let mut overflow_area = bx.load(bx.type_ptr(), overflow_area_ptr, ptr_align_abi); // Round up address of argument to alignment @@ -445,27 +437,25 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( overflow_area = bx.inbounds_ptradd(overflow_area, bx.const_usize(size.bytes())); bx.store(overflow_area, overflow_area_ptr, ptr_align_abi); - bx.br(end); - - mem_addr - }; + bx.br_with_phi(end, [(&mut phi, mem_addr)]); + } // Return the appropriate result. bx.switch_to_block(end); - let val_addr = bx.phi(bx.type_ptr(), &[reg_addr, mem_addr], &[in_reg, in_mem]); + let val_addr = bx.phi_output(phi); let val_type = to_backend_type(bx, layout); let val_addr = - if is_indirect { bx.load(bx.cx.type_ptr(), val_addr, ptr_align_abi) } else { val_addr }; + if is_indirect { bx.load(bx.type_ptr(), val_addr, ptr_align_abi) } else { val_addr }; let align = get_param_type_alignment(bx, layout); bx.load(val_type, val_addr, align) } -fn emit_s390x_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_s390x_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { - let dl = bx.cx.data_layout(); +) -> Bx::Value { + let dl = &bx.tcx().data_layout; // Implementation of the s390x ELF ABI calling convention for va_args see // https://github.com/IBM/s390x-abi (chapter 1.2.4) @@ -483,10 +473,10 @@ fn emit_s390x_va_arg<'ll, 'tcx>( let i64_offset = 8; let ptr_offset = 8; let gpr = va_list_addr; - let fpr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(i64_offset)); - let overflow_arg_area = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * i64_offset)); + let fpr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(i64_offset)); + let overflow_arg_area = bx.inbounds_ptradd(va_list_addr, bx.const_usize(2 * i64_offset)); let reg_save_area = - bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * i64_offset + ptr_offset)); + bx.inbounds_ptradd(va_list_addr, bx.const_usize(2 * i64_offset + ptr_offset)); let in_reg = bx.append_sibling_block("va_arg.in_reg"); let in_mem = bx.append_sibling_block("va_arg.in_mem"); @@ -543,7 +533,8 @@ fn emit_s390x_va_arg<'ll, 'tcx>( // Update the register count. let new_reg_count_v = bx.add(reg_count_v, bx.const_u64(1)); bx.store(new_reg_count_v, reg_count, Align::from_bytes(8).unwrap()); - bx.br(end); + let mut phi = bx.new_phi(); + bx.br_with_phi(end, [(&mut phi, reg_addr)]); // Emit code to load the value if it was passed in memory. bx.switch_to_block(in_mem); @@ -554,26 +545,26 @@ fn emit_s390x_va_arg<'ll, 'tcx>( let mem_addr = bx.ptradd(arg_ptr_v, arg_off); // Update the argument overflow area pointer. - let arg_size = bx.cx().const_u64(padded_size); + let arg_size = bx.const_u64(padded_size); let new_arg_ptr_v = bx.inbounds_ptradd(arg_ptr_v, arg_size); bx.store(new_arg_ptr_v, overflow_arg_area, ptr_align_abi); - bx.br(end); + bx.br_with_phi(end, [(&mut phi, mem_addr)]); // Return the appropriate result. bx.switch_to_block(end); - let val_addr = bx.phi(bx.type_ptr(), &[reg_addr, mem_addr], &[in_reg, in_mem]); + let val_addr = bx.phi_output(phi); let val_type = to_backend_type(bx, layout); let val_addr = - if indirect { bx.load(bx.cx.type_ptr(), val_addr, ptr_align_abi) } else { val_addr }; + if indirect { bx.load(bx.type_ptr(), val_addr, ptr_align_abi) } else { val_addr }; bx.load(val_type, val_addr, layout.align) } -fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_x86_64_sysv64_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { - let dl = bx.cx.data_layout(); +) -> Bx::Value { + let dl = &bx.tcx().data_layout; // Implementation of the systemv x86_64 ABI calling convention for va_args, see // https://gitlab.com/x86-psABIs/x86-64-ABI (section 3.5.7). This implementation is heavily @@ -606,7 +597,7 @@ fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>( // #[repr(C)] // struct Foo([Empty; 8], i32); // ``` - let layout = layout.peel_transparent_wrappers_from_non_1zst(bx.cx); + let layout = layout.peel_transparent_wrappers_from_non_1zst(bx); // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed // in the registers. If not go to step 7. @@ -658,10 +649,10 @@ fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>( // We support x86_64-unknown-linux-gnux32 which uses 4-byte pointers. let unsigned_int_offset = 4; - let ptr_offset = bx.tcx().data_layout.pointer_size().bytes(); + let ptr_offset = bx.data_layout().pointer_size().bytes(); let gp_offset_ptr = va_list_addr; - let fp_offset_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(unsigned_int_offset)); + let fp_offset_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(unsigned_int_offset)); let gp_offset_v = bx.load(bx.type_i32(), gp_offset_ptr, Align::EIGHT); let fp_offset_v = bx.load(bx.type_i32(), fp_offset_ptr, Align::FOUR); @@ -700,7 +691,7 @@ fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>( // simple assembling of a structure from scattered addresses has many more // loads than necessary. Can we clean this up? let reg_save_area_ptr = - bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(2 * unsigned_int_offset + ptr_offset)); + bx.inbounds_ptradd(va_list_addr, bx.const_usize(2 * unsigned_int_offset + ptr_offset)); let reg_save_area_v = bx.load(bx.type_ptr(), reg_save_area_ptr, dl.pointer_align()); let reg_addr = match layout.layout.backend_repr() { @@ -716,11 +707,11 @@ fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>( Primitive::Bool => bug!("bool should not be allowed in va_arg"), }, BackendRepr::ScalarPair { a: scalar1, b: scalar2, b_offset: offset } => { - let ty_lo = bx.cx().scalar_pair_element_backend_type(layout, 0, false); - let ty_hi = bx.cx().scalar_pair_element_backend_type(layout, 1, false); + let ty_lo = bx.scalar_pair_element_backend_type(layout, 0, false); + let ty_hi = bx.scalar_pair_element_backend_type(layout, 1, false); - let align_lo = layout.field(bx.cx, 0).layout.align(); - let align_hi = layout.field(bx.cx, 1).layout.align(); + let align_lo = layout.field(bx, 0).layout.align(); + let align_hi = layout.field(bx, 1).layout.align(); match (scalar1.primitive(), scalar2.primitive()) { (Primitive::Float(_), Primitive::Float(_)) => { @@ -802,27 +793,28 @@ fn emit_x86_64_sysv64_va_arg<'ll, 'tcx>( bx.store(sum, fp_offset_ptr, Align::FOUR); } - bx.br(end); + let mut phi = bx.new_phi(); + bx.br_with_phi(end, [(&mut phi, reg_addr)]); bx.switch_to_block(in_mem); let mem_addr = x86_64_sysv64_va_arg_from_memory(bx, va_list_addr, layout); - bx.br(end); + bx.br_with_phi(end, [(&mut phi, mem_addr)]); bx.switch_to_block(end); let val_type = to_backend_type(bx, layout); - let val_addr = bx.phi(bx.type_ptr(), &[reg_addr, mem_addr], &[in_reg, in_mem]); + let val_addr = bx.phi_output(phi); bx.load(val_type, val_addr, layout.align) } /// Copy into a temporary if the type is more aligned than the register save area. -fn copy_to_temporary_if_more_aligned<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - reg_addr: Value<'ll>, +fn copy_to_temporary_if_more_aligned<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + reg_addr: Bx::Value, layout: TyAndLayout<'tcx>, src_align: Align, -) -> Value<'ll> { +) -> Bx::Value { if layout.layout.align > src_align { assert!(layout.ty.is_integral()); @@ -836,12 +828,12 @@ fn copy_to_temporary_if_more_aligned<'ll, 'tcx>( } } -fn x86_64_sysv64_va_arg_from_memory<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - va_list_addr: Value<'ll>, +fn x86_64_sysv64_va_arg_from_memory<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + va_list_addr: Bx::Value, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { - let dl = bx.cx.data_layout(); +) -> Bx::Value { + let dl = bx.data_layout(); let ptr_align_abi = dl.data_layout().pointer_align(); let overflow_arg_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(8)); @@ -875,11 +867,11 @@ fn x86_64_sysv64_va_arg_from_memory<'ll, 'tcx>( mem_addr } -fn emit_hexagon_va_arg_musl<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_hexagon_va_arg_musl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { +) -> Bx::Value { // Implementation of va_arg for Hexagon musl target. // Based on LLVM's HexagonBuiltinVaList implementation. // @@ -892,8 +884,8 @@ fn emit_hexagon_va_arg_musl<'ll, 'tcx>( // All variadic arguments are passed on the stack, but the musl implementation // uses a register save area for compatibility. let va_list_addr = list.immediate(); - let ptr_align_abi = bx.tcx().data_layout.pointer_align(); - let ptr_size = bx.tcx().data_layout.pointer_size().bytes(); + let ptr_align_abi = bx.data_layout().pointer_align(); + let ptr_size = bx.data_layout().pointer_size().bytes(); // Check if argument fits in register save area let maybe_reg = bx.append_sibling_block("va_arg.maybe_reg"); @@ -929,7 +921,8 @@ fn emit_hexagon_va_arg_musl<'ll, 'tcx>( let reg_value_addr = aligned_current; // Update current pointer bx.store(next_ptr, current_ptr_addr, ptr_align_abi); - bx.br(end); + let mut phi = bx.new_phi(); + bx.br_with_phi(end, [(&mut phi, reg_value_addr)]); // Load from overflow area (stack) bx.switch_to_block(from_overflow); @@ -945,26 +938,25 @@ fn emit_hexagon_va_arg_musl<'ll, 'tcx>( // IMPORTANT: Also update the current saved register area pointer to match // This synchronizes the pointers when switching to overflow area bx.store(next_overflow, current_ptr_addr, ptr_align_abi); - bx.br(end); + bx.br_with_phi(end, [(&mut phi, overflow_value_addr)]); // Return the value bx.switch_to_block(end); - let value_addr = - bx.phi(bx.type_ptr(), &[reg_value_addr, overflow_value_addr], &[maybe_reg, from_overflow]); + let value_addr = bx.phi_output(phi); bx.load(to_backend_type(bx, layout), value_addr, layout.align) } -fn emit_hexagon_va_arg_bare_metal<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_hexagon_va_arg_bare_metal<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { +) -> Bx::Value { // Implementation of va_arg for Hexagon bare-metal (non-musl) targets. // Based on LLVM's EmitVAArgForHexagon implementation. // // va_list is a simple pointer (char *) let va_list_addr = list.immediate(); - let ptr_align_abi = bx.tcx().data_layout.pointer_align(); + let ptr_align_abi = bx.data_layout().pointer_align(); // Load current pointer from va_list let current_ptr = bx.load(bx.type_ptr(), va_list_addr, ptr_align_abi); @@ -991,11 +983,11 @@ fn emit_hexagon_va_arg_bare_metal<'ll, 'tcx>( bx.load(to_backend_type(bx, layout), aligned_ptr, layout.align) } -fn emit_xtensa_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - list: OperandRef<'tcx, Value<'ll>>, +fn emit_xtensa_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + list: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { +) -> Bx::Value { // Implementation of va_arg for Xtensa. There doesn't seem to be an authoritative source for // this, other than "what GCC does". // @@ -1017,14 +1009,14 @@ fn emit_xtensa_va_arg<'ll, 'tcx>( let from_stack = bx.append_sibling_block("va_arg.from_stack"); let from_regsave = bx.append_sibling_block("va_arg.from_regsave"); let end = bx.append_sibling_block("va_arg.end"); - let ptr_align_abi = bx.tcx().data_layout.pointer_align(); + let ptr_align_abi = bx.data_layout().pointer_align(); // (*va).va_ndx let va_reg_offset = 4; let va_ndx_offset = va_reg_offset + 4; - let offset_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(va_ndx_offset)); + let offset_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(va_ndx_offset)); - let offset = bx.load(bx.type_i32(), offset_ptr, bx.tcx().data_layout.i32_align); + let offset = bx.load(bx.type_i32(), offset_ptr, bx.data_layout().i32_align); let offset = round_up_to_alignment(bx, offset, layout.align); let slot_size = layout.size.align_to(Align::FOUR).bytes() as i32; @@ -1043,10 +1035,11 @@ fn emit_xtensa_va_arg<'ll, 'tcx>( bx.store(offset_next, offset_ptr, ptr_align_abi); // (*va).va_reg - let regsave_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(va_reg_offset)); + let regsave_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(va_reg_offset)); let regsave_area = bx.load(bx.type_ptr(), regsave_area_ptr, ptr_align_abi); let regsave_value_ptr = bx.inbounds_ptradd(regsave_area, offset); - bx.br(end); + let mut phi = bx.new_phi(); + bx.br_with_phi(end, [(&mut phi, regsave_value_ptr)]); bx.switch_to_block(from_stack); @@ -1066,10 +1059,10 @@ fn emit_xtensa_va_arg<'ll, 'tcx>( bx.store(offset_next_corrected, offset_ptr, ptr_align_abi); // let stack_value_ptr = unsafe { (*va).va_stk.byte_add(offset_corrected) }; - let stack_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.cx.const_usize(0)); + let stack_area_ptr = bx.inbounds_ptradd(va_list_addr, bx.const_usize(0)); let stack_area = bx.load(bx.type_ptr(), stack_area_ptr, ptr_align_abi); let stack_value_ptr = bx.inbounds_ptradd(stack_area, offset_corrected); - bx.br(end); + bx.br_with_phi(end, [(&mut phi, stack_value_ptr)]); bx.switch_to_block(end); @@ -1082,9 +1075,8 @@ fn emit_xtensa_va_arg<'ll, 'tcx>( // } else { // unsafe { *stack_value_ptr } // } - assert!(bx.tcx().sess.target.endian == Endian::Little); - let value_ptr = - bx.phi(bx.type_ptr(), &[regsave_value_ptr, stack_value_ptr], &[from_regsave, from_stack]); + assert!(bx.sess().target.endian == Endian::Little); + let value_ptr = bx.phi_output(phi); bx.load(to_backend_type(bx, layout), value_ptr, layout.align) } @@ -1092,16 +1084,16 @@ fn emit_xtensa_va_arg<'ll, 'tcx>( /// is lacking in some instances, so we should only use it as a fallback. /// /// -pub(super) fn emit_va_arg<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - addr: OperandRef<'tcx, Value<'ll>>, +pub(super) fn emit_va_arg<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + addr: OperandRef<'tcx, Bx::Value>, layout: TyAndLayout<'tcx>, -) -> Value<'ll> { +) -> Bx::Value { // Some ABIs have special behavior for zero-sized types. currently `VaArgSafe` is not // implemented for any zero-sized types, so this assert should always hold. assert!(!layout.is_zst()); - let target = &bx.cx.tcx.sess.target; + let target = &bx.sess().target; let stability = target.supports_c_variadic_definitions(); match target.arch { @@ -1315,7 +1307,7 @@ pub(super) fn emit_va_arg<'ll, 'tcx>( // In big-endian mode the actual value is stored in the right side of the slot, meaning // that when the value is smaller than a slot, we need to adjust the pointer we read // to somewhere in the middle of the slot. - match bx.tcx().sess.target.endian { + match bx.sess().target.endian { Endian::Big => ForceRightAdjust::Yes, Endian::Little => ForceRightAdjust::No, }, diff --git a/compiler/rustc_codegen_ssa/src/traits/backend.rs b/compiler/rustc_codegen_ssa/src/traits/backend.rs index 2f28f86333230..28d8d1a9464e0 100644 --- a/compiler/rustc_codegen_ssa/src/traits/backend.rs +++ b/compiler/rustc_codegen_ssa/src/traits/backend.rs @@ -22,6 +22,7 @@ pub trait BackendTypes { type Function: CodegenObject; type BasicBlock: Copy; type Funclet; + type PhiBuilder; type Value: CodegenObject + PartialEq; type Type: CodegenObject + PartialEq; diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 9acfad1fb2a5e..9a61ded24e21a 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -71,6 +71,7 @@ pub trait BuilderMethods<'a, 'tcx>: Type = Self::Type, FunctionSignature = Self::FunctionSignature, Funclet = Self::Funclet, + PhiBuilder = Self::PhiBuilder, DIScope = Self::DIScope, DILocation = Self::DILocation, DIVariable = Self::DIVariable, @@ -96,6 +97,15 @@ pub trait BuilderMethods<'a, 'tcx>: fn br_with_attrs(&mut self, dest: Self::BasicBlock, _loop_hint_attrs: &[UnrollAttr]) { self.br(dest) } + /// Adding inputs to a phi is done as part of the branch as some backends (like + /// rustc_codegen_gcc) need to insert statements before the basic block terminator. Having a + /// combined `br_with_phi` operation prevents incorrect usage of the API even on backends + /// that don't need to insert any statements, like rustc_codegen_llvm. + fn br_with_phi( + &mut self, + dest: Self::BasicBlock, + phi_builders: [(&mut Self::PhiBuilder, Self::Value); N], + ); fn cond_br( &mut self, cond: Self::Value, @@ -369,6 +379,7 @@ pub trait BuilderMethods<'a, 'tcx>: fn inbounds_ptradd(&mut self, ptr: Self::Value, offset: Self::Value) -> Self::Value { self.inbounds_gep(Size::from_bytes(1), ptr, offset) } + fn ptr_mask(&mut self, ptr: Self::Value, mask: Self::Value) -> Self::Value; fn trunc(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; /// Produces the same value as [`Self::trunc`] (and defaults to that), @@ -578,7 +589,6 @@ pub trait BuilderMethods<'a, 'tcx>: else_val: Self::Value, ) -> Self::Value; - fn va_arg(&mut self, list: Self::Value, ty: Self::Type) -> Self::Value; fn extract_element(&mut self, vec: Self::Value, idx: Self::Value) -> Self::Value; fn vector_splat(&mut self, num_elts: u64, elt: Self::Value) -> Self::Value; fn extract_value(&mut self, agg_val: Self::Value, idx: u64) -> Self::Value; @@ -685,4 +695,8 @@ pub trait BuilderMethods<'a, 'tcx>: fn zext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn apply_attrs_to_cleanup_callsite(&mut self, llret: Self::Value); + + fn new_phi(&mut self) -> Self::PhiBuilder; + /// Gets the output of a phi. Must be called in the destination block. + fn phi_output(&mut self, phi: Self::PhiBuilder) -> Self::Value; } diff --git a/tests/run-make/c-link-to-rust-va-list-fn/rmake.rs b/tests/run-make/c-link-to-rust-va-list-fn/rmake.rs index 308733f0b4333..ef18555587203 100644 --- a/tests/run-make/c-link-to-rust-va-list-fn/rmake.rs +++ b/tests/run-make/c-link-to-rust-va-list-fn/rmake.rs @@ -8,8 +8,6 @@ //@ ignore-sgx: (x86 machine code cannot be directly executed) //@ ignore-pauthtest: (it requires non-trivial compilation of c sources, and only supports dynamic // linking, ignore the test). -// FIXME: Once GCC backend is fixed, remove this `ignore-backends`. -//@ ignore-backends: gcc use run_make_support::{cc, extra_c_flags, run, rustc, static_lib_name, target};