Skip to content

Commit b44f6db

Browse files
committed
Add #[rustc_intrinsic_const_vector_arg] to allow vectors to be passed as constants
This allows constant vectors using a repr(simd) type to be propagated through to the backend by reusing the functionality used to do a similar thing for the simd_shuffle intrinsic. fix #118209
1 parent 0011fac commit b44f6db

File tree

24 files changed

+460
-33
lines changed

24 files changed

+460
-33
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -3502,6 +3502,7 @@ dependencies = [
35023502
"either",
35033503
"itertools",
35043504
"polonius-engine",
3505+
"rustc_ast",
35053506
"rustc_data_structures",
35063507
"rustc_errors",
35073508
"rustc_fluent_macro",

compiler/rustc_borrowck/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ edition = "2021"
88
either = "1.5.0"
99
itertools = "0.11"
1010
polonius-engine = "0.13.0"
11+
rustc_ast = { path = "../rustc_ast" }
1112
rustc_data_structures = { path = "../rustc_data_structures" }
1213
rustc_errors = { path = "../rustc_errors" }
1314
rustc_fluent_macro = { path = "../rustc_fluent_macro" }

compiler/rustc_borrowck/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ borrowck_higher_ranked_lifetime_error =
7171
borrowck_higher_ranked_subtype_error =
7272
higher-ranked subtype error
7373
74+
borrowck_intrinsic_const_vector_arg_non_const = argument at index {$index} must be a constant
75+
7476
borrowck_lifetime_constraints_error =
7577
lifetime may not live long enough
7678

compiler/rustc_borrowck/src/session_diagnostics.rs

+8
Original file line numberDiff line numberDiff line change
@@ -459,3 +459,11 @@ pub(crate) struct SimdShuffleLastConst {
459459
#[primary_span]
460460
pub span: Span,
461461
}
462+
463+
#[derive(Diagnostic)]
464+
#[diag(borrowck_intrinsic_const_vector_arg_non_const)]
465+
pub(crate) struct IntrinsicConstVectorArgNonConst {
466+
#[primary_span]
467+
pub span: Span,
468+
pub index: u128,
469+
}

compiler/rustc_borrowck/src/type_check/mod.rs

+32-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
5151
use rustc_mir_dataflow::move_paths::MoveData;
5252
use rustc_mir_dataflow::ResultsCursor;
5353

54-
use crate::session_diagnostics::{MoveUnsized, SimdShuffleLastConst};
54+
use crate::session_diagnostics::{
55+
IntrinsicConstVectorArgNonConst, MoveUnsized, SimdShuffleLastConst,
56+
};
5557
use crate::{
5658
borrow_set::BorrowSet,
5759
constraints::{OutlivesConstraint, OutlivesConstraintSet},
@@ -1613,6 +1615,35 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
16131615
}
16141616
_ => {}
16151617
}
1618+
} else if let Some(attr) =
1619+
self.tcx().get_attr(def_id, sym::rustc_intrinsic_const_vector_arg)
1620+
{
1621+
match attr.meta_item_list() {
1622+
Some(items) => {
1623+
items.into_iter().for_each(|item: rustc_ast::NestedMetaItem| match item {
1624+
rustc_ast::NestedMetaItem::Lit(rustc_ast::MetaItemLit {
1625+
kind: rustc_ast::LitKind::Int(index, _),
1626+
..
1627+
}) => {
1628+
if index >= args.len() as u128 {
1629+
span_mirbug!(self, term, "index out of bounds");
1630+
} else {
1631+
if !matches!(args[index as usize], Operand::Constant(_)) {
1632+
self.tcx().sess.emit_err(IntrinsicConstVectorArgNonConst {
1633+
span: term.source_info.span,
1634+
index,
1635+
});
1636+
}
1637+
}
1638+
}
1639+
_ => {
1640+
span_mirbug!(self, term, "invalid index");
1641+
}
1642+
});
1643+
}
1644+
// Error is reported by `rustc_attr!`
1645+
None => (),
1646+
}
16161647
}
16171648
}
16181649
debug!(?func_ty);

compiler/rustc_codegen_gcc/src/common.rs

+5
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,11 @@ impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
159159
self.context.new_struct_constructor(None, struct_type.as_type(), None, values)
160160
}
161161

162+
fn const_vector(&self, values: &[RValue<'gcc>]) -> RValue<'gcc> {
163+
let typ = self.type_vector(values[0].get_type(), values.len() as u64);
164+
self.context.new_rvalue_from_vector(None, typ, values)
165+
}
166+
162167
fn const_to_opt_uint(&self, _v: RValue<'gcc>) -> Option<u64> {
163168
// TODO(antoyo)
164169
None

compiler/rustc_codegen_llvm/src/common.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,6 @@ impl<'ll> CodegenCx<'ll, '_> {
9898
unsafe { llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint) }
9999
}
100100

101-
pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
102-
unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
103-
}
104-
105101
pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
106102
bytes_in_context(self.llcx, bytes)
107103
}
@@ -217,6 +213,10 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
217213
struct_in_context(self.llcx, elts, packed)
218214
}
219215

216+
fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
217+
unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
218+
}
219+
220220
fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
221221
try_as_const_integral(v).and_then(|v| unsafe {
222222
let mut i = 0u64;

compiler/rustc_codegen_ssa/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ codegen_ssa_cgu_not_recorded =
1616
1717
codegen_ssa_check_installed_visual_studio = please ensure that Visual Studio 2017 or later, or Build Tools for Visual Studio were installed with the Visual C++ option.
1818
19+
codegen_ssa_const_vector_evaluation = could not evaluate constant vector at compile time
20+
1921
codegen_ssa_copy_path = could not copy {$from} to {$to}: {$error}
2022
2123
codegen_ssa_copy_path_buf = unable to copy {$source_file} to {$output_path}: {$error}

compiler/rustc_codegen_ssa/src/errors.rs

+7
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,13 @@ pub struct ShuffleIndicesEvaluation {
594594
pub span: Span,
595595
}
596596

597+
#[derive(Diagnostic)]
598+
#[diag(codegen_ssa_const_vector_evaluation)]
599+
pub struct ConstVectorEvaluation {
600+
#[primary_span]
601+
pub span: Span,
602+
}
603+
597604
#[derive(Diagnostic)]
598605
#[diag(codegen_ssa_missing_memory_ordering)]
599606
pub struct MissingMemoryOrdering;

compiler/rustc_codegen_ssa/src/mir/block.rs

+52-3
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ use super::{CachedLlbb, FunctionCx, LocalRef};
55

66
use crate::base;
77
use crate::common::{self, IntPredicate};
8+
use crate::errors;
89
use crate::meth;
910
use crate::traits::*;
1011
use crate::MemFlags;
1112

1213
use rustc_ast as ast;
13-
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
14+
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, LitKind, MetaItemLit, NestedMetaItem};
1415
use rustc_hir::lang_items::LangItem;
1516
use rustc_middle::mir::{self, AssertKind, SwitchTargets, UnwindTerminateReason};
1617
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
@@ -864,7 +865,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
864865
// promotes any complex rvalues to constants.
865866
if i == 2 && intrinsic == sym::simd_shuffle {
866867
if let mir::Operand::Constant(constant) = &arg.node {
867-
let (llval, ty) = self.simd_shuffle_indices(bx, constant);
868+
let (llval, ty) = self.early_evaluate_const_vector(bx, constant);
869+
let llval = llval.unwrap_or_else(|| {
870+
bx.tcx().sess.emit_err(errors::ShuffleIndicesEvaluation {
871+
span: constant.span,
872+
});
873+
// We've errored, so we don't have to produce working code.
874+
let llty = bx.backend_type(bx.layout_of(ty));
875+
bx.const_undef(llty)
876+
});
868877
return OperandRef {
869878
val: Immediate(llval),
870879
layout: bx.layout_of(ty),
@@ -908,9 +917,49 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
908917
(args, None)
909918
};
910919

920+
let const_vec_arg_indexes = (|| {
921+
if let Some(def) = def
922+
&& let Some(attr) =
923+
bx.tcx().get_attr(def.def_id(), sym::rustc_intrinsic_const_vector_arg)
924+
{
925+
attr.meta_item_list()
926+
.iter()
927+
.flatten()
928+
.map(|item: &NestedMetaItem| match item {
929+
NestedMetaItem::Lit(MetaItemLit {
930+
kind: LitKind::Int(index, _), ..
931+
}) => *index as usize,
932+
_ => span_bug!(item.span(), "attribute argument must be an integer"),
933+
})
934+
.collect()
935+
} else {
936+
Vec::<usize>::new()
937+
}
938+
})();
939+
911940
let mut copied_constant_arguments = vec![];
912941
'make_args: for (i, arg) in first_args.iter().enumerate() {
913-
let mut op = self.codegen_operand(bx, &arg.node);
942+
let mut op = if const_vec_arg_indexes.contains(&i) {
943+
// Force the specified argument to be constant by using const-qualification to promote any complex rvalues to constant.
944+
if let mir::Operand::Constant(constant) = &arg.node
945+
&& constant.ty().is_simd()
946+
{
947+
let (llval, ty) = self.early_evaluate_const_vector(bx, &constant);
948+
let llval = llval.unwrap_or_else(|| {
949+
bx.tcx()
950+
.sess
951+
.emit_err(errors::ConstVectorEvaluation { span: constant.span });
952+
// We've errored, so we don't have to produce working code.
953+
let llty = bx.backend_type(bx.layout_of(ty));
954+
bx.const_undef(llty)
955+
});
956+
OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) }
957+
} else {
958+
span_bug!(span, "argument at {i} must be a constant vector");
959+
}
960+
} else {
961+
self.codegen_operand(bx, &arg.node)
962+
};
914963

915964
if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
916965
match op.val {

compiler/rustc_codegen_ssa/src/mir/constant.rs

+17-19
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::errors;
21
use crate::mir::operand::OperandRef;
32
use crate::traits::*;
43
use rustc_middle::mir;
@@ -28,7 +27,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
2827
.expect("erroneous constant not captured by required_consts")
2928
}
3029

31-
/// This is a convenience helper for `simd_shuffle_indices`. It has the precondition
30+
/// This is a convenience helper for `early_evaluate_const_vector`. It has the precondition
3231
/// that the given `constant` is an `Const::Unevaluated` and must be convertible to
3332
/// a `ValTree`. If you want a more general version of this, talk to `wg-const-eval` on zulip.
3433
///
@@ -63,19 +62,20 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
6362
)
6463
}
6564

66-
/// process constant containing SIMD shuffle indices
67-
pub fn simd_shuffle_indices(
65+
/// process constant SIMD vector or constant containing SIMD shuffle indices
66+
pub fn early_evaluate_const_vector(
6867
&mut self,
6968
bx: &Bx,
7069
constant: &mir::ConstOperand<'tcx>,
71-
) -> (Bx::Value, Ty<'tcx>) {
70+
) -> (Option<Bx::Value>, Ty<'tcx>) {
7271
let ty = self.monomorphize(constant.ty());
73-
let val = self
74-
.eval_unevaluated_mir_constant_to_valtree(constant)
75-
.ok()
76-
.flatten()
77-
.map(|val| {
78-
let field_ty = ty.builtin_index().unwrap();
72+
let field_ty = if ty.is_simd() {
73+
ty.simd_size_and_type(bx.tcx()).1
74+
} else {
75+
ty.builtin_index().unwrap()
76+
};
77+
let val =
78+
self.eval_unevaluated_mir_constant_to_valtree(constant).ok().flatten().map(|val| {
7979
let values: Vec<_> = val
8080
.unwrap_branch()
8181
.iter()
@@ -87,17 +87,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
8787
};
8888
bx.scalar_to_backend(prim, scalar, bx.immediate_backend_type(layout))
8989
} else {
90-
bug!("simd shuffle field {:?}", field)
90+
bug!("field is not a scalar {:?}", field)
9191
}
9292
})
9393
.collect();
94-
bx.const_struct(&values, false)
95-
})
96-
.unwrap_or_else(|| {
97-
bx.tcx().dcx().emit_err(errors::ShuffleIndicesEvaluation { span: constant.span });
98-
// We've errored, so we don't have to produce working code.
99-
let llty = bx.backend_type(bx.layout_of(ty));
100-
bx.const_undef(llty)
94+
if ty.is_simd() {
95+
bx.const_vector(&values)
96+
} else {
97+
bx.const_struct(&values, false)
98+
}
10199
});
102100
(val, ty)
103101
}

compiler/rustc_codegen_ssa/src/traits/consts.rs

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pub trait ConstMethods<'tcx>: BackendTypes {
2828

2929
fn const_str(&self, s: &str) -> (Self::Value, Self::Value);
3030
fn const_struct(&self, elts: &[Self::Value], packed: bool) -> Self::Value;
31+
fn const_vector(&self, elts: &[Self::Value]) -> Self::Value;
3132

3233
fn const_to_opt_uint(&self, v: Self::Value) -> Option<u64>;
3334
fn const_to_opt_u128(&self, v: Self::Value, sign_ext: bool) -> Option<u128>;

compiler/rustc_feature/src/builtin_attrs.rs

+3
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,9 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
654654
rustc_attr!(
655655
rustc_const_panic_str, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE
656656
),
657+
rustc_attr!(
658+
rustc_intrinsic_const_vector_arg, Normal, template!(List: "arg1_index, arg2_index, ..."), ErrorFollowing, INTERNAL_UNSTABLE
659+
),
657660

658661
// ==========================================================================
659662
// Internal attributes, Layout related:

compiler/rustc_passes/messages.ftl

+12
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,18 @@ passes_rustc_allow_const_fn_unstable =
609609
passes_rustc_dirty_clean =
610610
attribute requires -Z query-dep-graph to be enabled
611611
612+
passes_rustc_intrinsic_const_vector_arg =
613+
attribute should be applied to functions in `extern "unadjusted"` modules
614+
.label = not a function in an `extern "unadjusted"` module
615+
616+
passes_rustc_intrinsic_const_vector_arg_invalid = attribute requires a parameter index
617+
618+
passes_rustc_intrinsic_const_vector_arg_non_vector = parameter at index {$index} must be a simd type
619+
.label = parameter is a non-simd type
620+
621+
passes_rustc_intrinsic_const_vector_arg_out_of_bounds = function does not have a parameter at index {$index}
622+
.label = function has {$arg_count} arguments
623+
612624
passes_rustc_layout_scalar_valid_range_arg =
613625
expected exactly one integer literal argument
614626

0 commit comments

Comments
 (0)