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