Skip to content

Commit

Permalink
Auto merge of rust-lang#136482 - jieyouxu:rollup-ffa9eh8, r=jieyouxu
Browse files Browse the repository at this point in the history
Rollup of 8 pull requests

Successful merges:

 - rust-lang#134807 (fix(rustdoc): always use a channel when linking to doc.rust-lang.org)
 - rust-lang#134814 (Add `kl` and `widekl` target features, and the feature gate)
 - rust-lang#135836 (bootstrap: only build `crt{begin,end}.o` when compiling to MUSL)
 - rust-lang#136022 (Port ui/simd tests to use the intrinsic macro)
 - rust-lang#136235 (Pretty print pattern type values with transmute if they don't satisfy their pattern)
 - rust-lang#136309 (set rustc dylib on manually constructed rustc command)
 - rust-lang#136392 (bootstrap: add wrapper macros for `feature = "tracing"`-gated `tracing` macros)
 - rust-lang#136462 (mir_build: Simplify `lower_pattern_range_endpoint`)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Feb 3, 2025
2 parents 534d79a + 74901e2 commit a74589f
Show file tree
Hide file tree
Showing 89 changed files with 779 additions and 486 deletions.
2 changes: 2 additions & 0 deletions compiler/rustc_const_eval/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ pub fn provide(providers: &mut Providers) {
providers.check_validity_requirement = |tcx, (init_kind, param_env_and_ty)| {
util::check_validity_requirement(tcx, init_kind, param_env_and_ty)
};
providers.hooks.validate_scalar_in_layout =
|tcx, scalar, layout| util::validate_scalar_in_layout(tcx, scalar, layout);
}

/// `rustc_driver::main` installs a handler that will set this to `true` if
Expand Down
52 changes: 40 additions & 12 deletions compiler/rustc_const_eval/src/util/check_validity_requirement.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use rustc_abi::{BackendRepr, FieldsShape, Scalar, Variants};
use rustc_middle::bug;
use rustc_middle::query::TyCtxtAt;
use rustc_middle::ty::layout::{
HasTyCtxt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, ValidityRequirement,
};
use rustc_middle::ty::{PseudoCanonicalInput, Ty, TyCtxt};
use rustc_middle::ty::{PseudoCanonicalInput, ScalarInt, Ty, TyCtxt};
use rustc_middle::{bug, span_bug, ty};

use crate::const_eval::{CanAccessMutGlobal, CheckAlignment, CompileTimeMachine};
use crate::interpret::{InterpCx, MemoryKind};
Expand Down Expand Up @@ -34,7 +35,7 @@ pub fn check_validity_requirement<'tcx>(

let layout_cx = LayoutCx::new(tcx, input.typing_env);
if kind == ValidityRequirement::Uninit || tcx.sess.opts.unstable_opts.strict_init_checks {
check_validity_requirement_strict(layout, &layout_cx, kind)
Ok(check_validity_requirement_strict(layout, &layout_cx, kind))
} else {
check_validity_requirement_lax(layout, &layout_cx, kind)
}
Expand All @@ -46,7 +47,7 @@ fn check_validity_requirement_strict<'tcx>(
ty: TyAndLayout<'tcx>,
cx: &LayoutCx<'tcx>,
kind: ValidityRequirement,
) -> Result<bool, &'tcx LayoutError<'tcx>> {
) -> bool {
let machine = CompileTimeMachine::new(CanAccessMutGlobal::No, CheckAlignment::Error);

let mut cx = InterpCx::new(cx.tcx(), rustc_span::DUMMY_SP, cx.typing_env, machine);
Expand All @@ -69,14 +70,13 @@ fn check_validity_requirement_strict<'tcx>(
// due to this.
// The value we are validating is temporary and discarded at the end of this function, so
// there is no point in reseting provenance and padding.
Ok(cx
.validate_operand(
&allocated.into(),
/*recursive*/ false,
/*reset_provenance_and_padding*/ false,
)
.discard_err()
.is_some())
cx.validate_operand(
&allocated.into(),
/*recursive*/ false,
/*reset_provenance_and_padding*/ false,
)
.discard_err()
.is_some()
}

/// Implements the 'lax' (default) version of the [`check_validity_requirement`] checks; see that
Expand Down Expand Up @@ -168,3 +168,31 @@ fn check_validity_requirement_lax<'tcx>(

Ok(true)
}

pub(crate) fn validate_scalar_in_layout<'tcx>(
tcx: TyCtxtAt<'tcx>,
scalar: ScalarInt,
ty: Ty<'tcx>,
) -> bool {
let machine = CompileTimeMachine::new(CanAccessMutGlobal::No, CheckAlignment::Error);

let typing_env = ty::TypingEnv::fully_monomorphized();
let mut cx = InterpCx::new(tcx.tcx, tcx.span, typing_env, machine);

let Ok(layout) = cx.layout_of(ty) else {
span_bug!(tcx.span, "could not compute layout of {scalar:?}:{ty:?}")
};
let allocated = cx
.allocate(layout, MemoryKind::Machine(crate::const_eval::MemoryKind::Heap))
.expect("OOM: failed to allocate for uninit check");

cx.write_scalar(scalar, &allocated).unwrap();

cx.validate_operand(
&allocated.into(),
/*recursive*/ false,
/*reset_provenance_and_padding*/ false,
)
.discard_err()
.is_some()
}
1 change: 1 addition & 0 deletions compiler/rustc_const_eval/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod type_name;

pub use self::alignment::{is_disaligned, is_within_packed};
pub use self::check_validity_requirement::check_validity_requirement;
pub(crate) use self::check_validity_requirement::validate_scalar_in_layout;
pub use self::compare_types::{relate_types, sub_types};
pub use self::type_name::type_name;

Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,8 @@ declare_features! (
(unstable, inline_const_pat, "1.58.0", Some(76001)),
/// Allows using `pointer` and `reference` in intra-doc links
(unstable, intra_doc_pointers, "1.51.0", Some(80896)),
// Allows using the `kl` and `widekl` target features and the associated intrinsics
(unstable, keylocker_x86, "CURRENT_RUSTC_VERSION", Some(134813)),
// Allows setting the threshold for the `large_assignments` lint.
(unstable, large_assignments, "1.52.0", Some(83518)),
/// Allow to have type alias types for inter-crate use.
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_middle/src/hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ declare_hooks! {
hook save_dep_graph() -> ();

hook query_key_hash_verify_all() -> ();

/// Ensure the given scalar is valid for the given type.
/// This checks non-recursive runtime validity.
hook validate_scalar_in_layout(scalar: crate::ty::ScalarInt, ty: Ty<'tcx>) -> bool;
}

#[cold]
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1741,7 +1741,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
" as ",
)?;
}
ty::Pat(base_ty, pat) => {
ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => {
self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?;
p!(write(" is {pat:?}"));
}
Expand Down
81 changes: 42 additions & 39 deletions compiler/rustc_mir_build/src/thir/pattern/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,42 +155,41 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
fn lower_pattern_range_endpoint(
&mut self,
expr: Option<&'tcx hir::PatExpr<'tcx>>,
) -> Result<
(Option<PatRangeBoundary<'tcx>>, Option<Ascription<'tcx>>, Option<LocalDefId>),
ErrorGuaranteed,
> {
match expr {
None => Ok((None, None, None)),
Some(expr) => {
let (kind, ascr, inline_const) = match self.lower_lit(expr) {
PatKind::ExpandedConstant { subpattern, def_id, is_inline: true } => {
(subpattern.kind, None, def_id.as_local())
}
PatKind::ExpandedConstant { subpattern, is_inline: false, .. } => {
(subpattern.kind, None, None)
}
PatKind::AscribeUserType { ascription, subpattern: box Pat { kind, .. } } => {
(kind, Some(ascription), None)
}
kind => (kind, None, None),
};
let value = match kind {
PatKind::Constant { value } => value,
PatKind::ExpandedConstant { subpattern, .. }
if let PatKind::Constant { value } = subpattern.kind =>
{
value
}
_ => {
let msg = format!(
"found bad range pattern endpoint `{expr:?}` outside of error recovery"
);
return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
// Out-parameters collecting extra data to be reapplied by the caller
ascriptions: &mut Vec<Ascription<'tcx>>,
inline_consts: &mut Vec<LocalDefId>,
) -> Result<Option<PatRangeBoundary<'tcx>>, ErrorGuaranteed> {
let Some(expr) = expr else { return Ok(None) };

// Lower the endpoint into a temporary `PatKind` that will then be
// deconstructed to obtain the constant value and other data.
let mut kind: PatKind<'tcx> = self.lower_lit(expr);

// Unpeel any ascription or inline-const wrapper nodes.
loop {
match kind {
PatKind::AscribeUserType { ascription, subpattern } => {
ascriptions.push(ascription);
kind = subpattern.kind;
}
PatKind::ExpandedConstant { is_inline, def_id, subpattern } => {
if is_inline {
inline_consts.extend(def_id.as_local());
}
};
Ok((Some(PatRangeBoundary::Finite(value)), ascr, inline_const))
kind = subpattern.kind;
}
_ => break,
}
}

// The unpeeled kind should now be a constant, giving us the endpoint value.
let PatKind::Constant { value } = kind else {
let msg =
format!("found bad range pattern endpoint `{expr:?}` outside of error recovery");
return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
};

Ok(Some(PatRangeBoundary::Finite(value)))
}

/// Overflowing literals are linted against in a late pass. This is mostly fine, except when we
Expand Down Expand Up @@ -253,11 +252,15 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
self.tcx.dcx().span_bug(span, msg);
}

let (lo, lo_ascr, lo_inline) = self.lower_pattern_range_endpoint(lo_expr)?;
let (hi, hi_ascr, hi_inline) = self.lower_pattern_range_endpoint(hi_expr)?;
// Collect extra data while lowering the endpoints, to be reapplied later.
let mut ascriptions = vec![];
let mut inline_consts = vec![];

let mut lower_endpoint =
|expr| self.lower_pattern_range_endpoint(expr, &mut ascriptions, &mut inline_consts);

let lo = lo.unwrap_or(PatRangeBoundary::NegInfinity);
let hi = hi.unwrap_or(PatRangeBoundary::PosInfinity);
let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity);
let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity);

let cmp = lo.compare_with(hi, ty, self.tcx, self.typing_env);
let mut kind = PatKind::Range(Box::new(PatRange { lo, hi, end, ty }));
Expand Down Expand Up @@ -298,13 +301,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
// If we are handling a range with associated constants (e.g.
// `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
// constants somewhere. Have them on the range pattern.
for ascription in [lo_ascr, hi_ascr].into_iter().flatten() {
for ascription in ascriptions {
kind = PatKind::AscribeUserType {
ascription,
subpattern: Box::new(Pat { span, ty, kind }),
};
}
for def in [lo_inline, hi_inline].into_iter().flatten() {
for def in inline_consts {
kind = PatKind::ExpandedConstant {
def_id: def.to_def_id(),
is_inline: true,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,7 @@ symbols! {
iterator,
iterator_collect_fn,
kcfi,
keylocker_x86,
keyword,
kind,
kreg,
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_target/src/target_features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("fma", Stable, &["avx"]),
("fxsr", Stable, &[]),
("gfni", Unstable(sym::avx512_target_feature), &["sse2"]),
("kl", Unstable(sym::keylocker_x86), &["sse2"]),
("lahfsahf", Unstable(sym::lahfsahf_target_feature), &[]),
("lzcnt", Stable, &[]),
("movbe", Stable, &[]),
Expand All @@ -433,6 +434,7 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("tbm", Unstable(sym::tbm_target_feature), &[]),
("vaes", Unstable(sym::avx512_target_feature), &["avx2", "aes"]),
("vpclmulqdq", Unstable(sym::avx512_target_feature), &["avx", "pclmulqdq"]),
("widekl", Unstable(sym::keylocker_x86), &["kl"]),
("x87", Unstable(sym::x87_target_feature), &[]),
("xop", Unstable(sym::xop_target_feature), &[/*"fma4", */ "avx", "sse4a"]),
("xsave", Stable, &[]),
Expand Down
12 changes: 5 additions & 7 deletions src/bootstrap/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ use std::str::FromStr;
use std::{env, process};

use bootstrap::{
Build, CONFIG_CHANGE_HISTORY, Config, Flags, Subcommand, find_recent_config_change_ids,
Build, CONFIG_CHANGE_HISTORY, Config, Flags, Subcommand, debug, find_recent_config_change_ids,
human_readable_changes, t,
};
use build_helper::ci::CiEnv;
#[cfg(feature = "tracing")]
use tracing::{debug, instrument};
use tracing::instrument;

#[cfg_attr(feature = "tracing", instrument(level = "trace", name = "main"))]
fn main() {
Expand All @@ -29,10 +29,8 @@ fn main() {
return;
}

#[cfg(feature = "tracing")]
debug!("parsing flags");
let flags = Flags::parse(&args);
#[cfg(feature = "tracing")]
debug!("parsing config based on flags");
let config = Config::parse(flags);

Expand Down Expand Up @@ -95,7 +93,6 @@ fn main() {
let dump_bootstrap_shims = config.dump_bootstrap_shims;
let out_dir = config.out.clone();

#[cfg(feature = "tracing")]
debug!("creating new build based on config");
Build::new(config).build();

Expand Down Expand Up @@ -207,8 +204,9 @@ fn check_version(config: &Config) -> Option<String> {
// Due to the conditional compilation via the `tracing` cargo feature, this means that `tracing`
// usages in bootstrap need to be also gated behind the `tracing` feature:
//
// - `tracing` macros (like `trace!`) and anything from `tracing`, `tracing_subscriber` and
// `tracing-tree` will need to be gated by `#[cfg(feature = "tracing")]`.
// - `tracing` macros with log levels (`trace!`, `debug!`, `warn!`, `info`, `error`) should not be
// used *directly*. You should use the wrapped `tracing` macros which gate the actual invocations
// behind `feature = "tracing"`.
// - `tracing`'s `#[instrument(..)]` macro will need to be gated like `#![cfg_attr(feature =
// "tracing", instrument(..))]`.
#[cfg(feature = "tracing")]
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/src/core/build_steps/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ fn copy_self_contained_objects(
// to using gcc from a glibc-targeting toolchain for linking.
// To do that we have to distribute musl startup objects as a part of Rust toolchain
// and link with them manually in the self-contained mode.
if target.contains("musl") && !target.contains("unikraft") {
if target.needs_crt_begin_end() {
let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
});
Expand Down
4 changes: 3 additions & 1 deletion src/bootstrap/src/core/build_steps/llvm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1295,7 +1295,9 @@ impl Step for CrtBeginEnd {
}

fn make_run(run: RunConfig<'_>) {
run.builder.ensure(CrtBeginEnd { target: run.target });
if run.target.needs_crt_begin_end() {
run.builder.ensure(CrtBeginEnd { target: run.target });
}
}

/// Build crtbegin.o/crtend.o for musl target.
Expand Down
6 changes: 5 additions & 1 deletion src/bootstrap/src/core/builder/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -659,14 +659,18 @@ impl Builder<'_> {
// Build proc macros both for the host and the target unless proc-macros are not
// supported by the target.
if target != compiler.host && cmd_kind != Kind::Check {
let error = command(self.rustc(compiler))
let mut rustc_cmd = command(self.rustc(compiler));
self.add_rustc_lib_path(compiler, &mut rustc_cmd);

let error = rustc_cmd
.arg("--target")
.arg(target.rustc_target_arg())
.arg("--print=file-names")
.arg("--crate-type=proc-macro")
.arg("-")
.run_capture(self)
.stderr();

let not_supported = error
.lines()
.any(|line| line.contains("unsupported crate type `proc-macro`"));
Expand Down
4 changes: 4 additions & 0 deletions src/bootstrap/src/core/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,10 @@ impl TargetSelection {
env::var("OSTYPE").is_ok_and(|v| v.to_lowercase().contains("cygwin"))
}

pub fn needs_crt_begin_end(&self) -> bool {
self.contains("musl") && !self.contains("unikraft")
}

/// Path to the file defining the custom target, if any.
pub fn filepath(&self) -> Option<&Path> {
self.file.as_ref().map(Path::new)
Expand Down
Loading

0 comments on commit a74589f

Please sign in to comment.