4 from contextlib
import contextmanager
5 from bitarray
import bitarray
6 from vcd
import VCDWriter
7 from vcd
.gtkw
import GTKWSave
9 from ..tools
import flatten
10 from ..hdl
.ast
import *
11 from ..hdl
.ir
import *
12 from ..hdl
.xfrm
import ValueVisitor
, StatementVisitor
15 __all__
= ["Simulator", "Delay", "Tick", "Passive", "DeadlineError"]
18 class DeadlineError(Exception):
23 __slots__
= ("curr", "curr_dirty", "next", "next_dirty")
28 self
.curr_dirty
= bitarray()
29 self
.next_dirty
= bitarray()
33 self
.curr
.append(value
)
34 self
.next
.append(value
)
35 self
.curr_dirty
.append(True)
36 self
.next_dirty
.append(False)
39 def set(self
, slot
, value
):
40 if self
.next
[slot
] != value
:
41 self
.next_dirty
[slot
] = True
42 self
.next
[slot
] = value
44 def commit(self
, slot
):
45 old_value
= self
.curr
[slot
]
46 new_value
= self
.next
[slot
]
47 if old_value
!= new_value
:
48 self
.next_dirty
[slot
] = False
49 self
.curr_dirty
[slot
] = True
50 self
.curr
[slot
] = new_value
51 return old_value
, new_value
53 def flush_curr_dirty(self
):
56 slot
= self
.curr_dirty
.index(True)
59 self
.curr_dirty
[slot
] = False
62 def iter_next_dirty(self
):
66 slot
= self
.next_dirty
.index(True, start
)
73 normalize
= Const
.normalize
76 class _ValueCompiler(ValueVisitor
):
77 def on_AnyConst(self
, value
):
78 raise NotImplementedError # :nocov:
80 def on_AnySeq(self
, value
):
81 raise NotImplementedError # :nocov:
83 def on_Sample(self
, value
):
84 raise NotImplementedError # :nocov:
86 def on_Record(self
, value
):
87 return self(Cat(value
.fields
.values()))
90 class _RHSValueCompiler(_ValueCompiler
):
91 def __init__(self
, signal_slots
, sensitivity
=None, mode
="rhs"):
92 self
.signal_slots
= signal_slots
93 self
.sensitivity
= sensitivity
94 self
.signal_mode
= mode
96 def on_Const(self
, value
):
97 return lambda state
: value
.value
99 def on_Signal(self
, value
):
100 if self
.sensitivity
is not None:
101 self
.sensitivity
.add(value
)
102 if value
not in self
.signal_slots
:
103 # A signal that is neither driven nor a port always remains at its reset state.
104 return lambda state
: value
.reset
105 value_slot
= self
.signal_slots
[value
]
106 if self
.signal_mode
== "rhs":
107 return lambda state
: state
.curr
[value_slot
]
108 elif self
.signal_mode
== "lhs":
109 return lambda state
: state
.next
[value_slot
]
111 raise ValueError # :nocov:
113 def on_ClockSignal(self
, value
):
114 raise NotImplementedError # :nocov:
116 def on_ResetSignal(self
, value
):
117 raise NotImplementedError # :nocov:
119 def on_Operator(self
, value
):
120 shape
= value
.shape()
121 if len(value
.operands
) == 1:
122 arg
, = map(self
, value
.operands
)
124 return lambda state
: normalize(~
arg(state
), shape
)
126 return lambda state
: normalize(-arg(state
), shape
)
128 return lambda state
: normalize(bool(arg(state
)), shape
)
129 elif len(value
.operands
) == 2:
130 lhs
, rhs
= map(self
, value
.operands
)
132 return lambda state
: normalize(lhs(state
) + rhs(state
), shape
)
134 return lambda state
: normalize(lhs(state
) - rhs(state
), shape
)
136 return lambda state
: normalize(lhs(state
) * rhs(state
), shape
)
138 return lambda state
: normalize(lhs(state
) & rhs(state
), shape
)
140 return lambda state
: normalize(lhs(state
) |
rhs(state
), shape
)
142 return lambda state
: normalize(lhs(state
) ^
rhs(state
), shape
)
145 return lhs
<< rhs
if rhs
>= 0 else lhs
>> -rhs
146 return lambda state
: normalize(sshl(lhs(state
), rhs(state
)), shape
)
149 return lhs
>> rhs
if rhs
>= 0 else lhs
<< -rhs
150 return lambda state
: normalize(sshr(lhs(state
), rhs(state
)), shape
)
152 return lambda state
: normalize(lhs(state
) == rhs(state
), shape
)
154 return lambda state
: normalize(lhs(state
) != rhs(state
), shape
)
156 return lambda state
: normalize(lhs(state
) < rhs(state
), shape
)
158 return lambda state
: normalize(lhs(state
) <= rhs(state
), shape
)
160 return lambda state
: normalize(lhs(state
) > rhs(state
), shape
)
162 return lambda state
: normalize(lhs(state
) >= rhs(state
), shape
)
163 elif len(value
.operands
) == 3:
165 sel
, val1
, val0
= map(self
, value
.operands
)
166 return lambda state
: val1(state
) if sel(state
) else val0(state
)
167 raise NotImplementedError("Operator '{}' not implemented".format(value
.op
)) # :nocov:
169 def on_Slice(self
, value
):
170 shape
= value
.shape()
171 arg
= self(value
.value
)
173 mask
= (1 << (value
.end
- value
.start
)) - 1
174 return lambda state
: normalize((arg(state
) >> shift
) & mask
, shape
)
176 def on_Part(self
, value
):
177 shape
= value
.shape()
178 arg
= self(value
.value
)
179 shift
= self(value
.offset
)
180 mask
= (1 << value
.width
) - 1
181 return lambda state
: normalize((arg(state
) >> shift(state
)) & mask
, shape
)
183 def on_Cat(self
, value
):
184 shape
= value
.shape()
187 for opnd
in value
.parts
:
188 parts
.append((offset
, (1 << len(opnd
)) - 1, self(opnd
)))
192 for offset
, mask
, opnd
in parts
:
193 result |
= (opnd(state
) & mask
) << offset
194 return normalize(result
, shape
)
197 def on_Repl(self
, value
):
198 shape
= value
.shape()
199 offset
= len(value
.value
)
200 mask
= (1 << len(value
.value
)) - 1
202 opnd
= self(value
.value
)
205 for _
in range(count
):
207 result |
= opnd(state
)
208 return normalize(result
, shape
)
211 def on_ArrayProxy(self
, value
):
212 shape
= value
.shape()
213 elems
= list(map(self
, value
.elems
))
214 index
= self(value
.index
)
216 index_value
= index(state
)
217 if index_value
>= len(elems
):
218 index_value
= len(elems
) - 1
219 return normalize(elems
[index_value
](state
), shape
)
223 class _LHSValueCompiler(_ValueCompiler
):
224 def __init__(self
, signal_slots
, rhs_compiler
):
225 self
.signal_slots
= signal_slots
226 self
.rhs_compiler
= rhs_compiler
228 def on_Const(self
, value
):
229 raise TypeError # :nocov:
231 def on_Signal(self
, value
):
232 shape
= value
.shape()
233 value_slot
= self
.signal_slots
[value
]
234 def eval(state
, rhs
):
235 state
.set(value_slot
, normalize(rhs
, shape
))
238 def on_ClockSignal(self
, value
):
239 raise NotImplementedError # :nocov:
241 def on_ResetSignal(self
, value
):
242 raise NotImplementedError # :nocov:
244 def on_Operator(self
, value
):
245 raise TypeError # :nocov:
247 def on_Slice(self
, value
):
248 lhs_r
= self
.rhs_compiler(value
.value
)
249 lhs_l
= self(value
.value
)
251 mask
= (1 << (value
.end
- value
.start
)) - 1
252 def eval(state
, rhs
):
253 lhs_value
= lhs_r(state
)
254 lhs_value
&= ~
(mask
<< shift
)
255 lhs_value |
= (rhs
& mask
) << shift
256 lhs_l(state
, lhs_value
)
259 def on_Part(self
, value
):
260 lhs_r
= self
.rhs_compiler(value
.value
)
261 lhs_l
= self(value
.value
)
262 shift
= self
.rhs_compiler(value
.offset
)
263 mask
= (1 << value
.width
) - 1
264 def eval(state
, rhs
):
265 lhs_value
= lhs_r(state
)
266 shift_value
= shift(state
)
267 lhs_value
&= ~
(mask
<< shift_value
)
268 lhs_value |
= (rhs
& mask
) << shift_value
269 lhs_l(state
, lhs_value
)
272 def on_Cat(self
, value
):
275 for opnd
in value
.parts
:
276 parts
.append((offset
, (1 << len(opnd
)) - 1, self(opnd
)))
278 def eval(state
, rhs
):
279 for offset
, mask
, opnd
in parts
:
280 opnd(state
, (rhs
>> offset
) & mask
)
283 def on_Repl(self
, value
):
284 raise TypeError # :nocov:
286 def on_ArrayProxy(self
, value
):
287 elems
= list(map(self
, value
.elems
))
288 index
= self
.rhs_compiler(value
.index
)
289 def eval(state
, rhs
):
290 index_value
= index(state
)
291 if index_value
>= len(elems
):
292 index_value
= len(elems
) - 1
293 elems
[index_value
](state
, rhs
)
297 class _StatementCompiler(StatementVisitor
):
298 def __init__(self
, signal_slots
):
299 self
.sensitivity
= SignalSet()
300 self
.rrhs_compiler
= _RHSValueCompiler(signal_slots
, self
.sensitivity
, mode
="rhs")
301 self
.lrhs_compiler
= _RHSValueCompiler(signal_slots
, self
.sensitivity
, mode
="lhs")
302 self
.lhs_compiler
= _LHSValueCompiler(signal_slots
, self
.lrhs_compiler
)
304 def on_Assign(self
, stmt
):
305 shape
= stmt
.lhs
.shape()
306 lhs
= self
.lhs_compiler(stmt
.lhs
)
307 rhs
= self
.rrhs_compiler(stmt
.rhs
)
309 lhs(state
, normalize(rhs(state
), shape
))
312 def on_Assert(self
, stmt
):
313 raise NotImplementedError("Asserts not yet implemented for Simulator backend.") # :nocov:
315 def on_Assume(self
, stmt
):
318 def on_Switch(self
, stmt
):
319 test
= self
.rrhs_compiler(stmt
.test
)
321 for value
, stmts
in stmt
.cases
.items():
323 mask
= "".join("0" if b
== "-" else "1" for b
in value
)
324 value
= "".join("0" if b
== "-" else b
for b
in value
)
326 mask
= "1" * len(value
)
328 value
= int(value
, 2)
329 def make_test(mask
, value
):
330 return lambda test
: test
& mask
== value
331 cases
.append((make_test(mask
, value
), self
.on_statements(stmts
)))
333 test_value
= test(state
)
334 for check
, body
in cases
:
335 if check(test_value
):
340 def on_statements(self
, stmts
):
341 stmts
= [self
.on_statement(stmt
) for stmt
in stmts
]
349 def __init__(self
, fragment
, vcd_file
=None, gtkw_file
=None, traces
=()):
350 self
._fragment
= fragment
352 self
._signal
_slots
= SignalDict() # Signal -> int/slot
353 self
._slot
_signals
= list() # int/slot -> Signal
355 self
._domains
= dict() # str/domain -> ClockDomain
356 self
._domain
_triggers
= list() # int/slot -> str/domain
358 self
._signals
= SignalSet() # {Signal}
359 self
._comb
_signals
= bitarray() # {Signal}
360 self
._sync
_signals
= bitarray() # {Signal}
361 self
._user
_signals
= bitarray() # {Signal}
362 self
._domain
_signals
= dict() # str/domain -> {Signal}
364 self
._started
= False
367 self
._epsilon
= 1e-10
368 self
._fastest
_clock
= self
._epsilon
369 self
._state
= _State()
371 self
._processes
= set() # {process}
372 self
._process
_loc
= dict() # process -> str/loc
373 self
._passive
= set() # {process}
374 self
._suspended
= set() # {process}
375 self
._wait
_deadline
= dict() # process -> float/timestamp
376 self
._wait
_tick
= dict() # process -> str/domain
378 self
._funclets
= list() # int/slot -> set(lambda)
380 self
._vcd
_file
= vcd_file
381 self
._vcd
_writer
= None
382 self
._vcd
_signals
= list() # int/slot -> set(vcd_signal)
383 self
._vcd
_names
= list() # int/slot -> str/name
384 self
._gtkw
_file
= gtkw_file
385 self
._traces
= traces
387 self
._run
_called
= False
389 while not isinstance(self
._fragment
, Fragment
):
390 self
._fragment
= self
._fragment
.get_fragment(platform
=None)
393 def _check_process(process
):
394 if inspect
.isgeneratorfunction(process
):
396 if not inspect
.isgenerator(process
):
397 raise TypeError("Cannot add a process '{!r}' because it is not a generator or "
398 "a generator function"
402 def _name_process(self
, process
):
403 if process
in self
._process
_loc
:
404 return self
._process
_loc
[process
]
406 frame
= process
.gi_frame
407 return "{}:{}".format(inspect
.getfile(frame
), inspect
.getlineno(frame
))
409 def add_process(self
, process
):
410 process
= self
._check
_process
(process
)
411 self
._processes
.add(process
)
413 def add_sync_process(self
, process
, domain
="sync"):
414 process
= self
._check
_process
(process
)
419 self
._process
_loc
[sync_process
] = self
._name
_process
(process
)
420 cmd
= process
.send(result
)
424 except StopIteration:
426 sync_process
= sync_process()
427 self
.add_process(sync_process
)
429 def add_clock(self
, period
, phase
=None, domain
="sync"):
430 if self
._fastest
_clock
== self
._epsilon
or period
< self
._fastest
_clock
:
431 self
._fastest
_clock
= period
433 half_period
= period
/ 2
436 clk
= self
._domains
[domain
].clk
442 yield Delay(half_period
)
444 yield Delay(half_period
)
445 self
.add_process(clk_process
)
449 self
._vcd
_writer
= VCDWriter(self
._vcd
_file
, timescale
="100 ps",
450 comment
="Generated by nMigen")
452 root_fragment
= self
._fragment
.prepare()
453 self
._domains
= root_fragment
.domains
456 def add_fragment(fragment
, scope
=()):
457 hierarchy
[fragment
] = scope
458 for index
, (subfragment
, name
) in enumerate(fragment
.subfragments
):
460 add_fragment(subfragment
, (*scope
, "#{}".format(index
)))
462 add_fragment(subfragment
, (*scope
, name
))
463 add_fragment(root_fragment
, scope
=("top",))
465 def add_signal(signal
):
466 if signal
not in self
._signals
:
467 self
._signals
.add(signal
)
469 signal_slot
= self
._state
.add(normalize(signal
.reset
, signal
.shape()))
470 self
._signal
_slots
[signal
] = signal_slot
471 self
._slot
_signals
.append(signal
)
473 self
._comb
_signals
.append(False)
474 self
._sync
_signals
.append(False)
475 self
._user
_signals
.append(False)
476 for domain
in self
._domains
:
477 if domain
not in self
._domain
_signals
:
478 self
._domain
_signals
[domain
] = bitarray()
479 self
._domain
_signals
[domain
].append(False)
481 self
._funclets
.append(set())
483 self
._domain
_triggers
.append(None)
485 self
._vcd
_signals
.append(set())
486 self
._vcd
_names
.append(None)
488 return self
._signal
_slots
[signal
]
490 def add_domain_signal(signal
, domain
):
491 signal_slot
= add_signal(signal
)
492 self
._domain
_triggers
[signal_slot
] = domain
494 for fragment
, fragment_scope
in hierarchy
.items():
495 for signal
in fragment
.iter_signals():
498 for domain
, cd
in fragment
.domains
.items():
499 add_domain_signal(cd
.clk
, domain
)
500 if cd
.rst
is not None:
501 add_domain_signal(cd
.rst
, domain
)
503 for fragment
, fragment_scope
in hierarchy
.items():
504 for signal
in fragment
.iter_signals():
505 if not self
._vcd
_writer
:
508 signal_slot
= self
._signal
_slots
[signal
]
510 for subfragment
, name
in fragment
.subfragments
:
511 if signal
in subfragment
.ports
:
512 var_name
= "{}_{}".format(name
, signal
.name
)
515 var_name
= signal
.name
520 var_init
= signal
.decoder(signal
.reset
).replace(" ", "_")
523 var_size
= signal
.nbits
524 var_init
= signal
.reset
530 var_name_suffix
= var_name
532 var_name_suffix
= "{}${}".format(var_name
, suffix
)
533 self
._vcd
_signals
[signal_slot
].add(self
._vcd
_writer
.register_var(
534 scope
=".".join(fragment_scope
), name
=var_name_suffix
,
535 var_type
=var_type
, size
=var_size
, init
=var_init
))
536 if self
._vcd
_names
[signal_slot
] is None:
537 self
._vcd
_names
[signal_slot
] = \
538 ".".join(fragment_scope
+ (var_name_suffix
,))
541 suffix
= (suffix
or 0) + 1
543 for domain
, signals
in fragment
.drivers
.items():
544 signals_bits
= bitarray(len(self
._signals
))
545 signals_bits
.setall(False)
546 for signal
in signals
:
547 signals_bits
[self
._signal
_slots
[signal
]] = True
550 self
._comb
_signals |
= signals_bits
552 self
._sync
_signals |
= signals_bits
553 self
._domain
_signals
[domain
] |
= signals_bits
556 for signal
in fragment
.iter_comb():
557 statements
.append(signal
.eq(signal
.reset
))
558 for domain
, signal
in fragment
.iter_sync():
559 statements
.append(signal
.eq(signal
))
560 statements
+= fragment
.statements
562 compiler
= _StatementCompiler(self
._signal
_slots
)
563 funclet
= compiler(statements
)
565 def add_funclet(signal
, funclet
):
566 if signal
in self
._signal
_slots
:
567 self
._funclets
[self
._signal
_slots
[signal
]].add(funclet
)
569 for signal
in compiler
.sensitivity
:
570 add_funclet(signal
, funclet
)
571 for domain
, cd
in fragment
.domains
.items():
572 add_funclet(cd
.clk
, funclet
)
573 if cd
.rst
is not None:
574 add_funclet(cd
.rst
, funclet
)
576 self
._user
_signals
= bitarray(len(self
._signals
))
577 self
._user
_signals
.setall(True)
578 self
._user
_signals
&= ~self
._comb
_signals
579 self
._user
_signals
&= ~self
._sync
_signals
583 def _update_dirty_signals(self
):
584 """Perform the statement part of IR processes (aka RTLIL case)."""
585 # First, for all dirty signals, use sensitivity lists to determine the set of fragments
586 # that need their statements to be reevaluated because the signals changed at the previous
589 for signal_slot
in self
._state
.flush_curr_dirty():
590 funclets
.update(self
._funclets
[signal_slot
])
592 # Second, compute the values of all signals at the start of the next delta cycle, by
593 # running precompiled statements.
594 for funclet
in funclets
:
597 def _commit_signal(self
, signal_slot
, domains
):
598 """Perform the driver part of IR processes (aka RTLIL sync), for individual signals."""
599 # Take the computed value (at the start of this delta cycle) of a signal (that could have
600 # come from an IR process that ran earlier, or modified by a simulator process) and update
601 # the value for this delta cycle.
602 old
, new
= self
._state
.commit(signal_slot
)
606 # If the signal is a clock that triggers synchronous logic, record that fact.
607 if new
== 1 and self
._domain
_triggers
[signal_slot
] is not None:
608 domains
.add(self
._domain
_triggers
[signal_slot
])
611 # Finally, dump the new value to the VCD file.
612 for vcd_signal
in self
._vcd
_signals
[signal_slot
]:
613 signal
= self
._slot
_signals
[signal_slot
]
615 var_value
= signal
.decoder(new
).replace(" ", "_")
618 vcd_timestamp
= (self
._timestamp
+ self
._delta
) / self
._epsilon
619 self
._vcd
_writer
.change(vcd_signal
, vcd_timestamp
, var_value
)
621 def _commit_comb_signals(self
, domains
):
622 """Perform the comb part of IR processes (aka RTLIL always)."""
623 # Take the computed value (at the start of this delta cycle) of every comb signal and
624 # update the value for this delta cycle.
625 for signal_slot
in self
._state
.iter_next_dirty():
626 if self
._comb
_signals
[signal_slot
]:
627 self
._commit
_signal
(signal_slot
, domains
)
629 def _commit_sync_signals(self
, domains
):
630 """Perform the sync part of IR processes (aka RTLIL posedge)."""
631 # At entry, `domains` contains a list of every simultaneously triggered sync update.
633 # Advance the timeline a bit (purely for observational purposes) and commit all of them
634 # at the same timestamp.
635 self
._delta
+= self
._epsilon
636 curr_domains
, domains
= domains
, set()
639 domain
= curr_domains
.pop()
641 # Wake up any simulator processes that wait for a domain tick.
642 for process
, wait_domain
in list(self
._wait
_tick
.items()):
643 if domain
== wait_domain
:
644 del self
._wait
_tick
[process
]
645 self
._suspended
.remove(process
)
647 # Immediately run the process. It is important that this happens here,
648 # and not on the next step, when all the processes will run anyway,
649 # because Tick() simulates an edge triggered process. Like DFFs that latch
650 # a value from the previous clock cycle, simulator processes observe signal
651 # values from the previous clock cycle on a tick, too.
652 self
._run
_process
(process
)
654 # Take the computed value (at the start of this delta cycle) of every sync signal
655 # in this domain and update the value for this delta cycle. This can trigger more
656 # synchronous logic, so record that.
657 for signal_slot
in self
._state
.iter_next_dirty():
658 if self
._domain
_signals
[domain
][signal_slot
]:
659 self
._commit
_signal
(signal_slot
, domains
)
661 # Unless handling synchronous logic above has triggered more synchronous logic (which
662 # can happen e.g. if a domain is clocked off a clock divisor in fabric), we're done.
663 # Otherwise, do one more round of updates.
665 def _run_process(self
, process
):
667 cmd
= process
.send(None)
669 if type(cmd
) is Delay
:
670 if cmd
.interval
is None:
671 interval
= self
._epsilon
673 interval
= cmd
.interval
674 self
._wait
_deadline
[process
] = self
._timestamp
+ interval
675 self
._suspended
.add(process
)
678 elif type(cmd
) is Tick
:
679 self
._wait
_tick
[process
] = cmd
.domain
680 self
._suspended
.add(process
)
683 elif type(cmd
) is Passive
:
684 self
._passive
.add(process
)
686 elif type(cmd
) is Assign
:
687 lhs_signals
= cmd
.lhs
._lhs
_signals
()
688 for signal
in lhs_signals
:
689 if not signal
in self
._signals
:
690 raise ValueError("Process '{}' sent a request to set signal '{!r}', "
691 "which is not a part of simulation"
692 .format(self
._name
_process
(process
), signal
))
693 signal_slot
= self
._signal
_slots
[signal
]
694 if self
._comb
_signals
[signal_slot
]:
695 raise ValueError("Process '{}' sent a request to set signal '{!r}', "
696 "which is a part of combinatorial assignment in "
698 .format(self
._name
_process
(process
), signal
))
700 if type(cmd
.lhs
) is Signal
and type(cmd
.rhs
) is Const
:
702 self
._state
.set(self
._signal
_slots
[cmd
.lhs
],
703 normalize(cmd
.rhs
.value
, cmd
.lhs
.shape()))
705 compiler
= _StatementCompiler(self
._signal
_slots
)
706 funclet
= compiler(cmd
)
710 for signal
in lhs_signals
:
711 self
._commit
_signal
(self
._signal
_slots
[signal
], domains
)
712 self
._commit
_sync
_signals
(domains
)
714 elif type(cmd
) is Signal
:
716 cmd
= process
.send(self
._state
.curr
[self
._signal
_slots
[cmd
]])
719 elif isinstance(cmd
, Value
):
720 compiler
= _RHSValueCompiler(self
._signal
_slots
)
721 funclet
= compiler(cmd
)
722 cmd
= process
.send(funclet(self
._state
))
726 raise TypeError("Received unsupported command '{!r}' from process '{}'"
727 .format(cmd
, self
._name
_process
(process
)))
729 cmd
= process
.send(None)
731 except StopIteration:
732 self
._processes
.remove(process
)
733 self
._passive
.discard(process
)
735 except Exception as e
:
738 def step(self
, run_passive
=False):
739 # Are there any delta cycles we should run?
740 if self
._state
.curr_dirty
.any():
741 # We might run some delta cycles, and we have simulator processes waiting on
742 # a deadline. Take care to not exceed the closest deadline.
743 if self
._wait
_deadline
and \
744 (self
._timestamp
+ self
._delta
) >= min(self
._wait
_deadline
.values()):
745 # Oops, we blew the deadline. We *could* run the processes now, but this is
746 # virtually certainly a logic loop and a design bug, so bail out instead.d
747 raise DeadlineError("Delta cycles exceeded process deadline; combinatorial loop?")
750 while self
._state
.curr_dirty
.any():
751 self
._update
_dirty
_signals
()
752 self
._commit
_comb
_signals
(domains
)
753 self
._commit
_sync
_signals
(domains
)
756 # Are there any processes that haven't had a chance to run yet?
757 if len(self
._processes
) > len(self
._suspended
):
758 # Schedule an arbitrary one.
759 process
= (self
._processes
- set(self
._suspended
)).pop()
760 self
._run
_process
(process
)
763 # All processes are suspended. Are any of them active?
764 if len(self
._processes
) > len(self
._passive
) or run_passive
:
765 # Are any of them suspended before a deadline?
766 if self
._wait
_deadline
:
767 # Schedule the one with the lowest deadline.
768 process
, deadline
= min(self
._wait
_deadline
.items(), key
=lambda x
: x
[1])
769 del self
._wait
_deadline
[process
]
770 self
._suspended
.remove(process
)
771 self
._timestamp
= deadline
773 self
._run
_process
(process
)
776 # No processes, or all processes are passive. Nothing to do!
780 self
._run
_called
= True
785 def run_until(self
, deadline
, run_passive
=False):
786 self
._run
_called
= True
788 while self
._timestamp
< deadline
:
789 if not self
.step(run_passive
):
794 def __exit__(self
, *args
):
795 if not self
._run
_called
:
796 warnings
.warn("Simulation created, but not run", UserWarning)
799 vcd_timestamp
= (self
._timestamp
+ self
._delta
) / self
._epsilon
800 self
._vcd
_writer
.close(vcd_timestamp
)
802 if self
._vcd
_file
and self
._gtkw
_file
:
803 gtkw_save
= GTKWSave(self
._gtkw
_file
)
804 if hasattr(self
._vcd
_file
, "name"):
805 gtkw_save
.dumpfile(self
._vcd
_file
.name
)
806 if hasattr(self
._vcd
_file
, "tell"):
807 gtkw_save
.dumpfile_size(self
._vcd
_file
.tell())
809 gtkw_save
.treeopen("top")
810 gtkw_save
.zoom_markers(math
.log(self
._epsilon
/ self
._fastest
_clock
) - 14)
812 def add_trace(signal
, **kwargs
):
813 signal_slot
= self
._signal
_slots
[signal
]
814 if self
._vcd
_names
[signal_slot
] is not None:
816 suffix
= "[{}:0]".format(len(signal
) - 1)
819 gtkw_save
.trace(self
._vcd
_names
[signal_slot
] + suffix
, **kwargs
)
821 for domain
, cd
in self
._domains
.items():
822 with gtkw_save
.group("d.{}".format(domain
)):
823 if cd
.rst
is not None:
827 for signal
in self
._traces
:
831 self
._vcd
_file
.close()
833 self
._gtkw
_file
.close()