API reference

fhdl.structure module

class migen.fhdl.structure.Array[source]

Bases: list

Addressable multiplexer

An array is created from an iterable of values and indexed using the usual Python simple indexing notation (no negative indices or slices). It can be indexed by numeric constants, _Value s, or Signal s.

The result of indexing the array is a proxy for the entry at the given index that can be used on either RHS or LHS of assignments.

An array can be indexed multiple times.

Multidimensional arrays are supported by packing inner arrays into outer arrays.

Parameters:values (iterable of ints, _Values, Signals) – Entries of the array. Each entry can be a numeric constant, a Signal or a Record.

Examples

>>> a = Array(range(10))
>>> b = Signal(max=10)
>>> c = Signal(max=10)
>>> b.eq(a[9 - c])
migen.fhdl.structure.C[source]

alias of migen.fhdl.structure.Constant

class migen.fhdl.structure.Case(test, cases)[source]

Bases: migen.fhdl.structure._Statement

Case/Switch statement

Parameters:
  • test (_Value, in) – Selector value used to decide which block to execute
  • cases (dict) – Dictionary of cases. The keys are numeric constants to compare with test. The values are statements to be executed the corresponding key matches test. The dictionary may contain a string key “default” to mark a fall-through case that is executed if no other key matches.

Examples

>>> a = Signal()
>>> b = Signal()
>>> Case(a, {
...     0:         b.eq(1),
...     1:         b.eq(0),
...     "default": b.eq(0),
... })
makedefault(key=None)[source]

Mark a key as the default case

Deletes/substitutes any previously existing default case.

Parameters:key (int, Constant or None) – Key to use as default case if no other key matches. By default, the largest key is the default key.
class migen.fhdl.structure.Cat(*args)[source]

Bases: migen.fhdl.structure._Value

Concatenate values

Form a compound _Value from several smaller ones by concatenation. The first argument occupies the lower bits of the result. The return value can be used on either side of an assignment, that is, the concatenated value can be used as an argument on the RHS or as a target on the LHS. If it is used on the LHS, it must solely consist of Signal s, slices of Signal s, and other concatenations meeting these properties. The bit length of the return value is the sum of the bit lengths of the arguments:

len(Cat(args)) == sum(len(arg) for arg in args)
Parameters:*args (_Values or iterables of _Values, inout) – _Value s to be concatenated.
Returns:Resulting _Value obtained by concatentation.
Return type:Cat, inout
class migen.fhdl.structure.ClockDomain(name=None, reset_less=False)[source]

Bases: object

Synchronous domain

Parameters:
  • name (str or None) – Domain name. If None (the default) the name is inferred from the variable name this ClockDomain is assigned to (stripping any “cd_” prefix).
  • reset_less (bool) – The domain does not use a reset signal. Registers within this domain are still all initialized to their reset state once, e.g. through Verilog “initial” statements.
clk

Signal, inout – The clock for this domain. Can be driven or used to drive other signals (preferably in combinatorial context).

rst

Signal or None, inout – Reset signal for this domain. Can be driven or used to drive.

rename(new_name)[source]

Rename the clock domain

Parameters:new_name (str) – New name
class migen.fhdl.structure.ClockSignal(cd='sys')[source]

Bases: migen.fhdl.structure._Value

Clock signal for a given clock domain

ClockSignal s for a given clock domain can be retrieved multiple times. They all ultimately refer to the same signal.

Parameters:cd (str) – Clock domain to obtain a clock signal for. Defaults to “sys”.
class migen.fhdl.structure.Constant(value, bits_sign=None)[source]

Bases: migen.fhdl.structure._Value

A constant, HDL-literal integer _Value

Parameters:
  • value (int) –
  • bits_sign (int or tuple or None) – Either an integer bits or a tuple (bits, signed) specifying the number of bits in this Constant and whether it is signed (can represent negative values). bits_sign defaults to the minimum width and signedness of value.
class migen.fhdl.structure.DUID[source]

Bases: object

Deterministic Unique IDentifier

class migen.fhdl.structure.If(cond, *t)[source]

Bases: migen.fhdl.structure._Statement

Conditional execution of statements

Parameters:
  • cond (_Value(1), in) – Condition
  • *t (Statements) – Statements to execute if cond is asserted.

Examples

>>> a = Signal()
>>> b = Signal()
>>> c = Signal()
>>> d = Signal()
>>> If(a,
...     b.eq(1)
... ).Elif(c,
...     b.eq(0)
... ).Else(
...     b.eq(d)
... )
Elif(cond, *t)[source]

Add an else if conditional block

Parameters:
  • cond (_Value(1), in) – Condition
  • *t (Statements) – Statements to execute if previous conditions fail and cond is asserted.
Else(*f)[source]

Add an else conditional block

Parameters:*f (Statements) – Statements to execute if all previous conditions fail.
migen.fhdl.structure.Mux(sel, val1, val0)[source]

Multiplex between two values

Parameters:
  • sel (_Value(1), in) – Selector.
  • val1 (_Value(N), in) –
  • val0 (_Value(N), in) – Input values.
Returns:

Output _Value. If sel is asserted, the Mux returns val1, else val0.

Return type:

_Value(N), out

class migen.fhdl.structure.Replicate(v, n)[source]

Bases: migen.fhdl.structure._Value

Replicate a value

An input value is replicated (repeated) several times to be used on the RHS of assignments:

len(Replicate(s, n)) == len(s)*n
Parameters:
  • v (_Value, in) – Input value to be replicated.
  • n (int) – Number of replications.
Returns:

Replicated value.

Return type:

Replicate, out

class migen.fhdl.structure.ResetSignal(cd='sys', allow_reset_less=False)[source]

Bases: migen.fhdl.structure._Value

Reset signal for a given clock domain

ResetSignal s for a given clock domain can be retrieved multiple times. They all ultimately refer to the same signal.

Parameters:
  • cd (str) – Clock domain to obtain a reset signal for. Defaults to “sys”.
  • allow_reset_less (bool) – If the clock domain is resetless, return 0 instead of reporting an error.
class migen.fhdl.structure.Signal(bits_sign=None, name=None, variable=False, reset=0, reset_less=False, name_override=None, min=None, max=None, related=None, attr=None)[source]

Bases: migen.fhdl.structure._Value

A _Value that can change

The Signal object represents a value that is expected to change in the circuit. It does exactly what Verilog’s wire and reg and VHDL’s signal do.

A Signal can be indexed to access a subset of its bits. Negative indices (signal[-1]) and the extended Python slicing notation (signal[start:stop:step]) are supported. The indices 0 and -1 are the least and most significant bits respectively.

Parameters:
  • bits_sign (int or tuple) – Either an integer bits or a tuple (bits, signed) specifying the number of bits in this Signal and whether it is signed (can represent negative values). signed defaults to False.
  • name (str or None) – Name hint for this signal. If None (default) the name is inferred from the variable name this Signal is assigned to. Name collisions are automatically resolved by prepending names of objects that contain this Signal and by appending integer sequences.
  • variable (bool) – Deprecated.
  • reset (int) – Reset (synchronous) or default (combinatorial) value. When this Signal is assigned to in synchronous context and the corresponding clock domain is reset, the Signal assumes the given value. When this Signal is unassigned in combinatorial context (due to conditional assignments not being taken), the Signal assumes its reset value. Defaults to 0.
  • reset_less (bool) – If True, do not generate reset logic for this Signal in synchronous statements. The reset value is only used as a combinatorial default or as the initial value. Defaults to False.
  • name_override (str or None) – Do not use the inferred name but the given one.
  • min (int or None) –
  • max (int or None) – If bits_sign is None, the signal bit width and signedness are determined by the integer range given by min (inclusive, defaults to 0) and max (exclusive, defaults to 2).
  • related (Signal or None) –
  • attr (set of synthesis attributes) –
classmethod like(other, **kwargs)[source]

Create Signal based on another.

Parameters:
  • other (_Value) – Object to base this Signal on.
  • migen.fhdl.bitcontainer.value_bits_sign for details. (See) –
migen.fhdl.structure.wrap(value)[source]

Ensures that the passed object is a Migen value. Booleans and integers are automatically wrapped into Constant.

fhdl.bitcontainer module

migen.fhdl.bitcontainer.value_bits_sign(v)[source]

Bit length and signedness of a value.

Parameters:v (Value) –
Returns:Number of bits required to store v or available in v, followed by whether v has a sign bit (included in the bit count).
Return type:int, bool

Examples

>>> value_bits_sign(f.Signal(8))
8, False
>>> value_bits_sign(C(0xaa))
8, False

genlib.fifo module

class migen.genlib.fifo.SyncFIFO(width, depth, fwft=True)[source]

Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInterface

Synchronous FIFO (first in, first out)

Read and write interfaces are accessed from the same clock domain. If different clock domains are needed, use AsyncFIFO.

Data written to the input interface (din, we, writable) is buffered and can be read at the output interface (dout, re, readable). The data entry written first to the input also appears first on the output.

Parameters:
  • width (int) – Bit width for the data.
  • depth (int) – Depth of the FIFO.
din

in, width – Input data

writable

out – There is space in the FIFO and we can be asserted to load new data.

we

in – Write enable signal to latch din into the FIFO. Does nothing if writable is not asserted.

dout

out, width – Output data. Only valid if readable is asserted.

readable

out – Output data dout valid, FIFO not empty.

re

in – Acknowledge dout. If asserted, the next entry will be available on the next cycle (if readable is high then).

level

out – Number of unread entries.

replace

in – Replaces the last entry written into the FIFO with din. Does nothing if that entry has already been read (i.e. the FIFO is empty). Assert in conjunction with we.

class migen.genlib.fifo.SyncFIFOBuffered(width, depth)[source]

Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInterface

Has an interface compatible with SyncFIFO with fwft=True, but does not use asynchronous RAM reads that are not compatible with block RAMs. Increases latency by one cycle.

class migen.genlib.fifo.AsyncFIFO(width, depth)[source]

Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInterface

Asynchronous FIFO (first in, first out)

Read and write interfaces are accessed from different clock domains, named read and write. Use ClockDomainsRenamer to rename to other names.

Data written to the input interface (din, we, writable) is buffered and can be read at the output interface (dout, re, readable). The data entry written first to the input also appears first on the output.

Parameters:
  • width (int) – Bit width for the data.
  • depth (int) – Depth of the FIFO.
din

in, width – Input data

writable

out – There is space in the FIFO and we can be asserted to load new data.

we

in – Write enable signal to latch din into the FIFO. Does nothing if writable is not asserted.

dout

out, width – Output data. Only valid if readable is asserted.

readable

out – Output data dout valid, FIFO not empty.

re

in – Acknowledge dout. If asserted, the next entry will be available on the next cycle (if readable is high then).

class migen.genlib.fifo.AsyncFIFOBuffered(width, depth)[source]

Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInterface

Improves timing when it breaks due to sluggish clock-to-output delay in e.g. Xilinx block RAMs. Increases latency by one cycle.

genlib.coding module

Encoders and decoders between binary and one-hot representation

class migen.genlib.coding.Decoder(width)[source]

Bases: migen.fhdl.module.Module

Decode binary to one-hot

If n is low, the i th bit in o is asserted, the others are not, else o == 0.

Parameters:width (int) – Bit width of the output
i

Signal(max=width), in – Input binary

o

Signal(width), out – Decoded one-hot

n

Signal(1), in – Invalid, no output bits are to be asserted

class migen.genlib.coding.Encoder(width)[source]

Bases: migen.fhdl.module.Module

Encode one-hot to binary

If n is low, the o th bit in i is asserted, else none or multiple bits are asserted.

Parameters:width (int) – Bit width of the input
i

Signal(width), in – One-hot input

o

Signal(max=width), out – Encoded binary

n

Signal(1), out – Invalid, either none or multiple input bits are asserted

class migen.genlib.coding.PriorityDecoder(width)[source]

Bases: migen.genlib.coding.Decoder

class migen.genlib.coding.PriorityEncoder(width)[source]

Bases: migen.fhdl.module.Module

Priority encode requests to binary

If n is low, the o th bit in i is asserted and the bits below o are unasserted, else o == 0. The LSB has priority.

Parameters:width (int) – Bit width of the input
i

Signal(width), in – Input requests

o

Signal(max=width), out – Encoded binary

n

Signal(1), out – Invalid, no input bits are asserted

genlib.sort module

class migen.genlib.sort.BitonicSort(n, m, ascending=True)[source]

Bases: migen.fhdl.module.Module

Combinatorial sorting network

The Bitonic sort is implemented as a combinatorial sort using comparators and multiplexers. Its asymptotic complexity (in terms of number of comparators/muxes) is O(n log(n)**2), like mergesort or shellsort.

http://www.dps.uibk.ac.at/~cosenza/teaching/gpu/sort-batcher.pdf

http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm

http://www.myhdl.org/doku.php/cookbook:bitonic

Parameters:
  • n (int) – Number of inputs and output signals.
  • m (int) – Bit width of inputs and outputs. Or a tuple of (m, signed).
  • ascending (bool) – Sort direction. True if input is to be sorted ascending, False for descending. Defaults to ascending.
i

list of Signals, in – Input values, each m wide.

o

list of Signals, out – Output values, sorted, each m bits wide.

genlib.fsm module

class migen.genlib.fsm.FSM(reset_state=None)[source]

Bases: migen.fhdl.module.Module

Finite state machine

Any Python objects can be used as states, e.g. strings.

Parameters:reset_state – Reset state. Defaults to the first added state.

Examples

>>> self.active = Signal()
>>> self.bitno = Signal(3)
>>>
>>> fsm = FSM(reset_state="START")
>>> self.submodules += fsm
>>>
>>> fsm.act("START",
...     self.active.eq(1),
...     If(strobe,
...         NextState("DATA")
...     )
... )
>>> fsm.act("DATA",
...     self.active.eq(1),
...     If(strobe,
...         NextValue(self.bitno, self.bitno + 1),
...         If(self.bitno == 7,
...             NextState("END")
...         )
...     )
... )
>>> fsm.act("END",
...     self.active.eq(0),
...     NextState("STOP")
... )
act(state, *statements)[source]

Schedules statements to be executed in state. Statements may include:

  • combinatorial statements of form a.eq(b), equivalent to self.comb += a.eq(b) when the FSM is in the given state;
  • synchronous statements of form NextValue(a, b), equivalent to self.sync += a.eq(b) when the FSM is in the given state;
  • a statement of form NextState(new_state), selecting the next state;
  • If, Case, etc.
ongoing(state)[source]

Returns a signal that has the value 1 when the FSM is in the given state, and 0 otherwise.