Skip to content

Commit c9430d9

Browse files
committed
Track local frames incrementally during execution
1 parent 3162b7a commit c9430d9

File tree

6 files changed

+147
-158
lines changed

6 files changed

+147
-158
lines changed

src/concurrency/thread.rs

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Implements threads.
22
3+
use std::cell::Cell;
34
use std::cell::RefCell;
45
use std::collections::hash_map::Entry;
56
use std::num::TryFromIntError;
@@ -118,6 +119,17 @@ pub struct Thread<'mir, 'tcx> {
118119
/// The virtual call stack.
119120
stack: Vec<Frame<'mir, 'tcx, Provenance, FrameData<'tcx>>>,
120121

122+
/// The index of the topmost local frame in `stack`. If `Some`, this field must contain
123+
/// the value produced by `reset_top_local`.
124+
/// This field is a cache to reduce how often we call that method. The cache is invalidated by
125+
/// mutation of the stack, so calls to `active_thread_stack_mut` set this to `None`.
126+
///
127+
/// The outer `Option` represents the validity of the cache, and the inner `Option` represents
128+
/// whether or not there is a local frame. Being able to differentiate between knowing that we
129+
/// have no local frame and not knowing whether there is a local frame reduces how often the
130+
/// cache is invalidated.
131+
top_local_frame: Cell<Option<Option<usize>>>,
132+
121133
/// The join status.
122134
join_status: ThreadJoinStatus,
123135

@@ -147,6 +159,35 @@ impl<'mir, 'tcx> Thread<'mir, 'tcx> {
147159
fn thread_name(&self) -> &[u8] {
148160
if let Some(ref thread_name) = self.thread_name { thread_name } else { b"<unnamed>" }
149161
}
162+
163+
fn compute_top_local_frame(&self) -> Option<usize> {
164+
self.stack
165+
.iter()
166+
.enumerate()
167+
.rev()
168+
.find_map(|(idx, frame)| if frame.extra.is_local { Some(idx) } else { None })
169+
}
170+
171+
pub fn top_local_frame(&self) -> usize {
172+
let top_local = if let Some(idx) = self.top_local_frame.get() {
173+
debug_assert_eq!(idx, self.compute_top_local_frame());
174+
idx
175+
} else {
176+
let idx = self.compute_top_local_frame();
177+
self.top_local_frame.set(Some(idx));
178+
idx
179+
};
180+
top_local.unwrap_or_else(|| self.stack.len().saturating_sub(1))
181+
}
182+
183+
pub fn set_top_local_frame(&mut self, frame_idx: Option<usize>) {
184+
if let Some(idx) = frame_idx {
185+
self.top_local_frame.set(Some(Some(idx)));
186+
debug_assert_eq!(Some(idx), self.compute_top_local_frame());
187+
} else {
188+
self.top_local_frame.set(None);
189+
}
190+
}
150191
}
151192

152193
impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
@@ -167,6 +208,7 @@ impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
167208
state: ThreadState::Enabled,
168209
thread_name: None,
169210
stack: Vec::new(),
211+
top_local_frame: Cell::new(None),
170212
join_status: ThreadJoinStatus::Joinable,
171213
panic_payload: None,
172214
last_error: None,
@@ -184,8 +226,15 @@ impl<'mir, 'tcx> Thread<'mir, 'tcx> {
184226

185227
impl VisitTags for Thread<'_, '_> {
186228
fn visit_tags(&self, visit: &mut dyn FnMut(SbTag)) {
187-
let Thread { panic_payload, last_error, stack, state: _, thread_name: _, join_status: _ } =
188-
self;
229+
let Thread {
230+
panic_payload,
231+
last_error,
232+
stack,
233+
top_local_frame: _,
234+
state: _,
235+
thread_name: _,
236+
join_status: _,
237+
} = self;
189238

190239
panic_payload.visit_tags(visit);
191240
last_error.visit_tags(visit);
@@ -414,10 +463,16 @@ impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
414463
}
415464

416465
/// Get a shared borrow of the currently active thread.
417-
fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
466+
pub fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
418467
&self.threads[self.active_thread]
419468
}
420469

470+
/// Reset the current-span caching logic of the active thread.
471+
/// Mostly called when a new frame is added or removed.
472+
pub fn top_local_frame(&self) -> usize {
473+
self.active_thread_ref().top_local_frame()
474+
}
475+
421476
/// Mark the thread as detached, which means that no other thread will try
422477
/// to join it and the thread is responsible for cleaning up.
423478
///

src/helpers.rs

Lines changed: 10 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -936,78 +936,35 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
936936
}
937937

938938
impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
939-
pub fn current_span(&self) -> CurrentSpan<'_, 'mir, 'tcx> {
940-
CurrentSpan { current_frame_idx: None, machine: self }
941-
}
942-
}
943-
944-
/// A `CurrentSpan` should be created infrequently (ideally once) per interpreter step. It does
945-
/// nothing on creation, but when `CurrentSpan::get` is called, searches the current stack for the
946-
/// topmost frame which corresponds to a local crate, and returns the current span in that frame.
947-
/// The result of that search is cached so that later calls are approximately free.
948-
#[derive(Clone)]
949-
pub struct CurrentSpan<'a, 'mir, 'tcx> {
950-
current_frame_idx: Option<usize>,
951-
machine: &'a MiriMachine<'mir, 'tcx>,
952-
}
953-
954-
impl<'a, 'mir: 'a, 'tcx: 'a + 'mir> CurrentSpan<'a, 'mir, 'tcx> {
955-
pub fn machine(&self) -> &'a MiriMachine<'mir, 'tcx> {
956-
self.machine
957-
}
958-
959939
/// Get the current span, skipping non-local frames.
960940
/// This function is backed by a cache, and can be assumed to be very fast.
961-
pub fn get(&mut self) -> Span {
962-
let idx = self.current_frame_idx();
963-
self.stack().get(idx).map(Frame::current_span).unwrap_or(rustc_span::DUMMY_SP)
941+
pub fn current_span(&self) -> Span {
942+
self.stack()
943+
.get(self.top_local_frame())
944+
.map(Frame::current_span)
945+
.unwrap_or(rustc_span::DUMMY_SP)
964946
}
965947

966948
/// Returns the span of the *caller* of the current operation, again
967949
/// walking down the stack to find the closest frame in a local crate, if the caller of the
968950
/// current operation is not in a local crate.
969951
/// This is useful when we are processing something which occurs on function-entry and we want
970952
/// to point at the call to the function, not the function definition generally.
971-
pub fn get_caller(&mut self) -> Span {
953+
pub fn caller_span(&self) -> Span {
972954
// We need to go down at least to the caller (len - 2), or however
973955
// far we have to go to find a frame in a local crate.
974-
let local_frame_idx = self.current_frame_idx();
956+
let local_frame_idx = self.top_local_frame();
975957
let stack = self.stack();
976958
let idx = cmp::min(local_frame_idx, stack.len().saturating_sub(2));
977959
stack.get(idx).map(Frame::current_span).unwrap_or(rustc_span::DUMMY_SP)
978960
}
979961

980962
fn stack(&self) -> &[Frame<'mir, 'tcx, Provenance, machine::FrameData<'tcx>>] {
981-
self.machine.threads.active_thread_stack()
982-
}
983-
984-
fn current_frame_idx(&mut self) -> usize {
985-
*self
986-
.current_frame_idx
987-
.get_or_insert_with(|| Self::compute_current_frame_index(self.machine))
963+
self.threads.active_thread_stack()
988964
}
989965

990-
// Find the position of the inner-most frame which is part of the crate being
991-
// compiled/executed, part of the Cargo workspace, and is also not #[track_caller].
992-
#[inline(never)]
993-
fn compute_current_frame_index(machine: &MiriMachine<'_, '_>) -> usize {
994-
machine
995-
.threads
996-
.active_thread_stack()
997-
.iter()
998-
.enumerate()
999-
.rev()
1000-
.find_map(|(idx, frame)| {
1001-
let def_id = frame.instance.def_id();
1002-
if (def_id.is_local() || machine.local_crates.contains(&def_id.krate))
1003-
&& !frame.instance.def.requires_caller_location(machine.tcx)
1004-
{
1005-
Some(idx)
1006-
} else {
1007-
None
1008-
}
1009-
})
1010-
.unwrap_or(0)
966+
fn top_local_frame(&self) -> usize {
967+
self.threads.active_thread_ref().top_local_frame()
1011968
}
1012969
}
1013970

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ pub use crate::diagnostics::{
9797
pub use crate::eval::{
9898
create_ecx, eval_entry, AlignmentCheck, BacktraceStyle, IsolatedOp, MiriConfig, RejectOpWith,
9999
};
100-
pub use crate::helpers::{CurrentSpan, EvalContextExt as _};
100+
pub use crate::helpers::EvalContextExt as _;
101101
pub use crate::intptrcast::ProvenanceMode;
102102
pub use crate::machine::{
103103
AllocExtra, FrameData, MiriInterpCx, MiriInterpCxExt, MiriMachine, MiriMemoryKind,

src/machine.rs

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,14 @@ pub struct FrameData<'tcx> {
5050
/// for the start of this frame. When we finish executing this frame,
5151
/// we use this to register a completed event with `measureme`.
5252
pub timing: Option<measureme::DetachedTiming>,
53+
54+
pub is_local: bool,
5355
}
5456

5557
impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
5658
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5759
// Omitting `timing`, it does not support `Debug`.
58-
let FrameData { stacked_borrows, catch_unwind, timing: _ } = self;
60+
let FrameData { stacked_borrows, catch_unwind, timing: _, is_local: _ } = self;
5961
f.debug_struct("FrameData")
6062
.field("stacked_borrows", stacked_borrows)
6163
.field("catch_unwind", catch_unwind)
@@ -65,7 +67,7 @@ impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
6567

6668
impl VisitTags for FrameData<'_> {
6769
fn visit_tags(&self, visit: &mut dyn FnMut(SbTag)) {
68-
let FrameData { catch_unwind, stacked_borrows, timing: _ } = self;
70+
let FrameData { catch_unwind, stacked_borrows, timing: _, is_local: _ } = self;
6971

7072
catch_unwind.visit_tags(visit);
7173
stacked_borrows.visit_tags(visit);
@@ -895,13 +897,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
895897

896898
let alloc = alloc.into_owned();
897899
let stacks = ecx.machine.stacked_borrows.as_ref().map(|stacked_borrows| {
898-
Stacks::new_allocation(
899-
id,
900-
alloc.size(),
901-
stacked_borrows,
902-
kind,
903-
ecx.machine.current_span(),
904-
)
900+
Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind, &ecx.machine)
905901
});
906902
let race_alloc = ecx.machine.data_race.as_ref().map(|data_race| {
907903
data_race::AllocExtra::new_allocation(
@@ -1016,8 +1012,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
10161012
prov_extra,
10171013
range,
10181014
machine.stacked_borrows.as_ref().unwrap(),
1019-
machine.current_span(),
1020-
&machine.threads,
1015+
machine,
10211016
)?;
10221017
}
10231018
if let Some(weak_memory) = &alloc_extra.weak_memory {
@@ -1048,8 +1043,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
10481043
prov_extra,
10491044
range,
10501045
machine.stacked_borrows.as_ref().unwrap(),
1051-
machine.current_span(),
1052-
&machine.threads,
1046+
machine,
10531047
)?;
10541048
}
10551049
if let Some(weak_memory) = &alloc_extra.weak_memory {
@@ -1083,8 +1077,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
10831077
prove_extra,
10841078
range,
10851079
machine.stacked_borrows.as_ref().unwrap(),
1086-
machine.current_span(),
1087-
&machine.threads,
1080+
machine,
10881081
)
10891082
} else {
10901083
Ok(())
@@ -1120,13 +1113,19 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
11201113
None
11211114
};
11221115

1116+
let def_id = frame.instance.def_id();
1117+
let is_local = (def_id.is_local() || ecx.machine.local_crates.contains(&def_id.krate))
1118+
&& !frame.instance.def.requires_caller_location(ecx.machine.tcx);
1119+
11231120
let stacked_borrows = ecx.machine.stacked_borrows.as_ref();
11241121

11251122
let extra = FrameData {
11261123
stacked_borrows: stacked_borrows.map(|sb| sb.borrow_mut().new_frame(&ecx.machine)),
11271124
catch_unwind: None,
11281125
timing,
1126+
is_local,
11291127
};
1128+
11301129
Ok(frame.with_extra(extra))
11311130
}
11321131

@@ -1174,6 +1173,13 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
11741173

11751174
#[inline(always)]
11761175
fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1176+
if ecx.frame().extra.is_local {
1177+
// We just pushed a local frame, so we know that the topmost local frame is the topmost
1178+
// frame. If we push a non-local frame, there's no need to do anything.
1179+
let stack_len = ecx.active_thread_stack().len();
1180+
ecx.active_thread_mut().set_top_local_frame(Some(stack_len - 1));
1181+
}
1182+
11771183
if ecx.machine.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
11781184
}
11791185

@@ -1183,6 +1189,11 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
11831189
mut frame: Frame<'mir, 'tcx, Provenance, FrameData<'tcx>>,
11841190
unwinding: bool,
11851191
) -> InterpResult<'tcx, StackPopJump> {
1192+
if frame.extra.is_local {
1193+
// All that we store is whether or not the frame we just removed is local, so now we
1194+
// have no idea what if any the next topmost local frame is.
1195+
ecx.active_thread_mut().set_top_local_frame(None);
1196+
}
11861197
let timing = frame.extra.timing.take();
11871198
if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
11881199
stacked_borrows.borrow_mut().end_call(&frame.extra);

0 commit comments

Comments
 (0)