rustc_public: split `def`s out of `ty`
This is more of an "I feel like this should be like this" kind of change. I suppose that we might need to make the `ty` a bit more fine-grained as the coverage expands. That said, I don't have a strong opinion on whether it's necessary, so feel free to close this PR if you find it not convincing enough.
The diff looks so scary, though... I just split `ty.rs` into `def.rs` and `tys.rs` and changed `crate_def!` and `crate_def_with_ty!`.
miri: ensure validity of references and pointers we dereference and cast
Conceptually, when we evaluate the place expression `*place`, there are two steps that happen:
- perform a (typed) load from `place`, which yields a value of pointer/ref type
- construct a new place from that value
Since this is a typed load, we have to ensure that the value satisfies the validity invariant. We forgot to do that, which led to Miri missing a bunch of UB. This PR fixes that by adding the missing checks.
Triggering this UB is a bit non-trivial: you cannot just store an invalid value into `place` using regular assignment (that would already be caught as part of the assignment). However, you can take a raw pointer to `place` and then use that to mutate the contents of `place` in a way that its validity invariant no longer holds. For example:
```rust
fn main() {
let mut x = &();
// Overwrite `x` with null.
unsafe { (&raw mut x).cast::<usize>().write(0) };
let _val = *x; //~ERROR: null reference
}
```
This program clearly (IMO) should have UB, and has UB in MiniRust, but Miri accepted that program before this PR. The same applies to references that are invalid because they are unaligned (even if we end up only accessing a 1-aligned field, i.e. the rest of the place expression evaluates just fine), and to references that are invalid because they are not dereferenceable (even if we end up projecting to a zero-sized field, i.e., the rest of the place expression evaluates just fine).
Even raw pointers have this problem: a raw pointer can be invalid if its vtable pointer is wrong, and we did not check that.
And finally, this also affects `Box`, and this is where things get tricky. `Box` derefs are not even present any more in the MIR Miri sees; they have been replaced by derefs of the underlying raw pointer. But that means we have no way to know that we should check all those things. So to fix that I adjusted the ElaborateBoxDerefs to emit a new special kind of cast that's almost a transmute but also checks `Box` validity.
Fixes https://github.com/rust-lang/miri/issues/5226
Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/617
Cc @rust-lang/opsem
Structurally prevent zero-count `BackendRepr::SimdVector`s
This is already *supposed* to be impossible in layout, but this emphasizes that better. This PR makes no behaviour changes; just `BackendLaneCount` instead of `u64` in https://doc.rust-lang.org/nightly/nightly-rustc/rustc_abi/enum.BackendRepr.html
Ironically I was inspired to do this as part of [looking at making `Simd<T, 0>` *work*](https://rust-lang.zulipchat.com/#narrow/channel/257879-project-portable-simd/topic/Allow.20N.3D.3D0.3F/with/613345298), but importantly if that's going to happen I think it should be `BackendRepr::Memory` like other ZSTs, *not* a `BackendRepr::ScalarVector` that would need to carry around a useless LLVM value in `OperandValue::Immediate` (where it's not even clear what the LLVM type of that value would be).
This is already *supposed* to be impossible in layout, but this emphasizes that better.
Ironically I was inspired to do this as part of looking at making `Simd<T, 0>` *work*, but importantly if that's going to happen I think it should be `BackendRepr::Memory` like other ZSTs, *not* a `BackendRepr::ScalarVector` that would need to carry around a useless LLVM value in `OperandValue::Immediate` (where it's not even clear what the LLVM type of that value would be).
Lots of names weren't changed to account for the introduction of the
`Clause` type as a specialized form of `Predicate`, presumably because
it was tedious. This commit converts as many of them as I could find.
It's mostly very tedious renamings of types, functions, variables, and
queries. The more interesting ones are a couple of files
(`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass
(`ImpossiblePredicates`).
Support creating float constants in rustc_public mir
This PR adds a `try_from_float` similar to `try_from_uint` to the `rustc_public::ty::MirConst`.
It takes `u128` and users need a `.to_bits() as u128` to call this function. I did this because `f64` couldn't capture a `f128` const completely, and `f128` needs to cast and a branch on the input types, making the code complex. Another alternative is adding 4 functions `try_from_f16` to `try_from_f128`, which I don't like, but that's also an option.
Document rustc_public lib.rs and update README
Add module-level documentation with usage example, crate discovery guide, and status section. Document all public types, methods, and free functions in lib.rs. Update README to reflect the crate rename from `stable_mir`/`rustc_smir` to `rustc_public`/`rustc_public_bridge`.
Disclaimer: I used AI to help me generate the documentation.
- Add a concrete code example (duplicate crate detection)
- Clarify requires_monomorphization doc
- Add FIXME for Symbol type alias
Co-authored-by: Bruno Kolenbrander <59372212+mejrs@users.noreply.github.com>
Add a method Body::caller_location that resolves the correct caller
location constant for a call to a #[track_caller] function, walking
inlined source scopes to handle MIR inlining correctly.
Body now stores source scope data as a public field. Body::new
populates it with empty entries (no inlining info); bodies obtained
from the compiler have full scope data populated.
Span::as_caller_location is now pub(crate) since users should use
Body::caller_location instead, which handles inlining correctly.
Add module-level documentation with usage example, crate discovery
guide, and status section. Document all public types, methods, and
free functions in lib.rs. Update README to reflect the crate rename
from stable_mir/rustc_smir to rustc_public/rustc_public_bridge.
Introduce InstanceKind::LlvmIntrinsic
This way codegen backends don't have to check for a magic symbol name prefix to detect LLVM intrinsic calls and thus can more easily handle them separately as necessary.
Expose more info about ADTs and functions in rustc_public
This allows users of `rustc_public` to do more complex navigation through data structures by exposing the following info:
* `AdtDef::generics_of` - Get the generics for the ADT.
* `AdtDef::inherent_impls` - Get all the impls for the ADT.
* `FnDef::associated_item` - Get the trait or impl block that contains the function if it exists.
* `FnDef::generics_of` - get the generics for a given function.
* `ImplDef::generics_of` - Get the generics for the impl block.
* `ImplDef` implements `CrateDefType` - figure out the type of the impl block with `CrateDefType::ty()` or get the normalized type with `CrateDefType::ty_with_args()`.
This was partially written with the help of Gemini, but I reviewed the code it generated.
First steps of late-bound turbofishing (place FnDef behind a dummy binder)
r? oli-obk
This PR is part of rust-lang/rust#156581. This should be functionally identical to prior behavior, with the added fact that FnDef now places its arguments behind a binder.
most changes boil down to
- replacing `args` from `FnDef` with `args.no_bound_vars().unwrap()`
- replacing `Ty::new_fn_def(/* ... */, args)` with `Ty::new_fn_def(/* ... */, ty::Binder::dummy(args))`
This way codegen backends don't have to check for a magic symbol name
prefix to detect LLVM intrinsic calls and thus can more easily handle
them separately as necessary.
Add an API to construct the `&'static Location<'static>` constant
that must be passed as the implicit extra argument when calling a
`#[track_caller]` function. Users provide the span of the call
site (or the callee's definition span for reify shim fallback).
Fixes https://github.com/rust-lang/rustc_public/issues/62
Expose the internal `requires_caller_location` query through
rustc_public so tools can detect when an instance has an implicit
extra `&'static Location<'static>` argument in its ABI that is
not present in the MIR body signature.
Fixes https://github.com/rust-lang/rustc_public/issues/123
This allows users of `rustc_public` to do more complex navigation
through data structures by exposing the following info:
* `AdtDef::generics_of` - Get the generics for the ADT.
* `AdtDef::inherent_impls` - Get all the impls for the ADT.
* `FnDef::associated_item` - Get the trait or impl block that contains the
function if it exists.
* `FnDef::generics_of` - get the generics for a given function.
* `ImplDef::generics_of` - Get the generics for the impl block.
* `ImplDef` implements `CrateDefType` - figure out the type of the impl
block with `CrateDefType::ty()` or get the normalized type with
`CrateDefType::ty_with_args()`.
This was partially written with the help of Gemini, but I reviewed the
code it generated.
Distinguish null reference production from null pointer dereference in UB checks
Closesrust-lang/rust#154044
This change distinguishes null reference production from actual null pointer dereferences in the UB checks.
Producing a reference from a null pointer (for example, `&*ptr`) is undefined behavior even if no memory is dereferenced. This change introduces a dedicated `AssertKind::NullReferenceConstructed` and runtime panic so these cases produce a more accurate diagnostic while preserving the existing panic for actual null pointer dereferences.
Summary
- Add `AssertKind::NullReferenceConstructed`.
- Emit it for null reference production in the MIR null check pass.
- Add `panic_null_reference_constructed` and its lang item.
- Keep `NullPointerDereference` for actual dereferences.
- Update the affected UI tests.
Expose debug scope of statement and terminator in rustc_public
Currently, `scope` is exposed for variables, but it is a meaningless number since the boundary of each scope is not available. This PR changes `span` fields of statement and terminator to `source_info` which includes scope as well.
Disclaimer: Written by LLM
Introduce a dedicated panic for null reference production to distinguish
producing a reference from a null pointer from an actual null pointer
dereference.
This emits a dedicated panic message for null reference production while
preserving the existing panic for actual dereferences.
Rename UnevaluatedConst to AliasConst
refer: https://github.com/rust-lang/project-const-generics/issues/115
r? @khyperia
I only renamed the type system version to `AliasConst`/`AliasConstKind`. I did not rename MIR’s `UnevaluatedConst`, it currently holds direct def_id instead of kind variant we have in type-system. I also left `rustc_public`’s `UnevaluatedConst` unchanged.
* Const::new_unevaluated / interner method -> new_alias
* Interner::UnevaluatedConstId -> AnonConstId, since assoc type is only used for anonnymous consts
They tend to have similar handling -- e.g., they should be the only
input to the `mir_shims` query -- so it's cleaner to group them
together. This will also make potential future refactorings easier, such
as only carrying `GenericArgsRef` for instances that actually use it
(e.g., `Item`) but not others (e.g., `CloneShim`).
Many of the shim variants still have `Shim` at the end of their names.
To make the refactoring easier and keep the diff clean, I will trim
those suffixes off in the next commit.
Implement rustc_public::CrateDef{,Type} for FieldDef
This makes a few changes to rustc_public to make it a little easier to analyze ADT types.
* It implements `CrateDef` and `CrateDefType` for `FieldDef`, which allows easy access to the underlying `DefId`, names, and tool annotations.
* It adds `Crate::adts` to simplify stepping through all the ADTs in the crate.
Note that I did use Gemini to assist with writing this patch, but I wrote most of it, reviewed all the vode, and verified the tests pass locally.