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