miri/concurrency/weak_memory.rs
1//! Implementation of C++11-consistent weak memory emulation using store buffers
2//! based on Dynamic Race Detection for C++ ("the paper"):
3//! <https://www.doc.ic.ac.uk/~afd/homepages/papers/pdfs/2017/POPL.pdf>
4//!
5//! This implementation will never generate weak memory behaviours forbidden by the C++11 model,
6//! but it is incapable of producing all possible weak behaviours allowed by the model. There are
7//! certain weak behaviours observable on real hardware but not while using this.
8//!
9//! Note that this implementation does not fully take into account of C++20's memory model revision to SC accesses
10//! and fences introduced by P0668 (<https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0668r5.html>).
11//! This implementation is not fully correct under the revised C++20 model and may generate behaviours C++20
12//! disallows (<https://github.com/rust-lang/miri/issues/2301>).
13//!
14//! Modifications are made to the paper's model to address C++20 changes:
15//! - If an SC load reads from an atomic store of any ordering, then a later SC load cannot read
16//! from an earlier store in the location's modification order. This is to prevent creating a
17//! backwards S edge from the second load to the first, as a result of C++20's coherence-ordered
18//! before rules. (This seems to rule out behaviors that were actually permitted by the RC11 model
19//! that C++20 intended to copy (<https://plv.mpi-sws.org/scfix/paper.pdf>); a change was
20//! introduced when translating the math to English. According to Viktor Vafeiadis, this
21//! difference is harmless. So we stick to what the standard says, and allow fewer behaviors.)
22//! - If an SC store happens after a load (of any ordering), then the existing store (of any ordering)
23//! seen by the load is marked as an SC store. (The paper's model only marks stores that happen-before
24//! an SC store as SC.)
25//! - SC fences are treated like AcqRel RMWs to a global clock, to ensure they induce enough
26//! synchronization with the surrounding accesses. This rules out legal behavior, but it is really
27//! hard to be more precise here.
28//!
29//! Rust follows the C++20 memory model (except for the Consume ordering and some operations not performable through C++'s
30//! `std::atomic<T>` API). It is therefore possible for this implementation to generate behaviours never observable when the
31//! same program is compiled and run natively. Unfortunately, no literature exists at the time of writing which proposes
32//! an implementable and C++20-compatible relaxed memory model that supports all atomic operation existing in Rust. The closest one is
33//! A Promising Semantics for Relaxed-Memory Concurrency by Jeehoon Kang et al. (<https://www.cs.tau.ac.il/~orilahav/papers/popl17.pdf>)
34//! However, this model lacks SC accesses and is therefore unusable by Miri (SC accesses are everywhere in library code).
35//!
36//! If you find anything that proposes a relaxed memory model that is C++20-consistent, supports all orderings Rust's atomic accesses
37//! and fences accept, and is implementable (with operational semantics), please open a GitHub issue!
38//!
39//! One characteristic of this implementation, in contrast to some other notable operational models such as ones proposed in
40//! Taming Release-Acquire Consistency by Ori Lahav et al. (<https://plv.mpi-sws.org/sra/paper.pdf>) or Promising Semantics noted above,
41//! is that this implementation does not require each thread to hold an isolated view of the entire memory. Here, store buffers are per-location
42//! and shared across all threads. This is more memory efficient but does require store elements (representing writes to a location) to record
43//! information about reads, whereas in the other two models it is the other way round: reads points to the write it got its value from.
44//! Additionally, writes in our implementation do not have globally unique timestamps attached. In the other two models this timestamp is
45//! used to make sure a value in a thread's view is not overwritten by a write that occurred earlier than the one in the existing view.
46//! In our implementation, this is detected using read information attached to store elements, as there is no data structure representing reads.
47//!
48//! The C++ memory model is built around the notion of an 'atomic object', so it would be natural
49//! to attach store buffers to atomic objects. However, Rust follows LLVM in that it only has
50//! 'atomic accesses'. Therefore Miri cannot know when and where atomic 'objects' are being
51//! created or destroyed, to manage its store buffers. Instead, we hence lazily create an
52//! atomic object on the first atomic write to a given region, and we destroy that object
53//! on the next non-atomic or imperfectly overlapping atomic write to that region.
54//! These lazy (de)allocations happen in memory_accessed() on non-atomic accesses, and
55//! get_or_create_store_buffer_mut() on atomic writes.
56//!
57//! One consequence of this difference is that safe/sound Rust allows for more operations on atomic locations
58//! than the C++20 atomic API was intended to allow, such as non-atomically accessing
59//! a previously atomically accessed location, or accessing previously atomically accessed locations with a differently sized operation
60//! (such as accessing the top 16 bits of an AtomicU32). These scenarios are generally undiscussed in formalizations of C++ memory model.
61//! In Rust, these operations can only be done through a `&mut AtomicFoo` reference or one derived from it, therefore these operations
62//! can only happen after all previous accesses on the same locations. This implementation is adapted to allow these operations.
63//! A mixed atomicity read that races with writes, or a write that races with reads or writes will still cause UBs to be thrown.
64//! Mixed size atomic accesses must not race with any other atomic access, whether read or write, or a UB will be thrown.
65//! You can refer to test cases in weak_memory/extra_cpp.rs and weak_memory/extra_cpp_unsafe.rs for examples of these operations.
66
67// Our and the author's own implementation (tsan11) of the paper have some deviations from the provided operational semantics in §5.3:
68// 1. In the operational semantics, loads acquire the vector clock of the atomic location
69// irrespective of which store buffer element is loaded. That's incorrect; the synchronization clock
70// needs to be tracked per-store-buffer-element. (The paper has a field "clocks" for that purpose,
71// but it is not actuallt used.) tsan11 does this correctly
72// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.cc#L305).
73//
74// 2. In the operational semantics, each store element keeps the timestamp of a thread when it loads from the store.
75// If the same thread loads from the same store element multiple times, then the timestamps at all loads are saved in a list of load elements.
76// This is not necessary as later loads by the same thread will always have greater timestamp values, so we only need to record the timestamp of the first
77// load by each thread. This optimisation is done in tsan11
78// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.h#L35-L37)
79// and here.
80//
81// 3. §4.5 of the paper wants an SC store to mark all existing stores in the buffer that happens before it
82// as SC. This is not done in the operational semantics but implemented correctly in tsan11
83// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.cc#L160-L167).
84// On top of this we've added a C++20 change: if the current SC store happens after a load, then the store seen by that load
85// is marked SC.
86//
87// 4. W_SC ; R_SC case requires the SC load to ignore all but last store marked SC (stores not marked SC are not
88// affected). But this rule is applied to all loads in ReadsFromSet from the paper (last two lines of code), not just SC load.
89// This is implemented correctly in tsan11
90// (https://github.com/ChrisLidbury/tsan11/blob/ecbd6b81e9b9454e01cba78eb9d88684168132c7/lib/tsan/rtl/tsan_relaxed.cc#L295)
91// and here.
92
93use std::cell::{Ref, RefCell};
94use std::collections::VecDeque;
95
96use rustc_data_structures::fx::FxHashMap;
97
98use super::AllocDataRaceHandler;
99use super::data_race::{GlobalState as DataRaceState, ThreadClockSet};
100use super::vector_clock::{VClock, VTimestamp, VectorIdx};
101use crate::concurrency::GlobalDataRaceHandler;
102use crate::data_structures::range_object_map::{AccessType, RangeObjectMap};
103use crate::*;
104
105pub type AllocState = StoreBufferAlloc;
106
107// Each store buffer must be bounded otherwise it will grow indefinitely.
108// However, bounding the store buffer means restricting the amount of weak
109// behaviours observable. The author picked 128 as a good tradeoff
110// so we follow them here.
111const STORE_BUFFER_LIMIT: usize = 128;
112
113#[derive(Debug, Clone)]
114pub struct StoreBufferAlloc {
115 /// Store buffer of each atomic object in this allocation
116 // Behind a RefCell because we need to allocate/remove on read access
117 store_buffers: RefCell<RangeObjectMap<StoreBuffer>>,
118}
119
120impl VisitProvenance for StoreBufferAlloc {
121 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
122 let Self { store_buffers } = self;
123 for val in store_buffers
124 .borrow()
125 .iter()
126 .flat_map(|buf| buf.buffer.iter().map(|element| &element.val))
127 {
128 val.visit_provenance(visit);
129 }
130 }
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub(super) struct StoreBuffer {
135 // Stores to this location in modification order
136 buffer: VecDeque<StoreElement>,
137}
138
139/// Whether a load returned the latest value or not.
140#[derive(PartialEq, Eq)]
141enum LoadRecency {
142 Latest,
143 Outdated,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
147struct StoreElement {
148 /// The thread that performed the store.
149 store_thread: VectorIdx,
150 /// The timestamp of the storing thread when it performed the store
151 store_timestamp: VTimestamp,
152
153 /// The vector clock that can be acquired by loading this store.
154 sync_clock: VClock,
155
156 /// Whether this store is SC. If a store happens-before or precedes in `mo` another SC store,
157 /// then it is also marked as SC.
158 is_seqcst: bool,
159
160 /// The value of this store. `None` means uninitialized.
161 // FIXME: Currently, we cannot represent partial initialization.
162 val: Option<Scalar>,
163
164 /// Metadata about loads from this store element,
165 /// behind a RefCell to keep load op take &self
166 load_info: RefCell<LoadInfo>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Default)]
170struct LoadInfo {
171 /// Timestamp of first loads from this store element by each thread.
172 timestamps: FxHashMap<VectorIdx, VTimestamp>,
173 /// Whether this store element has been read by an SC load.
174 /// This is crucial to ensure we respect coherence-ordered-before. Concretely we use
175 /// this to ensure that if a store element is seen by an SC load, then all later SC loads
176 /// cannot see `mo`-earlier store elements.
177 sc_loaded: bool,
178}
179
180impl StoreBufferAlloc {
181 pub fn new_allocation() -> Self {
182 Self { store_buffers: RefCell::new(RangeObjectMap::new()) }
183 }
184
185 /// When a non-atomic write happens on a location that has been atomically accessed
186 /// before without data race, we can determine that the non-atomic write fully happens
187 /// after all the prior atomic writes so the location no longer needs to exhibit
188 /// any weak memory behaviours until further atomic writes.
189 pub fn non_atomic_write(&self, range: AllocRange, global: &DataRaceState) {
190 if !global.ongoing_action_data_race_free() {
191 let mut buffers = self.store_buffers.borrow_mut();
192 let access_type = buffers.access_type(range);
193 match access_type {
194 AccessType::PerfectlyOverlapping(pos) => {
195 buffers.remove_from_pos(pos);
196 }
197 AccessType::ImperfectlyOverlapping(pos_range) => {
198 // We rely on the data-race check making sure this is synchronized.
199 // Therefore we can forget about the old data here.
200 buffers.remove_pos_range(pos_range);
201 }
202 AccessType::Empty(_) => {
203 // The range had no weak behaviours attached, do nothing
204 }
205 }
206 }
207 }
208
209 /// Gets a store buffer associated with an atomic object in this allocation.
210 /// Returns `None` if there is no store buffer.
211 fn get_store_buffer<'tcx>(
212 &self,
213 range: AllocRange,
214 ) -> InterpResult<'tcx, Option<Ref<'_, StoreBuffer>>> {
215 let access_type = self.store_buffers.borrow().access_type(range);
216 let AccessType::PerfectlyOverlapping(pos) = access_type else {
217 // If there is nothing here yet, that means there wasn't an atomic write yet so
218 // we can't return anything outdated.
219 return interp_ok(None);
220 };
221 let store_buffer = Ref::map(self.store_buffers.borrow(), |buffer| &buffer[pos]);
222 interp_ok(Some(store_buffer))
223 }
224
225 /// Gets a mutable store buffer associated with an atomic object in this allocation,
226 /// or creates one with the specified initial value if no atomic object exists yet.
227 fn get_or_create_store_buffer_mut<'tcx>(
228 &mut self,
229 range: AllocRange,
230 init: Result<Option<Scalar>, ()>,
231 ) -> InterpResult<'tcx, &mut StoreBuffer> {
232 let buffers = self.store_buffers.get_mut();
233 let access_type = buffers.access_type(range);
234 let pos = match access_type {
235 AccessType::PerfectlyOverlapping(pos) => pos,
236 AccessType::Empty(pos) => {
237 let init =
238 init.expect("cannot have empty store buffer when previous write was atomic");
239 buffers.insert_at_pos(pos, range, StoreBuffer::new(init));
240 pos
241 }
242 AccessType::ImperfectlyOverlapping(pos_range) => {
243 // Once we reach here we would've already checked that this access is not racy.
244 let init = init.expect(
245 "cannot have partially overlapping store buffer when previous write was atomic",
246 );
247 buffers.remove_pos_range(pos_range.clone());
248 buffers.insert_at_pos(pos_range.start, range, StoreBuffer::new(init));
249 pos_range.start
250 }
251 };
252 interp_ok(&mut buffers[pos])
253 }
254}
255
256impl<'tcx> StoreBuffer {
257 fn new(init: Option<Scalar>) -> Self {
258 let mut buffer = VecDeque::new();
259 let store_elem = StoreElement {
260 // The thread index and timestamp of the initialisation write
261 // are never meaningfully used, so it's fine to leave them as 0
262 store_thread: VectorIdx::from(0),
263 store_timestamp: VTimestamp::ZERO,
264 // The initialization write is non-atomic so nothing can be acquired.
265 sync_clock: VClock::default(),
266 val: init,
267 is_seqcst: false,
268 load_info: RefCell::new(LoadInfo::default()),
269 };
270 buffer.push_back(store_elem);
271 Self { buffer }
272 }
273
274 /// Reads from the last store in modification order, if any.
275 fn read_from_last_store(
276 &self,
277 global: &DataRaceState,
278 thread_mgr: &ThreadManager<'_>,
279 is_seqcst: bool,
280 ) {
281 let store_elem = self.buffer.back();
282 if let Some(store_elem) = store_elem {
283 let (index, clocks) = global.active_thread_state(thread_mgr);
284 store_elem.load_impl(index, &clocks, is_seqcst);
285 }
286 }
287
288 fn buffered_read(
289 &self,
290 global: &DataRaceState,
291 thread_mgr: &ThreadManager<'_>,
292 is_seqcst: bool,
293 rng: &mut (impl rand::Rng + ?Sized),
294 validate: impl FnOnce(Option<&VClock>) -> InterpResult<'tcx>,
295 ) -> InterpResult<'tcx, (Option<Scalar>, LoadRecency)> {
296 // Having a live borrow to store_buffer while calling validate_atomic_load is fine
297 // because the race detector doesn't touch store_buffer
298
299 let (store_elem, recency) = {
300 // The `clocks` we got here must be dropped before calling validate_atomic_load
301 // as the race detector will update it
302 let (.., clocks) = global.active_thread_state(thread_mgr);
303 // Load from a valid entry in the store buffer
304 self.fetch_store(is_seqcst, &clocks, &mut *rng)
305 };
306
307 // Unlike in buffered_atomic_write, thread clock updates have to be done
308 // after we've picked a store element from the store buffer, as presented
309 // in ATOMIC LOAD rule of the paper. This is because fetch_store
310 // requires access to ThreadClockSet.clock, which is updated by the race detector
311 validate(Some(&store_elem.sync_clock))?;
312
313 let (index, clocks) = global.active_thread_state(thread_mgr);
314 let loaded = store_elem.load_impl(index, &clocks, is_seqcst);
315 interp_ok((loaded, recency))
316 }
317
318 fn buffered_write(
319 &mut self,
320 val: Scalar,
321 global: &DataRaceState,
322 thread_mgr: &ThreadManager<'_>,
323 is_seqcst: bool,
324 sync_clock: VClock,
325 ) -> InterpResult<'tcx> {
326 let (index, clocks) = global.active_thread_state(thread_mgr);
327
328 self.store_impl(val, index, &clocks.clock, is_seqcst, sync_clock);
329 interp_ok(())
330 }
331
332 /// Selects a valid store element in the buffer.
333 fn fetch_store<R: rand::Rng + ?Sized>(
334 &self,
335 is_seqcst: bool,
336 clocks: &ThreadClockSet,
337 rng: &mut R,
338 ) -> (&StoreElement, LoadRecency) {
339 use rand::seq::IteratorRandom;
340 let mut found_sc = false;
341 // FIXME: we want an inclusive take_while (stops after a false predicate, but
342 // includes the element that gave the false), but such function doesn't yet
343 // exist in the standard library https://github.com/rust-lang/rust/issues/62208
344 // so we have to hack around it with keep_searching
345 let mut keep_searching = true;
346 let candidates = self
347 .buffer
348 .iter()
349 .rev()
350 .take_while(move |&store_elem| {
351 if !keep_searching {
352 return false;
353 }
354
355 keep_searching = if store_elem.store_timestamp
356 <= clocks.clock[store_elem.store_thread]
357 {
358 // CoWR: if a store happens-before the current load,
359 // then we can't read-from anything earlier in modification order.
360 // C++20 §6.9.2.2 [intro.races] paragraph 18
361 false
362 } else if store_elem.load_info.borrow().timestamps.iter().any(
363 |(&load_index, &load_timestamp)| load_timestamp <= clocks.clock[load_index],
364 ) {
365 // CoRR: if there was a load from this store which happened-before the current load,
366 // then we cannot read-from anything earlier in modification order.
367 // C++20 §6.9.2.2 [intro.races] paragraph 16
368 false
369 } else if store_elem.store_timestamp <= clocks.write_seqcst[store_elem.store_thread]
370 && store_elem.is_seqcst
371 {
372 // The current non-SC load, which may be sequenced-after an SC fence,
373 // cannot read-before the last SC store executed before the fence.
374 // C++17 §32.4 [atomics.order] paragraph 4
375 false
376 } else if is_seqcst
377 && store_elem.store_timestamp <= clocks.read_seqcst[store_elem.store_thread]
378 {
379 // The current SC load cannot read-from any but the last store sequenced-before
380 // the last SC fence.
381 // C++17 §32.4 [atomics.order] paragraph 5
382 false
383 } else if is_seqcst && store_elem.load_info.borrow().sc_loaded {
384 // The current SC load cannot read-before a store that an earlier SC load has observed.
385 // See https://github.com/rust-lang/miri/issues/2301#issuecomment-1222720427.
386 // Consequences of C++20 §31.4 [atomics.order] paragraph 3.1, 3.3 (coherence-ordered before)
387 // and 4.1 (coherence-ordered before between SC makes global total order S).
388 false
389 } else {
390 true
391 };
392
393 true
394 })
395 .filter(|&store_elem| {
396 if is_seqcst && store_elem.is_seqcst {
397 // An SC load needs to ignore all but last store marked SC (stores not marked SC are not
398 // affected)
399 let include = !found_sc;
400 found_sc = true;
401 include
402 } else {
403 true
404 }
405 });
406
407 let chosen = candidates.choose(rng).expect("store buffer cannot be empty");
408 if std::ptr::eq(chosen, self.buffer.back().expect("store buffer cannot be empty")) {
409 (chosen, LoadRecency::Latest)
410 } else {
411 (chosen, LoadRecency::Outdated)
412 }
413 }
414
415 /// ATOMIC STORE IMPL in the paper
416 fn store_impl(
417 &mut self,
418 val: Scalar,
419 index: VectorIdx,
420 thread_clock: &VClock,
421 is_seqcst: bool,
422 sync_clock: VClock,
423 ) {
424 let store_elem = StoreElement {
425 store_thread: index,
426 store_timestamp: thread_clock[index],
427 sync_clock,
428 // In the language provided in the paper, an atomic store takes the value from a
429 // non-atomic memory location.
430 // But we already have the immediate value here so we don't need to do the memory
431 // access.
432 val: Some(val),
433 is_seqcst,
434 load_info: RefCell::new(LoadInfo::default()),
435 };
436 if self.buffer.len() >= STORE_BUFFER_LIMIT {
437 self.buffer.pop_front();
438 }
439 self.buffer.push_back(store_elem);
440 if is_seqcst {
441 // Every store that happens-before or is coherence-ordered before the ongoing SC store
442 // needs to be marked as SC, so that in a later SC load, only the latest SC-marked store
443 // or unmarked stores can be picked.
444 self.buffer.iter_mut().rev().for_each(|elem| {
445 if elem.store_timestamp <= thread_clock[elem.store_thread] {
446 // This store happens-before the ongoing SC store.
447 elem.is_seqcst = true;
448 } else if elem
449 .load_info
450 .borrow()
451 .timestamps
452 .iter()
453 .any(|(&idx, &load_ts)| load_ts <= thread_clock[idx])
454 {
455 // This store has a load which happens before the ongoing store.
456 // This store must precede the onging store in modification order,
457 // and is therefore coherence-ordered before the ongoing SC store.
458 elem.is_seqcst = true;
459 }
460 })
461 }
462 }
463}
464
465impl StoreElement {
466 /// ATOMIC LOAD IMPL in the paper
467 /// Unlike the operational semantics in the paper, we don't need to keep track
468 /// of the thread timestamp for every single load. Keeping track of the first (smallest)
469 /// timestamp of each thread that has loaded from a store is sufficient: if the earliest
470 /// load of another thread happens before the current one, then we must stop searching the store
471 /// buffer regardless of subsequent loads by the same thread; if the earliest load of another
472 /// thread doesn't happen before the current one, then no subsequent load by the other thread
473 /// can happen before the current one.
474 fn load_impl(
475 &self,
476 index: VectorIdx,
477 clocks: &ThreadClockSet,
478 is_seqcst: bool,
479 ) -> Option<Scalar> {
480 let mut load_info = self.load_info.borrow_mut();
481 load_info.sc_loaded |= is_seqcst;
482 let _ = load_info.timestamps.try_insert(index, clocks.clock[index]);
483 self.val
484 }
485}
486
487impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
488pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
489 fn buffered_atomic_rmw(
490 &mut self,
491 new_val: Scalar,
492 place: &MPlaceTy<'tcx>,
493 atomic: AtomicRwOrd,
494 init: Scalar,
495 ) -> InterpResult<'tcx> {
496 let this = self.eval_context_mut();
497 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(place.ptr(), 0)?;
498 if let (
499 crate::AllocExtra {
500 data_race: AllocDataRaceHandler::Vclocks(data_race_clocks, Some(alloc_buffers)),
501 ..
502 },
503 crate::MiriMachine {
504 data_race: GlobalDataRaceHandler::Vclocks(global), threads, ..
505 },
506 ) = this.get_alloc_extra_mut(alloc_id)?
507 {
508 if atomic == AtomicRwOrd::SeqCst {
509 global.sc_read(threads);
510 global.sc_write(threads);
511 }
512 let range = alloc_range(base_offset, place.layout.size);
513 let sync_clock = data_race_clocks.sync_clock(range);
514 let buffer = alloc_buffers.get_or_create_store_buffer_mut(range, Ok(Some(init)))?;
515 // The RMW always reads from the most recent store.
516 buffer.read_from_last_store(global, threads, atomic == AtomicRwOrd::SeqCst);
517 buffer.buffered_write(
518 new_val,
519 global,
520 threads,
521 atomic == AtomicRwOrd::SeqCst,
522 sync_clock,
523 )?;
524 }
525 interp_ok(())
526 }
527
528 /// The argument to `validate` is the synchronization clock of the memory that is being read,
529 /// if we are reading from a store buffer element.
530 fn buffered_atomic_read(
531 &self,
532 place: &MPlaceTy<'tcx>,
533 atomic: AtomicReadOrd,
534 latest_in_mo: Scalar,
535 validate: impl FnOnce(Option<&VClock>) -> InterpResult<'tcx>,
536 ) -> InterpResult<'tcx, Option<Scalar>> {
537 let this = self.eval_context_ref();
538 'fallback: {
539 if let Some(global) = this.machine.data_race.as_vclocks_ref() {
540 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(place.ptr(), 0)?;
541 if let Some(alloc_buffers) =
542 this.get_alloc_extra(alloc_id)?.data_race.as_weak_memory_ref()
543 {
544 if atomic == AtomicReadOrd::SeqCst {
545 global.sc_read(&this.machine.threads);
546 }
547 let mut rng = this.machine.rng.borrow_mut();
548 let Some(buffer) = alloc_buffers
549 .get_store_buffer(alloc_range(base_offset, place.layout.size))?
550 else {
551 // No old writes available, fall back to base case.
552 break 'fallback;
553 };
554 let (loaded, recency) = buffer.buffered_read(
555 global,
556 &this.machine.threads,
557 atomic == AtomicReadOrd::SeqCst,
558 &mut *rng,
559 validate,
560 )?;
561 if global.track_outdated_loads && recency == LoadRecency::Outdated {
562 this.emit_diagnostic(NonHaltingDiagnostic::WeakMemoryOutdatedLoad {
563 ptr: place.ptr(),
564 });
565 }
566
567 return interp_ok(loaded);
568 }
569 }
570 }
571
572 // Race detector or weak memory disabled, simply read the latest value
573 validate(None)?;
574 interp_ok(Some(latest_in_mo))
575 }
576
577 /// Add the given write to the store buffer. (Does not change machine memory.)
578 ///
579 /// `init` says with which value to initialize the store buffer in case there wasn't a store
580 /// buffer for this memory range before. `Err(())` means the value is not available;
581 /// `Ok(None)` means the memory does not contain a valid scalar.
582 ///
583 /// Must be called *after* `validate_atomic_store` to ensure that `sync_clock` is up-to-date.
584 fn buffered_atomic_write(
585 &mut self,
586 val: Scalar,
587 dest: &MPlaceTy<'tcx>,
588 atomic: AtomicWriteOrd,
589 init: Result<Option<Scalar>, ()>,
590 ) -> InterpResult<'tcx> {
591 let this = self.eval_context_mut();
592 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(dest.ptr(), 0)?;
593 if let (
594 crate::AllocExtra {
595 data_race: AllocDataRaceHandler::Vclocks(data_race_clocks, Some(alloc_buffers)),
596 ..
597 },
598 crate::MiriMachine {
599 data_race: GlobalDataRaceHandler::Vclocks(global), threads, ..
600 },
601 ) = this.get_alloc_extra_mut(alloc_id)?
602 {
603 if atomic == AtomicWriteOrd::SeqCst {
604 global.sc_write(threads);
605 }
606
607 let range = alloc_range(base_offset, dest.layout.size);
608 // It's a bit annoying that we have to go back to the data race part to get the clock...
609 // but it does make things a lot simpler.
610 let sync_clock = data_race_clocks.sync_clock(range);
611 let buffer = alloc_buffers.get_or_create_store_buffer_mut(range, init)?;
612 buffer.buffered_write(
613 val,
614 global,
615 threads,
616 atomic == AtomicWriteOrd::SeqCst,
617 sync_clock,
618 )?;
619 }
620
621 // Caller should've written to dest with the vanilla scalar write, we do nothing here
622 interp_ok(())
623 }
624
625 /// Caller should never need to consult the store buffer for the latest value.
626 /// This function is used exclusively for failed atomic_compare_exchange_scalar
627 /// to perform load_impl on the latest store element
628 fn perform_read_on_buffered_latest(
629 &self,
630 place: &MPlaceTy<'tcx>,
631 atomic: AtomicReadOrd,
632 ) -> InterpResult<'tcx> {
633 let this = self.eval_context_ref();
634
635 if let Some(global) = this.machine.data_race.as_vclocks_ref() {
636 if atomic == AtomicReadOrd::SeqCst {
637 global.sc_read(&this.machine.threads);
638 }
639 let size = place.layout.size;
640 let (alloc_id, base_offset, ..) = this.ptr_get_alloc_id(place.ptr(), 0)?;
641 if let Some(alloc_buffers) =
642 this.get_alloc_extra(alloc_id)?.data_race.as_weak_memory_ref()
643 {
644 let Some(buffer) =
645 alloc_buffers.get_store_buffer(alloc_range(base_offset, size))?
646 else {
647 // No store buffer, nothing to do.
648 return interp_ok(());
649 };
650 buffer.read_from_last_store(
651 global,
652 &this.machine.threads,
653 atomic == AtomicReadOrd::SeqCst,
654 );
655 }
656 }
657 interp_ok(())
658 }
659}