Skip to content

Commit

Permalink
Auto merge of rust-lang#129691 - matthiaskrgr:rollup-owlcr3m, r=matth…
Browse files Browse the repository at this point in the history
…iaskrgr

Rollup of 11 pull requests

Successful merges:

 - rust-lang#129421 (add repr to the allowlist for naked functions)
 - rust-lang#129480 (docs: correct panic conditions for rem_euclid and similar functions)
 - rust-lang#129551 (ub_checks intrinsics: fall back to cfg(ub_checks))
 - rust-lang#129608 (const-eval: do not make UbChecks behavior depend on current crate's flags)
 - rust-lang#129613 (interpret: do not make const-eval query result depend on tcx.sess)
 - rust-lang#129641 (rustdoc: fix missing resource suffix on `crates.js`)
 - rust-lang#129657 (Rename `BikeshedIntrinsicFrom` to `TransmuteFrom`)
 - rust-lang#129666 (interpret: add missing alignment check in raw_eq)
 - rust-lang#129667 (Rustc driver cleanup)
 - rust-lang#129668 (Fix Pin::set bounds regression)
 - rust-lang#129686 (coverage: Rename `CodeRegion` to `SourceRegion`)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Aug 28, 2024
2 parents ac77e88 + 4854fa7 commit 100fde5
Show file tree
Hide file tree
Showing 145 changed files with 899 additions and 701 deletions.
7 changes: 4 additions & 3 deletions compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use rustc_middle::mir::coverage::{
CodeRegion, ConditionInfo, CounterId, CovTerm, DecisionInfo, ExpressionId, MappingKind,
ConditionInfo, CounterId, CovTerm, DecisionInfo, ExpressionId, MappingKind, SourceRegion,
};

/// Must match the layout of `LLVMRustCounterKind`.
Expand Down Expand Up @@ -236,9 +236,10 @@ impl CounterMappingRegion {
pub(crate) fn from_mapping(
mapping_kind: &MappingKind,
local_file_id: u32,
code_region: &CodeRegion,
source_region: &SourceRegion,
) -> Self {
let &CodeRegion { file_name: _, start_line, start_col, end_line, end_col } = code_region;
let &SourceRegion { file_name: _, start_line, start_col, end_line, end_col } =
source_region;
match *mapping_kind {
MappingKind::Code(term) => Self::code_region(
Counter::from_term(term),
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxIndexSet;
use rustc_index::bit_set::BitSet;
use rustc_middle::mir::coverage::{
CodeRegion, CounterId, CovTerm, Expression, ExpressionId, FunctionCoverageInfo, Mapping,
MappingKind, Op,
CounterId, CovTerm, Expression, ExpressionId, FunctionCoverageInfo, Mapping, MappingKind, Op,
SourceRegion,
};
use rustc_middle::ty::Instance;
use rustc_span::Symbol;
Expand Down Expand Up @@ -201,7 +201,7 @@ impl<'tcx> FunctionCoverage<'tcx> {

/// Returns an iterator over all filenames used by this function's mappings.
pub(crate) fn all_file_names(&self) -> impl Iterator<Item = Symbol> + Captures<'_> {
self.function_coverage_info.mappings.iter().map(|mapping| mapping.code_region.file_name)
self.function_coverage_info.mappings.iter().map(|mapping| mapping.source_region.file_name)
}

/// Convert this function's coverage expression data into a form that can be
Expand Down Expand Up @@ -230,12 +230,12 @@ impl<'tcx> FunctionCoverage<'tcx> {
/// that will be used by `mapgen` when preparing for FFI.
pub(crate) fn counter_regions(
&self,
) -> impl Iterator<Item = (MappingKind, &CodeRegion)> + ExactSizeIterator {
) -> impl Iterator<Item = (MappingKind, &SourceRegion)> + ExactSizeIterator {
self.function_coverage_info.mappings.iter().map(move |mapping| {
let Mapping { kind, code_region } = mapping;
let Mapping { kind, source_region } = mapping;
let kind =
kind.map_terms(|term| if self.is_zero_term(term) { CovTerm::Zero } else { term });
(kind, code_region)
(kind, source_region)
})
}

Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_const_eval/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -402,9 +402,6 @@ const_eval_unallowed_mutable_refs =
const_eval_unallowed_op_in_const_context =
{$msg}
const_eval_unavailable_target_features_for_fn =
calling a function that requires unavailable target features: {$unavailable_feats}
const_eval_uninhabited_enum_variant_read =
read discriminant of an uninhabited enum variant
const_eval_uninhabited_enum_variant_written =
Expand Down
44 changes: 7 additions & 37 deletions compiler/rustc_const_eval/src/interpret/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,34 +311,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
Ok(())
}

fn check_fn_target_features(&self, instance: ty::Instance<'tcx>) -> InterpResult<'tcx, ()> {
// Calling functions with `#[target_feature]` is not unsafe on WASM, see #84988
let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
if !self.tcx.sess.target.is_like_wasm
&& attrs
.target_features
.iter()
.any(|feature| !self.tcx.sess.target_features.contains(&feature.name))
{
throw_ub_custom!(
fluent::const_eval_unavailable_target_features_for_fn,
unavailable_feats = attrs
.target_features
.iter()
.filter(|&feature| !feature.implied
&& !self.tcx.sess.target_features.contains(&feature.name))
.fold(String::new(), |mut s, feature| {
if !s.is_empty() {
s.push_str(", ");
}
s.push_str(feature.name.as_str());
s
}),
);
}
Ok(())
}

/// The main entry point for creating a new stack frame: performs ABI checks and initializes
/// arguments.
#[instrument(skip(self), level = "trace")]
Expand All @@ -360,20 +332,18 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
throw_unsup_format!("calling a c-variadic function is not supported");
}

if M::enforce_abi(self) {
if caller_fn_abi.conv != callee_fn_abi.conv {
throw_ub_custom!(
fluent::const_eval_incompatible_calling_conventions,
callee_conv = format!("{:?}", callee_fn_abi.conv),
caller_conv = format!("{:?}", caller_fn_abi.conv),
)
}
if caller_fn_abi.conv != callee_fn_abi.conv {
throw_ub_custom!(
fluent::const_eval_incompatible_calling_conventions,
callee_conv = format!("{:?}", callee_fn_abi.conv),
caller_conv = format!("{:?}", caller_fn_abi.conv),
)
}

// Check that all target features required by the callee (i.e., from
// the attribute `#[target_feature(enable = ...)]`) are enabled at
// compile time.
self.check_fn_target_features(instance)?;
M::check_fn_target_features(self, instance)?;

if !callee_fn_abi.can_unwind {
// The callee cannot unwind, so force the `Unreachable` unwind handling.
Expand Down
10 changes: 5 additions & 5 deletions compiler/rustc_const_eval/src/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,19 +684,19 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
assert!(layout.is_sized());

let get_bytes = |this: &InterpCx<'tcx, M>,
op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
size|
op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
-> InterpResult<'tcx, &[u8]> {
let ptr = this.read_pointer(op)?;
let Some(alloc_ref) = self.get_ptr_alloc(ptr, size)? else {
this.check_ptr_align(ptr, layout.align.abi)?;
let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
// zero-sized access
return Ok(&[]);
};
alloc_ref.get_bytes_strip_provenance()
};

let lhs_bytes = get_bytes(self, lhs, layout.size)?;
let rhs_bytes = get_bytes(self, rhs, layout.size)?;
let lhs_bytes = get_bytes(self, lhs)?;
let rhs_bytes = get_bytes(self, rhs)?;
Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
}
}
32 changes: 27 additions & 5 deletions compiler/rustc_const_eval/src/interpret/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,6 @@ pub trait Machine<'tcx>: Sized {
false
}

/// Whether function calls should be [ABI](CallAbi)-checked.
fn enforce_abi(_ecx: &InterpCx<'tcx, Self>) -> bool {
true
}

/// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
/// check for overflow.
fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool;
Expand Down Expand Up @@ -238,6 +233,13 @@ pub trait Machine<'tcx>: Sized {
unwind: mir::UnwindAction,
) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>>;

/// Check whether the given function may be executed on the current machine, in terms of the
/// target features is requires.
fn check_fn_target_features(
_ecx: &InterpCx<'tcx, Self>,
_instance: ty::Instance<'tcx>,
) -> InterpResult<'tcx>;

/// Called to evaluate `Assert` MIR terminators that trigger a panic.
fn assert_panic(
ecx: &mut InterpCx<'tcx, Self>,
Expand Down Expand Up @@ -280,6 +282,9 @@ pub trait Machine<'tcx>: Sized {
Ok(())
}

/// Determines the result of a `NullaryOp::UbChecks` invocation.
fn ub_checks(_ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool>;

/// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
/// You can use this to detect long or endlessly running programs.
#[inline]
Expand Down Expand Up @@ -614,6 +619,16 @@ pub macro compile_time_machine(<$tcx: lifetime>) {
unreachable!("unwinding cannot happen during compile-time evaluation")
}

#[inline(always)]
fn check_fn_target_features(
_ecx: &InterpCx<$tcx, Self>,
_instance: ty::Instance<$tcx>,
) -> InterpResult<$tcx> {
// For now we don't do any checking here. We can't use `tcx.sess` because that can differ
// between crates, and we need to ensure that const-eval always behaves the same.
Ok(())
}

#[inline(always)]
fn call_extra_fn(
_ecx: &mut InterpCx<$tcx, Self>,
Expand All @@ -627,6 +642,13 @@ pub macro compile_time_machine(<$tcx: lifetime>) {
match fn_val {}
}

#[inline(always)]
fn ub_checks(_ecx: &InterpCx<$tcx, Self>) -> InterpResult<$tcx, bool> {
// We can't look at `tcx.sess` here as that can differ across crates, which can lead to
// unsound differences in evaluating the same constant at different instantiation sites.
Ok(true)
}

#[inline(always)]
fn adjust_global_allocation<'b>(
_ecx: &InterpCx<$tcx, Self>,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/interpret/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
self.tcx.offset_of_subfield(self.param_env, layout, fields.iter()).bytes();
ImmTy::from_uint(val, usize_layout())
}
UbChecks => ImmTy::from_bool(self.tcx.sess.ub_checks(), *self.tcx),
UbChecks => ImmTy::from_bool(M::ub_checks(self)?, *self.tcx),
})
}
}
65 changes: 36 additions & 29 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,13 +393,17 @@ fn run_compiler(

let linker = compiler.enter(|queries| {
let early_exit = || early_exit().map(|_| None);

// Parse the crate root source code (doesn't parse submodules yet)
// Everything else is parsed during macro expansion.
queries.parse()?;

if let Some(ppm) = &sess.opts.pretty {
if ppm.needs_ast_map() {
// If pretty printing is requested: Figure out the representation, print it and exit
if let Some(pp_mode) = sess.opts.pretty {
if pp_mode.needs_ast_map() {
queries.global_ctxt()?.enter(|tcx| {
tcx.ensure().early_lint_checks(());
pretty::print(sess, *ppm, pretty::PrintExtra::NeedsAstMap { tcx });
pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
Ok(())
})?;

Expand All @@ -410,7 +414,7 @@ fn run_compiler(
let krate = queries.parse()?;
pretty::print(
sess,
*ppm,
pp_mode,
pretty::PrintExtra::AfterParsing { krate: &*krate.borrow() },
);
}
Expand Down Expand Up @@ -465,12 +469,8 @@ fn run_compiler(
linker.link(sess, codegen_backend)?
}

if sess.opts.unstable_opts.print_fuel.is_some() {
eprintln!(
"Fuel used by {}: {}",
sess.opts.unstable_opts.print_fuel.as_ref().unwrap(),
sess.print_fuel.load(Ordering::SeqCst)
);
if let Some(fuel) = sess.opts.unstable_opts.print_fuel.as_deref() {
eprintln!("Fuel used by {}: {}", fuel, sess.print_fuel.load(Ordering::SeqCst));
}

Ok(())
Expand All @@ -487,36 +487,43 @@ fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileNa
(odir, ofile)
}

// Extract input (string or file and optional path) from matches.
/// Extract input (string or file and optional path) from matches.
/// This handles reading from stdin if `-` is provided.
fn make_input(
early_dcx: &EarlyDiagCtxt,
free_matches: &[String],
) -> Result<Option<Input>, ErrorGuaranteed> {
let [ifile] = free_matches else { return Ok(None) };
if ifile == "-" {
let mut src = String::new();
if io::stdin().read_to_string(&mut src).is_err() {
// Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8).
let reported =
early_dcx.early_err("couldn't read from stdin, as it did not contain valid UTF-8");
return Err(reported);
}
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
let [input_file] = free_matches else { return Ok(None) };

if input_file != "-" {
// Normal `Input::File`
return Ok(Some(Input::File(PathBuf::from(input_file))));
}

// read from stdin as `Input::Str`
let mut input = String::new();
if io::stdin().read_to_string(&mut input).is_err() {
// Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8).
let reported =
early_dcx.early_err("couldn't read from stdin, as it did not contain valid UTF-8");
return Err(reported);
}

let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
Ok(path) => {
let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
"when UNSTABLE_RUSTDOC_TEST_PATH is set \
UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
);
let line = isize::from_str_radix(&line, 10)
.expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
Ok(Some(Input::Str { name: file_name, input: src }))
} else {
Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src }))
FileName::doc_test_source_code(PathBuf::from(path), line)
}
} else {
Ok(Some(Input::File(PathBuf::from(ifile))))
}
Err(_) => FileName::anon_source_code(&input),
};

Ok(Some(Input::Str { name, input }))
}

/// Whether to stop or continue compilation.
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_middle/src/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ macro_rules! arena_types {
)>,
[] crate_for_resolver: rustc_data_structures::steal::Steal<(rustc_ast::Crate, rustc_ast::AttrVec)>,
[] resolutions: rustc_middle::ty::ResolverGlobalCtxt,
[decode] code_region: rustc_middle::mir::coverage::CodeRegion,
[] const_allocs: rustc_middle::mir::interpret::Allocation,
[] region_scope_tree: rustc_middle::middle::region::ScopeTree,
// Required for the incremental on-disk cache
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_middle/src/mir/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,15 +163,15 @@ impl Debug for CoverageKind {

#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, Eq, PartialOrd, Ord)]
#[derive(TypeFoldable, TypeVisitable)]
pub struct CodeRegion {
pub struct SourceRegion {
pub file_name: Symbol,
pub start_line: u32,
pub start_col: u32,
pub end_line: u32,
pub end_col: u32,
}

impl Debug for CodeRegion {
impl Debug for SourceRegion {
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
write!(
fmt,
Expand Down Expand Up @@ -242,7 +242,7 @@ impl MappingKind {
#[derive(TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)]
pub struct Mapping {
pub kind: MappingKind,
pub code_region: CodeRegion,
pub source_region: SourceRegion,
}

/// Stores per-function coverage information attached to a `mir::Body`,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,8 +547,8 @@ fn write_function_coverage_info(
for (id, expression) in expressions.iter_enumerated() {
writeln!(w, "{INDENT}coverage {id:?} => {expression:?};")?;
}
for coverage::Mapping { kind, code_region } in mappings {
writeln!(w, "{INDENT}coverage {kind:?} => {code_region:?};")?;
for coverage::Mapping { kind, source_region } in mappings {
writeln!(w, "{INDENT}coverage {kind:?} => {source_region:?};")?;
}
writeln!(w)?;

Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_middle/src/ty/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,6 @@ impl_decodable_via_ref! {
&'tcx traits::ImplSource<'tcx, ()>,
&'tcx mir::Body<'tcx>,
&'tcx mir::BorrowCheckResult<'tcx>,
&'tcx mir::coverage::CodeRegion,
&'tcx ty::List<ty::BoundVariableKind>,
&'tcx ty::ListWithCachedTypeInfo<ty::Clause<'tcx>>,
&'tcx ty::List<FieldIdx>,
Expand Down
Loading

0 comments on commit 100fde5

Please sign in to comment.