Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 6 pull requests #112080

Merged
merged 14 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions compiler/rustc_codegen_cranelift/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,32 @@ This will build your project with rustc_codegen_cranelift instead of the usual L

For additional ways to use rustc_codegen_cranelift like the JIT mode see [usage.md](docs/usage.md).

## Building and testing with changes in rustc code

This is useful when changing code in `rustc_codegen_cranelift` as part of changing [main Rust repository](https://github.com/rust-lang/rust/).
This can happen, for example, when you are implementing a new compiler intrinsic.

Instruction below uses `$RustCheckoutDir` as substitute for any folder where you cloned Rust repository.

You need to do this steps to successfully compile and use the cranelift backend with your changes in rustc code:

1. `cd $RustCheckoutDir`
2. Run `python x.py setup` and choose option for compiler (`b`).
3. Build compiler and necessary tools: `python x.py build --stage=2 compiler library/std src/tools/rustdoc src/tools/rustfmt`
* (Optional) You can also build cargo by adding `src/tools/cargo` to previous command.
4. Copy exectutable files from `./build/host/stage2-tools/<your hostname triple>/release`
to `./build/host/stage2/bin/`. Note that you would need to do this every time you rebuilt `rust` repository.
5. Copy cargo from another toolchain: `cp $(rustup which cargo) .build/<your hostname triple>/stage2/bin/cargo`
* Another option is to build it at step 3 and copy with other executables at step 4.
6. Link your new `rustc` to toolchain: `rustup toolchain link stage2 ./build/host/stage2/`.
7. (Windows only) compile y.rs: `rustc +stage2 -O y.rs`.
8. You need to prefix every `./y.rs` (or `y` if you built `y.rs`) command by `rustup run stage2` to make cg_clif use your local changes in rustc.

* `rustup run stage2 ./y.rs prepare`
* `rustup run stage2 ./y.rs build`
* (Optional) run tests: `rustup run stage2 ./y.rs test`
9. Now you can use your cg_clif build to compile other Rust programs, e.g. you can open any Rust crate and run commands like `$RustCheckoutDir/compiler/rustc_codegen_cranelift/dist/cargo-clif build --release`.

## Configuration

See the documentation on the `BackendConfig` struct in [config.rs](src/config.rs) for all
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/compare_impl_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,7 @@ fn report_trait_method_mismatch<'tcx>(
if trait_m.fn_has_self_parameter =>
{
let ty = trait_sig.inputs()[0];
let sugg = match ExplicitSelf::determine(ty, |_| ty == impl_trait_ref.self_ty()) {
let sugg = match ExplicitSelf::determine(ty, |ty| ty == impl_trait_ref.self_ty()) {
ExplicitSelf::ByValue => "self".to_owned(),
ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
Expand Down
19 changes: 18 additions & 1 deletion compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ use rustc_span::{self, BytePos, DesugaringKind, Span};
use rustc_target::spec::abi::Abi;
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use rustc_trait_selection::traits::{
self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
};
Expand Down Expand Up @@ -144,12 +145,28 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
self.commit_if_ok(|_| {
let at = self.at(&self.cause, self.fcx.param_env);
if self.use_lub {

let res = if self.use_lub {
at.lub(DefineOpaqueTypes::Yes, b, a)
} else {
at.sup(DefineOpaqueTypes::Yes, b, a)
.map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
};

// In the new solver, lazy norm may allow us to shallowly equate
// more types, but we emit possibly impossible-to-satisfy obligations.
// Filter these cases out to make sure our coercion is more accurate.
if self.tcx.trait_solver_next() {
if let Ok(res) = &res {
for obligation in &res.obligations {
if !self.predicate_may_hold(&obligation) {
return Err(TypeError::Mismatch);
}
}
}
}

res
})
}

Expand Down
10 changes: 10 additions & 0 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
type FreeRegion = ty::FreeRegion;
type RegionVid = ty::RegionVid;
type PlaceholderRegion = ty::PlaceholderRegion;

fn ty_and_mut_to_parts(
TypeAndMut { ty, mutbl }: TypeAndMut<'tcx>,
) -> (Self::Ty, Self::Mutability) {
(ty, mutbl)
}

fn mutability_is_mut(mutbl: Self::Mutability) -> bool {
mutbl.is_mut()
}
}

type InternedSet<'tcx, T> = ShardedHashMap<InternedInSet<'tcx, T>, ()>;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1496,7 +1496,7 @@ impl<'tcx> OpaqueHiddenType<'tcx> {
/// identified by both a universe, as well as a name residing within that universe. Distinct bound
/// regions/types/consts within the same universe simply have an unknown relationship to one
/// another.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(HashStable, TyEncodable, TyDecodable)]
pub struct Placeholder<T> {
pub universe: UniverseIndex,
Expand Down
62 changes: 19 additions & 43 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,29 +685,30 @@ pub trait PrettyPrinter<'tcx>:
}
ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
ty::Infer(infer_ty) => {
let verbose = self.should_print_verbose();
if self.should_print_verbose() {
p!(write("{:?}", ty.kind()));
return Ok(self);
}

if let ty::TyVar(ty_vid) = infer_ty {
if let Some(name) = self.ty_infer_name(ty_vid) {
p!(write("{}", name))
} else {
if verbose {
p!(write("{:?}", infer_ty))
} else {
p!(write("{}", infer_ty))
}
p!(write("{}", infer_ty))
}
} else {
if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
p!(write("{}", infer_ty))
}
}
ty::Error(_) => p!("{{type error}}"),
ty::Param(ref param_ty) => p!(print(param_ty)),
ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
ty::BoundTyKind::Anon => debug_bound_var(&mut self, debruijn, bound_ty.var)?,
ty::BoundTyKind::Anon => {
rustc_type_ir::debug_bound_var(&mut self, debruijn, bound_ty.var)?
}
ty::BoundTyKind::Param(_, s) => match self.should_print_verbose() {
true if debruijn == ty::INNERMOST => p!(write("^{}", s)),
true => p!(write("^{}_{}", debruijn.index(), s)),
false => p!(write("{}", s)),
true => p!(write("{:?}", ty.kind())),
false => p!(write("{s}")),
},
},
ty::Adt(def, substs) => {
Expand Down Expand Up @@ -740,10 +741,11 @@ pub trait PrettyPrinter<'tcx>:
}
}
ty::Placeholder(placeholder) => match placeholder.bound.kind {
ty::BoundTyKind::Anon => {
debug_placeholder_var(&mut self, placeholder.universe, placeholder.bound.var)?;
}
ty::BoundTyKind::Param(_, name) => p!(write("{}", name)),
ty::BoundTyKind::Anon => p!(write("{placeholder:?}")),
ty::BoundTyKind::Param(_, name) => match self.should_print_verbose() {
true => p!(write("{:?}", ty.kind())),
false => p!(write("{name}")),
},
},
ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
// We use verbose printing in 'NO_QUERIES' mode, to
Expand Down Expand Up @@ -1372,11 +1374,9 @@ pub trait PrettyPrinter<'tcx>:
}

ty::ConstKind::Bound(debruijn, bound_var) => {
debug_bound_var(&mut self, debruijn, bound_var)?
rustc_type_ir::debug_bound_var(&mut self, debruijn, bound_var)?
}
ty::ConstKind::Placeholder(placeholder) => {
debug_placeholder_var(&mut self, placeholder.universe, placeholder.bound)?;
},
ty::ConstKind::Placeholder(placeholder) => p!(write("{placeholder:?}")),
// FIXME(generic_const_exprs):
// write out some legible representation of an abstract const?
ty::ConstKind::Expr(_) => p!("{{const expr}}"),
Expand Down Expand Up @@ -3065,27 +3065,3 @@ pub struct OpaqueFnEntry<'tcx> {
fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
}

pub fn debug_bound_var<T: std::fmt::Write>(
fmt: &mut T,
debruijn: ty::DebruijnIndex,
var: ty::BoundVar,
) -> Result<(), std::fmt::Error> {
if debruijn == ty::INNERMOST {
write!(fmt, "^{}", var.index())
} else {
write!(fmt, "^{}_{}", debruijn.index(), var.index())
}
}

pub fn debug_placeholder_var<T: std::fmt::Write>(
fmt: &mut T,
universe: ty::UniverseIndex,
bound: ty::BoundVar,
) -> Result<(), std::fmt::Error> {
if universe == ty::UniverseIndex::ROOT {
write!(fmt, "!{}", bound.index())
} else {
write!(fmt, "!{}_{}", universe.index(), bound.index())
}
}
59 changes: 52 additions & 7 deletions compiler/rustc_middle/src/ty/structural_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,35 @@ impl fmt::Debug for ty::FreeRegion {

impl<'tcx> fmt::Debug for ty::FnSig<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({:?}; c_variadic: {})->{:?}", self.inputs(), self.c_variadic, self.output())
let ty::FnSig { inputs_and_output: _, c_variadic, unsafety, abi } = self;

write!(f, "{}", unsafety.prefix_str())?;
match abi {
rustc_target::spec::abi::Abi::Rust => (),
abi => write!(f, "extern \"{abi:?}\" ")?,
};

write!(f, "fn(")?;
let inputs = self.inputs();
match inputs.len() {
0 if *c_variadic => write!(f, "...)")?,
0 => write!(f, ")")?,
_ => {
for ty in &self.inputs()[0..(self.inputs().len() - 1)] {
write!(f, "{ty:?}, ")?;
}
write!(f, "{:?}", self.inputs().last().unwrap())?;
if *c_variadic {
write!(f, "...")?;
}
write!(f, ")")?;
}
}

match self.output().kind() {
ty::Tuple(list) if list.is_empty() => Ok(()),
_ => write!(f, " -> {:?}", self.output()),
}
}
}

Expand Down Expand Up @@ -216,20 +244,37 @@ impl<'tcx> fmt::Debug for ty::ConstKind<'tcx> {
match self {
Param(param) => write!(f, "{param:?}"),
Infer(var) => write!(f, "{var:?}"),
Bound(debruijn, var) => ty::print::debug_bound_var(f, *debruijn, *var),
Placeholder(placeholder) => {
ty::print::debug_placeholder_var(f, placeholder.universe, placeholder.bound)
}
Bound(debruijn, var) => rustc_type_ir::debug_bound_var(f, *debruijn, *var),
Placeholder(placeholder) => write!(f, "{placeholder:?}"),
Unevaluated(uv) => {
f.debug_tuple("Unevaluated").field(&uv.substs).field(&uv.def).finish()
}
Value(valtree) => write!(f, "{valtree:?}"),
Error(_) => write!(f, "[const error]"),
Error(_) => write!(f, "{{const error}}"),
Expr(expr) => write!(f, "{expr:?}"),
}
}
}

impl fmt::Debug for ty::BoundTy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
ty::BoundTyKind::Anon => write!(f, "{:?}", self.var),
ty::BoundTyKind::Param(_, sym) => write!(f, "{sym:?}"),
}
}
}

impl<T: fmt::Debug> fmt::Debug for ty::Placeholder<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.universe == ty::UniverseIndex::ROOT {
write!(f, "!{:?}", self.bound)
} else {
write!(f, "!{}_{:?}", self.universe.index(), self.bound)
}
}
}

///////////////////////////////////////////////////////////////////////////
// Atomic structs
//
Expand Down Expand Up @@ -294,6 +339,7 @@ TrivialTypeTraversalAndLiftImpls! {
crate::ty::AliasRelationDirection,
crate::ty::Placeholder<crate::ty::BoundRegion>,
crate::ty::Placeholder<crate::ty::BoundTy>,
crate::ty::Placeholder<ty::BoundVar>,
crate::ty::ClosureKind,
crate::ty::FreeRegion,
crate::ty::InferTy,
Expand All @@ -310,7 +356,6 @@ TrivialTypeTraversalAndLiftImpls! {
interpret::Scalar,
rustc_target::abi::Size,
ty::BoundVar,
ty::Placeholder<ty::BoundVar>,
}

TrivialTypeTraversalAndLiftImpls! {
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1511,10 +1511,11 @@ impl Atom for RegionVid {

rustc_index::newtype_index! {
#[derive(HashStable)]
#[debug_format = "{}"]
pub struct BoundVar {}
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable)]
pub struct BoundTy {
pub var: BoundVar,
Expand Down
23 changes: 19 additions & 4 deletions compiler/rustc_type_ir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub trait Interner: Sized {
type PolyFnSig: Clone + Debug + Hash + Ord;
type ListBinderExistentialPredicate: Clone + Debug + Hash + Ord;
type BinderListTy: Clone + Debug + Hash + Ord;
type ListTy: Clone + Debug + Hash + Ord;
type ListTy: Clone + Debug + Hash + Ord + IntoIterator<Item = Self::Ty>;
type AliasTy: Clone + Debug + Hash + Ord;
type ParamTy: Clone + Debug + Hash + Ord;
type BoundTy: Clone + Debug + Hash + Ord;
Expand All @@ -67,6 +67,9 @@ pub trait Interner: Sized {
type FreeRegion: Clone + Debug + Hash + Ord;
type RegionVid: Clone + Debug + Hash + Ord;
type PlaceholderRegion: Clone + Debug + Hash + Ord;

fn ty_and_mut_to_parts(ty_and_mut: Self::TypeAndMut) -> (Self::Ty, Self::Mutability);
fn mutability_is_mut(mutbl: Self::Mutability) -> bool;
}

/// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter`
Expand Down Expand Up @@ -390,7 +393,19 @@ impl DebruijnIndex {
}
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub fn debug_bound_var<T: std::fmt::Write>(
fmt: &mut T,
debruijn: DebruijnIndex,
var: impl std::fmt::Debug,
) -> Result<(), std::fmt::Error> {
if debruijn == INNERMOST {
write!(fmt, "^{:?}", var)
} else {
write!(fmt, "^{}_{:?}", debruijn.index(), var)
}
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Encodable, Decodable, HashStable_Generic)]
pub enum IntTy {
Isize,
Expand Down Expand Up @@ -448,7 +463,7 @@ impl IntTy {
}
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
#[derive(Encodable, Decodable, HashStable_Generic)]
pub enum UintTy {
Usize,
Expand Down Expand Up @@ -506,7 +521,7 @@ impl UintTy {
}
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Encodable, Decodable, HashStable_Generic)]
pub enum FloatTy {
F32,
Expand Down
Loading