Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -818,8 +818,8 @@ fn test_unstable_options_tracking_hash() {
tracked!(min_function_alignment, Some(Align::EIGHT));
tracked!(mir_emit_retag, true);
tracked!(mir_enable_passes, vec![("DestProp".to_string(), false)]);
tracked!(mir_keep_place_mention, true);
tracked!(mir_opt_level, Some(4));
tracked!(mir_preserve_ub, true);
tracked!(move_size_limit, Some(4096));
tracked!(mutable_noalias, false);
tracked!(next_solver, NextSolverConfig { coherence: true, globally: true });
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/early_otherwise_branch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ impl<'tcx> crate::MirPass<'tcx> for EarlyOtherwiseBranch {
// Since this optimization adds new basic blocks and invalidates others,
// clean up the cfg to make it nicer for other passes
if should_cleanup {
simplify_cfg(body);
simplify_cfg(tcx, body);
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_mir_transform/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl<'tcx> crate::MirPass<'tcx> for Inline {
let _guard = span.enter();
if inline::<NormalInliner<'tcx>>(tcx, body) {
debug!("running simplify cfg on {:?}", body.source);
simplify_cfg(body);
simplify_cfg(tcx, body);
deref_finder(tcx, body);
}
}
Expand Down Expand Up @@ -99,7 +99,7 @@ impl<'tcx> crate::MirPass<'tcx> for ForceInline {
let _guard = span.enter();
if inline::<ForceInliner<'tcx>>(tcx, body) {
debug!("running simplify cfg on {:?}", body.source);
simplify_cfg(body);
simplify_cfg(tcx, body);
deref_finder(tcx, body);
}
}
Expand Down
135 changes: 64 additions & 71 deletions compiler/rustc_mir_transform/src/jump_threading.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/match_branches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl<'tcx> crate::MirPass<'tcx> for MatchBranchSimplification {
}

if should_cleanup {
simplify_cfg(body);
simplify_cfg(tcx, body);
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/remove_place_mention.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub(super) struct RemovePlaceMention;

impl<'tcx> crate::MirPass<'tcx> for RemovePlaceMention {
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
!sess.opts.unstable_opts.mir_keep_place_mention
!sess.opts.unstable_opts.mir_preserve_ub
}

fn run_pass(&self, _: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/remove_unneeded_drops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl<'tcx> crate::MirPass<'tcx> for RemoveUnneededDrops {
// if we applied optimizations, we potentially have some cfg to cleanup to
// make it easier for further passes
if should_simplify {
simplify_cfg(body);
simplify_cfg(tcx, body);
}
}

Expand Down
35 changes: 26 additions & 9 deletions compiler/rustc_mir_transform/src/simplify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@
//! Here the block (`{ return; }`) has the return type `char`, rather than `()`, but the MIR we
//! naively generate still contains the `_a = ()` write in the unreachable block "after" the
//! return.
//!
//! **WARNING**: This is one of the few optimizations that runs on built and analysis MIR, and
//! so its effects may affect the type-checking, borrow-checking, and other analysis of MIR.
//! We must be extremely careful to only apply optimizations that preserve UB and all
//! non-determinism, since changes here can affect which programs compile in an insta-stable way.
//! The normal logic that a program with UB can be changed to do anything does not apply to
//! pre-"runtime" MIR!

use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
Expand Down Expand Up @@ -66,8 +73,8 @@ impl SimplifyCfg {
}
}

pub(super) fn simplify_cfg(body: &mut Body<'_>) {
CfgSimplifier::new(body).simplify();
pub(super) fn simplify_cfg<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
CfgSimplifier::new(tcx, body).simplify();
remove_dead_blocks(body);

// FIXME: Should probably be moved into some kind of pass manager
Expand All @@ -79,9 +86,9 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyCfg {
self.name()
}

fn run_pass(&self, _: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
debug!("SimplifyCfg({:?}) - simplifying {:?}", self.name(), body.source);
simplify_cfg(body);
simplify_cfg(tcx, body);
}

fn is_required(&self) -> bool {
Expand All @@ -90,12 +97,13 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyCfg {
}

struct CfgSimplifier<'a, 'tcx> {
preserve_switch_reads: bool,
basic_blocks: &'a mut IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
pred_count: IndexVec<BasicBlock, u32>,
}

impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
fn new(body: &'a mut Body<'tcx>) -> Self {
fn new(tcx: TyCtxt<'tcx>, body: &'a mut Body<'tcx>) -> Self {
let mut pred_count = IndexVec::from_elem(0u32, &body.basic_blocks);

// we can't use mir.predecessors() here because that counts
Expand All @@ -110,9 +118,12 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
}
}

// Preserve `SwitchInt` reads on built and analysis MIR, or if `-Zmir-preserve-ub`.
let preserve_switch_reads = matches!(body.phase, MirPhase::Built | MirPhase::Analysis(_))
|| tcx.sess.opts.unstable_opts.mir_preserve_ub;
let basic_blocks = body.basic_blocks_mut();

CfgSimplifier { basic_blocks, pred_count }
CfgSimplifier { preserve_switch_reads, basic_blocks, pred_count }
}

fn simplify(mut self) {
Expand Down Expand Up @@ -253,9 +264,15 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {

// turn a branch with all successors identical to a goto
fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
match terminator.kind {
TerminatorKind::SwitchInt { .. } => {}
_ => return false,
// Removing a `SwitchInt` terminator may remove reads that result in UB,
// so we must not apply this optimization before borrowck or when
// `-Zmir-preserve-ub` is set.
if self.preserve_switch_reads {
return false;
}

let TerminatorKind::SwitchInt { .. } = terminator.kind else {
return false;
};

let first_succ = {
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2322,12 +2322,12 @@ options! {
mir_include_spans: MirIncludeSpans = (MirIncludeSpans::default(), parse_mir_include_spans, [UNTRACKED],
"include extra comments in mir pretty printing, like line numbers and statement indices, \
details about types, etc. (boolean for all passes, 'nll' to enable in NLL MIR only, default: 'nll')"),
mir_keep_place_mention: bool = (false, parse_bool, [TRACKED],
"keep place mention MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
(default: no)"),
#[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")]
mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
"MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),
mir_preserve_ub: bool = (false, parse_bool, [TRACKED],
"keep place mention statements and reads in trivial SwitchInt terminators, which are interpreted \
e.g., by miri; implies -Zmir-opt-level=0 (default: no)"),
mir_strip_debuginfo: MirStripDebugInfo = (MirStripDebugInfo::None, parse_mir_strip_debuginfo, [TRACKED],
"Whether to remove some of the MIR debug info from methods. Default: None"),
move_size_limit: Option<usize> = (None, parse_opt_number, [TRACKED],
Expand Down
33 changes: 33 additions & 0 deletions library/core/src/iter/adapters/enumerate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,39 @@ impl<I> Enumerate<I> {
pub(in crate::iter) fn new(iter: I) -> Enumerate<I> {
Enumerate { iter, count: 0 }
}

/// Retrieve the current position of the iterator.
///
/// If the iterator has not advanced, the position returned will be 0.
///
/// The position may also exceed the bounds of the iterator to allow for calculating
/// the displacement of the iterator from following calls to [`Iterator::next`].
///
/// # Examples
///
/// ```
/// #![feature(next_index)]
///
/// let arr = ['a', 'b'];
///
/// let mut iter = arr.iter().enumerate();
///
/// assert_eq!(iter.next_index(), 0);
/// assert_eq!(iter.next(), Some((0, &'a')));
///
/// assert_eq!(iter.next_index(), 1);
/// assert_eq!(iter.next_index(), 1);
/// assert_eq!(iter.next(), Some((1, &'b')));
///
/// assert_eq!(iter.next_index(), 2);
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next_index(), 2);
/// ```
#[inline]
#[unstable(feature = "next_index", issue = "130711")]
pub fn next_index(&self) -> usize {
self.count
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
10 changes: 10 additions & 0 deletions library/coretests/tests/iter/adapters/enumerate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,13 @@ fn test_double_ended_enumerate() {
assert_eq!(it.next_back(), Some((2, 3)));
assert_eq!(it.next(), None);
}

#[test]
fn test_empty_iterator_enumerate_next_index() {
let mut it = empty::<i32>().enumerate();
assert_eq!(it.next_index(), 0);
assert_eq!(it.next_index(), 0);
assert_eq!(it.next(), None);
assert_eq!(it.next_index(), 0);
assert_eq!(it.next_index(), 0);
}
1 change: 1 addition & 0 deletions library/coretests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
#![feature(maybe_uninit_write_slice)]
#![feature(min_specialization)]
#![feature(never_type)]
#![feature(next_index)]
#![feature(numfmt)]
#![feature(pattern)]
#![feature(pointer_is_aligned_to)]
Expand Down
3 changes: 1 addition & 2 deletions src/bootstrap/src/core/build_steps/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,8 +1194,7 @@ pub fn rustc_cargo(
let enzyme_dir = builder.build.out.join(arch).join("enzyme").join("lib");
cargo.rustflag("-L").rustflag(enzyme_dir.to_str().expect("Invalid path"));

if !builder.config.dry_run() {
let llvm_config = builder.llvm_config(builder.config.build).unwrap();
if let Some(llvm_config) = builder.llvm_config(builder.config.build) {
let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
cargo.rustflag("-l").rustflag(&format!("Enzyme-{llvm_version_major}"));
}
Expand Down
3 changes: 3 additions & 0 deletions src/bootstrap/src/core/build_steps/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,7 @@ Select which editor you would like to set up [default: None]: ";
"51068d4747a13732440d1a8b8f432603badb1864fa431d83d0fd4f8fa57039e0",
"d29af4d949bbe2371eac928a3c31cf9496b1701aa1c45f11cd6c759865ad5c45",
"b5dd299b93dca3ceeb9b335f929293cb3d4bf4977866fbe7ceeac2a8a9f99088",
"631c837b0e98ae35fd48b0e5f743b1ca60adadf2d0a2b23566ba25df372cf1a9",
],
EditorKind::Helix => &[
"2d3069b8cf1b977e5d4023965eb6199597755e6c96c185ed5f2854f98b83d233",
Expand All @@ -602,10 +603,12 @@ Select which editor you would like to set up [default: None]: ";
"4eecb58a2168b252077369da446c30ed0e658301efe69691979d1ef0443928f4",
"c394386e6133bbf29ffd32c8af0bb3d4aac354cba9ee051f29612aa9350f8f8d",
"e53e9129ca5ee5dcbd6ec8b68c2d87376474eb154992deba3c6d9ab1703e0717",
"f954316090936c7e590c253ca9d524008375882fa13c5b41d7e2547a896ff893",
],
EditorKind::Zed => &[
"bbce727c269d1bd0c98afef4d612eb4ce27aea3c3a8968c5f10b31affbc40b6c",
"a5380cf5dd9328731aecc5dfb240d16dac46ed272126b9728006151ef42f5909",
"2e96bf0d443852b12f016c8fc9840ab3d0a2b4fe0b0fb3a157e8d74d5e7e0e26",
],
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/etc/rust_analyzer_eglot.el
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
"check"
"--json-output"])
:linkedProjects ["Cargo.toml"
"src/bootstrap/Cargo.toml"
"src/tools/rust-analyzer/Cargo.toml"
"compiler/rustc_codegen_cranelift/Cargo.toml"
"compiler/rustc_codegen_gcc/Cargo.toml"]
"compiler/rustc_codegen_gcc/Cargo.toml"
"library/Cargo.toml"
"src/bootstrap/Cargo.toml"
"src/tools/rust-analyzer/Cargo.toml"]
:rustfmt ( :overrideCommand ["build/host/rustfmt/bin/rustfmt"
"--edition=2021"])
:procMacro ( :server "build/host/stage0/libexec/rust-analyzer-proc-macro-srv"
Expand Down
11 changes: 8 additions & 3 deletions src/etc/rust_analyzer_settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
],
"rust-analyzer.linkedProjects": [
"Cargo.toml",
"compiler/rustc_codegen_cranelift/Cargo.toml",
"compiler/rustc_codegen_gcc/Cargo.toml",
"library/Cargo.toml",
"src/bootstrap/Cargo.toml",
"src/tools/rust-analyzer/Cargo.toml",
"compiler/rustc_codegen_cranelift/Cargo.toml",
"compiler/rustc_codegen_gcc/Cargo.toml"
"src/tools/rust-analyzer/Cargo.toml"
],
"rust-analyzer.rustfmt.overrideCommand": [
"${workspaceFolder}/build/host/rustfmt/bin/rustfmt",
Expand All @@ -36,5 +36,10 @@
},
"rust-analyzer.server.extraEnv": {
"RUSTUP_TOOLCHAIN": "nightly"
},
"files.associations": {
"*.fixed": "rust",
"*.pp": "rust",
"*.mir": "rust"
}
}
13 changes: 8 additions & 5 deletions src/etc/rust_analyzer_zed.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
},
"linkedProjects": [
"Cargo.toml",
"compiler/rustc_codegen_cranelift/Cargo.toml",
"compiler/rustc_codegen_gcc/Cargo.toml",
"library/Cargo.toml",
"src/bootstrap/Cargo.toml",
"src/tools/rust-analyzer/Cargo.toml",
"compiler/rustc_codegen_cranelift/Cargo.toml",
"compiler/rustc_codegen_gcc/Cargo.toml"
"src/tools/rust-analyzer/Cargo.toml"
],
"procMacro": {
"enable": true,
"server": "${workspaceFolder}/build/host/stage0/libexec/rust-analyzer-proc-macro-srv"
"enable": true,
"server": "${workspaceFolder}/build/host/stage0/libexec/rust-analyzer-proc-macro-srv"
},
"rustc": {
"source": "./Cargo.toml"
Expand All @@ -47,5 +47,8 @@
}
}
}
},
"file_types": {
"Rust": ["fixed", "pp", "mir"]
}
}
Loading