Skip to main content

miden_processor/fast/
mod.rs

1use alloc::{boxed::Box, sync::Arc, vec, vec::Vec};
2use core::{cmp::min, ops::ControlFlow};
3
4use miden_air::{Felt, trace::RowIndex};
5use miden_core::{
6    EMPTY_WORD, WORD_SIZE, Word, ZERO,
7    mast::{ExecutableMastForest, MastForest},
8    precompile::PrecompileTranscript,
9    program::{MIN_STACK_DEPTH, Program, StackInputs, StackOutputs},
10    utils::range,
11};
12use miden_mast_package::Package;
13
14use crate::{
15    AdviceInputs, AdviceProvider, ContextId, ExecutionError, ExecutionOptions, ProcessorState,
16    advice::AdviceError,
17    continuation_stack::{Continuation, ContinuationStack},
18    errors::MapExecErrNoCtx,
19    tracer::{OperationHelperRegisters, Tracer},
20};
21
22mod basic_block;
23mod execution_api;
24mod external;
25mod memory;
26mod operation;
27mod step;
28
29pub use basic_block::SystemEventError;
30pub use memory::Memory;
31pub use step::{BreakReason, ResumeContext};
32
33#[cfg(test)]
34mod tests;
35
36// CONSTANTS
37// ================================================================================================
38
39/// The initial size of the stack buffer.
40///
41/// Note: This value is much larger than it needs to be for the majority of programs. However, some
42/// existing programs need it, so we're forced to push it up (though this should be double-checked).
43/// At this high a value, we're starting to see some performance degradation on benchmarks. For
44/// example, the blake3 benchmark went from 285 MHz to 250 MHz (~10% degradation). Perhaps a better
45/// solution would be to make this value much smaller (~1000), and then fallback to a `Vec` if the
46/// stack overflows.
47const INITIAL_STACK_BUFFER_SIZE: usize = 6850;
48
49/// The initial position of the top of the stack in the stack buffer.
50///
51/// We place this value close to 0 because if a program hits the limit, it's much more likely to hit
52/// the upper bound than the lower bound, since hitting the lower bound only occurs when you drop
53/// 0's that were generated automatically to keep the stack depth at 16. In practice, if this
54/// occurs, it is most likely a bug.
55const INITIAL_STACK_TOP_IDX: usize = 250;
56
57/// Default maximum operand stack depth preserving the previous fixed-buffer ceiling.
58const DEFAULT_MAX_STACK_DEPTH: usize =
59    INITIAL_STACK_BUFFER_SIZE - INITIAL_STACK_TOP_IDX - 1 + MIN_STACK_DEPTH;
60
61const _: [(); 1] =
62    [(); (ExecutionOptions::DEFAULT_MAX_STACK_DEPTH == DEFAULT_MAX_STACK_DEPTH) as usize];
63
64/// The stack buffer index where the logical operand stack starts after reset/recenter.
65const STACK_BUFFER_BASE_IDX: usize = INITIAL_STACK_TOP_IDX - MIN_STACK_DEPTH;
66
67// FAST PROCESSOR
68// ================================================================================================
69
70/// A fast processor which doesn't generate any trace.
71///
72/// This processor is designed to be as fast as possible. Hence, it only keeps track of the current
73/// state of the processor (i.e. the stack, current clock cycle, current memory context, and free
74/// memory pointer).
75///
76/// # Stack Management
77/// A few key points about how the stack was designed for maximum performance:
78///
79/// - The stack starts with a fixed buffer size defined by `INITIAL_STACK_BUFFER_SIZE`.
80///     - This was observed to increase performance by at least 2x compared to using a `Vec` with
81///       `push()` & `pop()`.
82///     - We track the stack top and bottom using indices `stack_top_idx` and `stack_bot_idx`,
83///       respectively.
84/// - Since we are using a fixed-size buffer, we need to ensure that stack buffer accesses are not
85///   out of bounds. Naively, we could check for this on every access. However, every operation
86///   alters the stack depth by a predetermined amount, allowing us to precisely determine the
87///   minimum number of operations required to reach a stack buffer boundary, whether at the top or
88///   bottom.
89///     - For example, if the stack top is 10 elements away from the top boundary, and the stack
90///       bottom is 15 elements away from the bottom boundary, then we can safely execute 10
91///       operations that modify the stack depth with no bounds check.
92/// - When switching contexts (e.g., during a call or syscall), all elements past the first 16 are
93///   stored in `stack_overflow_save_stack`, and the stack is truncated to 16 elements. They will be
94///   restored when returning from the call or syscall.
95///
96/// # Clock Cycle Management
97/// - The clock cycle (`clk`) is managed in the same way as in `Process`. That is, it is incremented
98///   by 1 for every row that `Process` adds to the main trace.
99///     - It is important to do so because the clock cycle is used to determine the context ID for
100///       new execution contexts when using `call` or `dyncall`.
101#[derive(Debug)]
102pub struct FastProcessor {
103    /// The stack is stored in reverse order, so that the last element is at the top of the stack.
104    stack: Box<[Felt]>,
105    /// The index of the top of the stack.
106    stack_top_idx: usize,
107    /// The index of the bottom of the stack.
108    stack_bot_idx: usize,
109
110    /// The current clock cycle.
111    clk: RowIndex,
112
113    /// The current context ID.
114    ctx: ContextId,
115
116    /// The hash of the function that called into the current context, or `[ZERO, ZERO, ZERO,
117    /// ZERO]` if we are in the first context (i.e. when `system_call_state_stack` is empty).
118    caller_hash: Word,
119
120    /// The advice provider to be used during execution.
121    advice: AdviceProvider,
122
123    /// A map from (context_id, word_address) to the word stored starting at that memory location.
124    memory: Memory,
125
126    /// Stack of saved system state, used when starting a new execution context (from a `call`,
127    /// `syscall` or `dyncall`) to keep track of the previous `(ctx, caller_hash)` upon return.
128    /// Pushed in lockstep with `stack_overflow_save_stack`.
129    system_call_state_stack: Vec<SystemCallState>,
130
131    /// Stack of saved operand-stack overflows, used when starting a new execution context to keep
132    /// the elements that lived past the top 16 of the previous context. Pushed in lockstep with
133    /// `system_call_state_stack`.
134    stack_overflow_save_stack: Vec<Vec<Felt>>,
135
136    /// Running total of the number of field elements currently held across all suspended overflow
137    /// segments in `stack_overflow_save_stack`. Maintained in lockstep with that stack so the
138    /// aggregate operand-stack depth (active context plus all suspended overflow) can be bounded
139    /// by `ExecutionOptions::max_stack_depth()` in O(1) without summing every saved segment on
140    /// each push. See [`Self::ensure_stack_capacity_for_push`].
141    saved_overflow_len: usize,
142
143    /// Options for execution, including cycle limits, stack limits, advice map limits, and the
144    /// size of core trace fragments during execution.
145    options: ExecutionOptions,
146
147    /// Transcript used to record commitments via `log_precompile` instruction (implemented via
148    /// Poseidon2 sponge).
149    pc_transcript: PrecompileTranscript,
150}
151
152impl FastProcessor {
153    /// Packages the processor state after successful execution into a public result type.
154    #[inline(always)]
155    fn into_execution_output(self, stack: StackOutputs) -> ExecutionOutput {
156        ExecutionOutput {
157            stack,
158            advice: self.advice,
159            memory: self.memory,
160            final_precompile_transcript: self.pc_transcript,
161        }
162    }
163
164    /// Converts the terminal result of a full execution run into [`ExecutionOutput`].
165    #[inline(always)]
166    fn execution_result_from_flow(
167        flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
168        processor: Self,
169    ) -> Result<ExecutionOutput, ExecutionError> {
170        match flow {
171            ControlFlow::Continue(stack_outputs) => {
172                Ok(processor.into_execution_output(stack_outputs))
173            },
174            ControlFlow::Break(break_reason) => match break_reason {
175                BreakReason::Err(err) => Err(err),
176                BreakReason::Stopped(_) => {
177                    unreachable!("Execution never stops prematurely with NeverStopper")
178                },
179            },
180        }
181    }
182
183    /// Converts a testing-only execution result into stack outputs.
184    #[cfg(any(test, feature = "testing"))]
185    #[inline(always)]
186    fn stack_result_from_flow(
187        flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
188    ) -> Result<StackOutputs, ExecutionError> {
189        match flow {
190            ControlFlow::Continue(stack_outputs) => Ok(stack_outputs),
191            ControlFlow::Break(break_reason) => match break_reason {
192                BreakReason::Err(err) => Err(err),
193                BreakReason::Stopped(_) => {
194                    unreachable!("Execution never stops prematurely with NeverStopper")
195                },
196            },
197        }
198    }
199
200    // CONSTRUCTORS
201    // ----------------------------------------------------------------------------------------------
202
203    /// Creates a new `FastProcessor` instance with the given stack inputs.
204    ///
205    /// By default, advice inputs are empty and execution options use their defaults.
206    ///
207    /// # Example
208    /// ```ignore
209    /// use miden_processor::FastProcessor;
210    ///
211    /// let processor = FastProcessor::new(stack_inputs)
212    ///     .with_advice(advice_inputs)
213    ///     .expect("advice inputs should fit advice map limits");
214    /// ```
215    ///
216    /// When using non-default advice map limits, prefer [`Self::new_with_options`] so the advice
217    /// inputs are validated against the intended execution options.
218    pub fn new(stack_inputs: StackInputs) -> Self {
219        Self::new_with_options(stack_inputs, AdviceInputs::default(), ExecutionOptions::default())
220            .expect("empty advice inputs should fit default advice map limits")
221    }
222
223    /// Sets the advice inputs for the processor.
224    ///
225    /// Advice inputs are loaded into the live advice provider immediately and are validated against
226    /// the processor's current [`ExecutionOptions`]. If the advice map needs non-default limits,
227    /// construct the processor with [`Self::new_with_options`] or call [`Self::with_options`]
228    /// before calling this method.
229    pub fn with_advice(mut self, advice_inputs: AdviceInputs) -> Result<Self, AdviceError> {
230        self.advice = AdviceProvider::new(advice_inputs, &self.options)?;
231        Ok(self)
232    }
233
234    /// Sets the execution options for the processor.
235    ///
236    /// Existing advice inputs are revalidated against the new options before they are applied. To
237    /// load advice inputs that require non-default advice map limits, call this before
238    /// [`Self::with_advice`] or use [`Self::new_with_options`].
239    pub fn with_options(mut self, options: ExecutionOptions) -> Result<Self, AdviceError> {
240        self.advice.set_options(&options)?;
241        self.memory.set_max_elements(options.max_memory_elements());
242        self.options = options;
243        Ok(self)
244    }
245
246    /// Constructor for creating a `FastProcessor` with all options specified at once.
247    ///
248    /// For a more fluent API, consider using `FastProcessor::new()` with builder methods.
249    pub fn new_with_options(
250        stack_inputs: StackInputs,
251        advice_inputs: AdviceInputs,
252        options: ExecutionOptions,
253    ) -> Result<Self, AdviceError> {
254        let stack_top_idx = INITIAL_STACK_TOP_IDX;
255        let stack = {
256            // Note: we use `Vec::into_boxed_slice()` here, since `Box::new([T; N])` first allocates
257            // the array on the stack, and then moves it to the heap. This might cause a
258            // stack overflow on some systems.
259            let mut stack = vec![ZERO; INITIAL_STACK_BUFFER_SIZE].into_boxed_slice();
260
261            // Copy inputs in reverse order so first element ends up at top of stack
262            for (i, &input) in stack_inputs.iter().enumerate() {
263                stack[stack_top_idx - 1 - i] = input;
264            }
265            stack
266        };
267
268        Ok(Self {
269            advice: AdviceProvider::new(advice_inputs, &options)?,
270            stack,
271            stack_top_idx,
272            stack_bot_idx: stack_top_idx - MIN_STACK_DEPTH,
273            clk: 0_u32.into(),
274            ctx: 0_u32.into(),
275            caller_hash: EMPTY_WORD,
276            memory: Memory::new(options.max_memory_elements()),
277            system_call_state_stack: Vec::new(),
278            stack_overflow_save_stack: Vec::new(),
279            saved_overflow_len: 0,
280            options,
281            pc_transcript: PrecompileTranscript::new(),
282        })
283    }
284
285    /// Returns the resume context to be used with the first call to `step_sync()`.
286    ///
287    /// This function asserts that `package` is not of executable type - callers should ensure that
288    /// it is before calling
289    pub fn get_initial_resume_context_for_package(
290        &mut self,
291        package: Arc<Package>,
292    ) -> Result<ResumeContext, ExecutionError> {
293        let program = package.unwrap_program();
294        let package_debug_info = package.debug_info()?.map(Arc::new);
295        let current_forest = program.mast_forest().clone();
296        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
297
298        Ok(ResumeContext {
299            current_forest,
300            continuation_stack: ContinuationStack::new(&program),
301            kernel: program.kernel().clone(),
302            package_debug_info,
303        })
304    }
305
306    /// Returns the resume context to be used with the first call to `step_sync()`.
307    pub fn get_initial_resume_context(
308        &mut self,
309        program: &Program,
310    ) -> Result<ResumeContext, ExecutionError> {
311        self.advice
312            .extend_map(program.mast_forest().advice_map())
313            .map_exec_err_no_ctx()?;
314
315        Ok(ResumeContext {
316            current_forest: program.mast_forest().clone(),
317            continuation_stack: ContinuationStack::new(program),
318            kernel: program.kernel().clone(),
319            package_debug_info: None,
320        })
321    }
322
323    // ACCESSORS
324    // -------------------------------------------------------------------------------------------
325
326    /// Returns the size of the stack.
327    #[inline(always)]
328    fn stack_size(&self) -> usize {
329        self.stack_top_idx - self.stack_bot_idx
330    }
331
332    /// Returns the stack, such that the top of the stack is at the last index of the returned
333    /// slice.
334    pub fn stack(&self) -> &[Felt] {
335        &self.stack[self.stack_bot_idx..self.stack_top_idx]
336    }
337
338    /// Returns the top 16 elements of the stack.
339    pub fn stack_top(&self) -> &[Felt] {
340        &self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
341    }
342
343    /// Returns a mutable reference to the top 16 elements of the stack.
344    pub fn stack_top_mut(&mut self) -> &mut [Felt] {
345        &mut self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
346    }
347
348    /// Returns the element on the stack at index `idx`.
349    ///
350    /// This method is only meant to be used to access the stack top by operation handlers, and
351    /// system event handlers.
352    ///
353    /// # Preconditions
354    /// - `idx` must be less than or equal to 15.
355    #[inline(always)]
356    pub fn stack_get(&self, idx: usize) -> Felt {
357        self.stack[self.stack_top_idx - idx - 1]
358    }
359
360    /// Same as [`Self::stack_get()`], but returns [`ZERO`] if `idx` falls below index 0 in the
361    /// stack buffer.
362    ///
363    /// Use this instead of `stack_get()` when `idx` may exceed 15.
364    #[inline(always)]
365    pub fn stack_get_safe(&self, idx: usize) -> Felt {
366        if idx < self.stack_top_idx {
367            self.stack[self.stack_top_idx - idx - 1]
368        } else {
369            ZERO
370        }
371    }
372
373    /// Mutable variant of `stack_get()`.
374    ///
375    /// This method is only meant to be used to access the stack top by operation handlers, and
376    /// system event handlers.
377    ///
378    /// # Preconditions
379    /// - `idx` must be less than or equal to 15.
380    #[inline(always)]
381    pub fn stack_get_mut(&mut self, idx: usize) -> &mut Felt {
382        &mut self.stack[self.stack_top_idx - idx - 1]
383    }
384
385    /// Returns the word on the stack starting at index `start_idx` in "stack order".
386    ///
387    /// For `start_idx=0` the top element of the stack will be at position 0 in the word.
388    ///
389    /// For example, if the stack looks like this:
390    ///
391    /// top                                                       bottom
392    /// v                                                           v
393    /// a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p
394    ///
395    /// Then
396    /// - `stack_get_word(0)` returns `[a, b, c, d]`,
397    /// - `stack_get_word(1)` returns `[b, c, d, e]`,
398    /// - etc.
399    ///
400    /// This method is only meant to be used to access the stack top by operation handlers, and
401    /// system event handlers.
402    ///
403    /// # Preconditions
404    /// - `start_idx` must be less than or equal to 12.
405    #[inline(always)]
406    pub fn stack_get_word(&self, start_idx: usize) -> Word {
407        // Ensure we have enough elements to form a complete word
408        debug_assert!(
409            start_idx + WORD_SIZE <= self.stack_depth() as usize,
410            "Not enough elements on stack to read word starting at index {start_idx}"
411        );
412
413        let word_start_idx = self.stack_top_idx - start_idx - WORD_SIZE;
414        let mut result: [Felt; WORD_SIZE] =
415            self.stack[range(word_start_idx, WORD_SIZE)].try_into().unwrap();
416        // Reverse so top of stack (idx 0) goes to word[0]
417        result.reverse();
418        result.into()
419    }
420
421    /// Same as [`Self::stack_get_word()`], but returns [`ZERO`] for any element that falls below
422    /// index 0 in the stack buffer.
423    ///
424    /// Use this instead of `stack_get_word()` when `start_idx + WORD_SIZE` may exceed
425    /// `stack_top_idx`.
426    #[inline(always)]
427    pub fn stack_get_word_safe(&self, start_idx: usize) -> Word {
428        let buf_end = self.stack_top_idx.saturating_sub(start_idx);
429        let buf_start = self.stack_top_idx.saturating_sub(start_idx.saturating_add(WORD_SIZE));
430        let num_elements_to_read_from_buf = buf_end - buf_start;
431
432        let mut result = [ZERO; WORD_SIZE];
433        if num_elements_to_read_from_buf == WORD_SIZE {
434            result.copy_from_slice(&self.stack[range(buf_start, WORD_SIZE)]);
435        } else if num_elements_to_read_from_buf > 0 {
436            let offset = WORD_SIZE - num_elements_to_read_from_buf;
437            result[offset..]
438                .copy_from_slice(&self.stack[range(buf_start, num_elements_to_read_from_buf)]);
439        }
440        result.reverse();
441
442        result.into()
443    }
444
445    /// Returns the number of elements on the stack in the current context.
446    #[inline(always)]
447    pub fn stack_depth(&self) -> u32 {
448        (self.stack_top_idx - self.stack_bot_idx) as u32
449    }
450
451    /// Returns a reference to the processor's memory.
452    pub fn memory(&self) -> &Memory {
453        &self.memory
454    }
455
456    /// Consumes the processor and returns the advice provider, memory, and precompile
457    /// transcript.
458    pub fn into_parts(self) -> (AdviceProvider, Memory, PrecompileTranscript) {
459        (self.advice, self.memory, self.pc_transcript)
460    }
461
462    /// Returns a reference to the execution options.
463    pub fn execution_options(&self) -> &ExecutionOptions {
464        &self.options
465    }
466
467    /// Returns a narrowed interface for reading and updating the processor state.
468    #[inline(always)]
469    pub fn state(&self) -> ProcessorState<'_> {
470        ProcessorState { processor: self }
471    }
472
473    // MUTATORS
474    // -------------------------------------------------------------------------------------------
475
476    /// Writes an element to the stack at the given index.
477    #[inline(always)]
478    pub fn stack_write(&mut self, idx: usize, element: Felt) {
479        self.stack[self.stack_top_idx - idx - 1] = element
480    }
481
482    /// Writes a word to the stack starting at the given index.
483    ///
484    /// `word[0]` goes to stack position start_idx (top), `word[1]` to start_idx+1, etc.
485    #[inline(always)]
486    pub fn stack_write_word(&mut self, start_idx: usize, word: &Word) {
487        debug_assert!(start_idx <= MIN_STACK_DEPTH - WORD_SIZE);
488
489        let word_start_idx = self.stack_top_idx - start_idx - 4;
490        let mut source: [Felt; WORD_SIZE] = (*word).into();
491        // Reverse so word[0] ends up at the top of stack (highest internal index)
492        source.reverse();
493        self.stack[range(word_start_idx, WORD_SIZE)].copy_from_slice(&source)
494    }
495
496    /// Swaps the elements at the given indices on the stack.
497    #[inline(always)]
498    pub fn stack_swap(&mut self, idx1: usize, idx2: usize) {
499        let a = self.stack_get(idx1);
500        let b = self.stack_get(idx2);
501        self.stack_write(idx1, b);
502        self.stack_write(idx2, a);
503    }
504
505    /// Increments the stack top pointer by 1.
506    ///
507    /// The bottom of the stack is never affected by this operation.
508    #[inline(always)]
509    fn increment_stack_size(&mut self) {
510        self.stack_top_idx += 1;
511    }
512
513    /// Ensures the internal stack storage can accommodate one additional logical stack element.
514    ///
515    /// The operand stack depth limit is the semantic resource bound; the buffer is only an
516    /// implementation detail. We therefore check the logical depth before allocating so a program
517    /// cannot force memory growth beyond `ExecutionOptions::max_stack_depth()`. When storage does
518    /// need to grow, it grows geometrically and remains heap-allocated as a boxed slice. A
519    /// `SmallVec` would put a useful inline buffer inside `FastProcessor`, and preallocating the
520    /// full limit would penalize ordinary programs. This policy is performance-sensitive and should
521    /// be benchmarked against the fixed-buffer baseline.
522    ///
523    /// The depth that is checked is the *aggregate* operand-stack depth: the active context's depth
524    /// plus every element held in suspended overflow segments (`saved_overflow_len`). A `call`,
525    /// `dyncall`, or `syscall` context switch hides the caller's overflow in
526    /// `stack_overflow_save_stack` rather than freeing it, so checking only the active context
527    /// would let a program nest context switches to accumulate `O(call_depth *
528    /// max_stack_depth)` hidden operand-stack memory while every live frame stayed within the
529    /// limit. Because a context switch merely moves elements between the active stack and the
530    /// saved overflow (it never creates elements), the aggregate is conserved across switches
531    /// and only grows on a push, so enforcing the bound here is sufficient to cap total
532    /// operand-stack memory.
533    #[inline(always)]
534    fn ensure_stack_capacity_for_push(&mut self) -> Result<(), ExecutionError> {
535        let depth = self.stack_size() + self.saved_overflow_len + 1;
536        let max = self.options.max_stack_depth();
537        if depth > max {
538            return Err(ExecutionError::StackDepthLimitExceeded { depth, max });
539        }
540
541        if self.stack_top_idx >= self.stack.len() - 1 {
542            self.grow_stack_buffer(self.stack_top_idx + 2);
543        }
544
545        Ok(())
546    }
547
548    fn ensure_stack_capacity_for_top_idx(&mut self, top_idx: usize) {
549        if top_idx >= self.stack.len() {
550            self.grow_stack_buffer(top_idx + 1);
551        }
552    }
553
554    fn grow_stack_buffer(&mut self, requested_min_len: usize) {
555        // The maximum allocation is tied to the logical operand stack depth, not to the current
556        // buffer position. Using `stack_bot_idx` here would make the allocation ceiling drift when
557        // the live stack has moved away from the initial base.
558        let max_len = STACK_BUFFER_BASE_IDX
559            .saturating_add(self.options.max_stack_depth())
560            .saturating_add(1);
561        let live_len = self.stack_size();
562
563        // Growth also recenters the live stack at the normal base. This keeps future push/drop
564        // behavior close to the fixed-buffer layout and avoids carrying unused prefix cells into
565        // the new allocation. The extra slot is for the next checked push that triggered growth.
566        let recentered_min_len = STACK_BUFFER_BASE_IDX.saturating_add(live_len).saturating_add(2);
567        debug_assert!(recentered_min_len <= max_len);
568
569        // Allocation growth is based on the stack's post-recentered live range, not the previous
570        // buffer length. The `requested_min_len` may be beyond the allocation cap when a shallow
571        // context is still positioned near the end of the old buffer; recentering the live stack is
572        // what makes that valid. The VM-visible requirements are that the live stack is restored at
573        // `STACK_BUFFER_BASE_IDX`, the post-recentered push slot is available, and allocation stays
574        // capped by the configured stack depth. The allocation size can differ from the previous
575        // doubling policy: normal push growth may allocate a couple of extra cells because of the
576        // spare push slot, while restoring a deep caller from a shallow callee may allocate only
577        // the requested restored range instead of doubling the old buffer. That smaller
578        // restore allocation is intentional, but it means future pushes can grow again
579        // sooner and should stay covered by benchmarks.
580        let new_len = recentered_min_len.saturating_mul(2).max(requested_min_len).min(max_len);
581        debug_assert!(new_len <= max_len);
582
583        let mut new_stack = vec![ZERO; new_len].into_boxed_slice();
584        let new_stack_bot_idx = STACK_BUFFER_BASE_IDX;
585        let new_stack_top_idx = new_stack_bot_idx + live_len;
586
587        // Only the active stack range carries VM state. Prefix/suffix cells are scratch storage and
588        // stay zeroed, which keeps growth proportional to the live depth instead of the old buffer
589        // length.
590        new_stack[new_stack_bot_idx..new_stack_top_idx]
591            .copy_from_slice(&self.stack[self.stack_bot_idx..self.stack_top_idx]);
592
593        self.stack = new_stack;
594        self.stack_bot_idx = new_stack_bot_idx;
595        self.stack_top_idx = new_stack_top_idx;
596    }
597
598    /// Decrements the stack top pointer by 1.
599    ///
600    /// The bottom of the stack is only decremented in cases where the stack depth would become less
601    /// than 16.
602    #[inline(always)]
603    fn decrement_stack_size(&mut self) {
604        if self.stack_top_idx == MIN_STACK_DEPTH {
605            // We no longer have any room in the stack buffer to decrement the stack size (which
606            // would cause the `stack_bot_idx` to go below 0). We therefore reset the stack to its
607            // original position.
608            self.reset_stack_in_buffer(INITIAL_STACK_TOP_IDX);
609        }
610
611        self.stack_top_idx -= 1;
612        self.stack_bot_idx = min(self.stack_bot_idx, self.stack_top_idx - MIN_STACK_DEPTH);
613    }
614
615    /// Resets the stack in the buffer to a new position, preserving the top 16 elements of the
616    /// stack.
617    ///
618    /// # Preconditions
619    /// - The stack is expected to have exactly 16 elements.
620    #[inline(always)]
621    fn reset_stack_in_buffer(&mut self, new_stack_top_idx: usize) {
622        debug_assert_eq!(self.stack_depth(), MIN_STACK_DEPTH as u32);
623
624        let new_stack_bot_idx = new_stack_top_idx - MIN_STACK_DEPTH;
625
626        // Copy stack to its new position
627        self.stack
628            .copy_within(self.stack_bot_idx..self.stack_top_idx, new_stack_bot_idx);
629
630        // Zero out stack below the new new_stack_bot_idx, since this is where overflow values
631        // come from, and are guaranteed to be ZERO. We don't need to zero out above
632        // `stack_top_idx`, since values there are never read before being written.
633        self.stack[0..new_stack_bot_idx].fill(ZERO);
634
635        // Update indices.
636        self.stack_bot_idx = new_stack_bot_idx;
637        self.stack_top_idx = new_stack_top_idx;
638    }
639}
640
641// EXECUTION OUTPUT
642// ===============================================================================================
643
644/// The output of a program execution, containing the state of the stack, advice provider,
645/// memory, and final precompile transcript at the end of execution.
646#[derive(Debug)]
647pub struct ExecutionOutput {
648    pub stack: StackOutputs,
649    pub advice: AdviceProvider,
650    pub memory: Memory,
651    pub final_precompile_transcript: PrecompileTranscript,
652}
653
654// SYSTEM CALL STATE
655// ===============================================================================================
656
657/// The system-state half of a saved execution context.
658///
659/// Used to keep track of the `(ctx, caller_hash)` pair that needs to be restored upon return from a
660/// `call`, `syscall` or `dyncall`.
661#[derive(Debug)]
662pub(super) struct SystemCallState {
663    pub ctx: ContextId,
664    pub caller_hash: Word,
665}
666
667// NOOP TRACER
668// ================================================================================================
669
670/// A [Tracer] that does nothing.
671pub struct NoopTracer;
672
673impl Tracer for NoopTracer {
674    type Processor = FastProcessor;
675    type Forest = Arc<MastForest>;
676
677    #[inline(always)]
678    fn start_clock_cycle(
679        &mut self,
680        _processor: &FastProcessor,
681        _continuation: Continuation<Arc<MastForest>>,
682        _continuation_stack: &ContinuationStack<Arc<MastForest>>,
683        _current_forest: &Arc<MastForest>,
684    ) {
685        // do nothing
686    }
687
688    #[inline(always)]
689    fn finalize_clock_cycle(
690        &mut self,
691        _processor: &FastProcessor,
692        _op_helper_registers: OperationHelperRegisters,
693        _current_forest: &Arc<MastForest>,
694    ) {
695        // do nothing
696    }
697}