43f0964e53cc9d1a8424a6de2d8c44a7f70133cb
[nmigen.git] / docs / lang.rst
1 Language guide
2 ##############
3
4 .. warning::
5
6 This guide is a work in progress and is seriously incomplete!
7
8 This guide introduces the nMigen language in depth. It assumes familiarity with synchronous digital logic and the Python programming language, but does not require prior experience with any hardware description language. See the :doc:`tutorial <tutorial>` for a step-by-step introduction to the language.
9
10 .. TODO: link to a good synchronous logic tutorial and a Python tutorial?
11
12
13 .. _lang-prelude:
14
15 The prelude
16 ===========
17
18 Because nMigen is a regular Python library, it needs to be imported before use. The root ``nmigen`` module, called *the prelude*, is carefully curated to export a small amount of the most essential names, useful in nearly every design. In source files dedicated to nMigen code, it is a good practice to use a :ref:`glob import <python:tut-pkg-import-star>` for readability:
19
20 .. code-block::
21
22 from nmigen import *
23
24 However, if a source file uses nMigen together with other libraries, or if glob imports are frowned upon, it is conventional to use a short alias instead:
25
26 .. code-block::
27
28 import nmigen as nm
29
30 All of the examples below assume that a glob import is used.
31
32 .. testsetup::
33
34 from nmigen import *
35
36
37 .. _lang-values:
38
39 Values
40 ======
41
42 The basic building block of the nMigen language is a *value*, which is a term for a binary number that is computed or stored anywhere in the design. Each value has a *width*---the amount of bits used to represent the value---and a *signedness*---the interpretation of the value by arithmetic operations---collectively called its *shape*. Signed values always use `two's complement`_ representation.
43
44 .. _two's complement: https://en.wikipedia.org/wiki/Two's_complement
45
46
47 .. _lang-constants:
48
49 Constants
50 =========
51
52 The simplest nMigen value is a *constant*, representing a fixed number, and introduced using ``Const(...)`` or its short alias ``C(...)``:
53
54 .. doctest::
55
56 >>> ten = Const(10)
57 >>> minus_two = C(-2)
58
59 The code above does not specify any shape for the constants. If the shape is omitted, nMigen uses unsigned shape for positive numbers and signed shape for negative numbers, with the width inferred from the smallest amount of bits necessary to represent the number. As a special case, in order to get the same inferred shape for ``True`` and ``False``, ``0`` is considered to be 1-bit unsigned.
60
61 .. doctest::
62
63 >>> ten.shape()
64 unsigned(4)
65 >>> minus_two.shape()
66 signed(2)
67 >>> C(0).shape()
68 unsigned(1)
69
70 The shape of the constant can be specified explicitly, in which case the number's binary representation will be truncated or extended to fit the shape. Although rarely useful, 0-bit constants are permitted.
71
72 .. doctest::
73
74 >>> Const(360, unsigned(8)).value
75 104
76 >>> Const(129, signed(8)).value
77 -127
78 >>> Const(1, unsigned(0)).value
79 0
80
81
82 .. _lang-shapes:
83
84 Shapes
85 ======
86
87 A ``Shape`` is an object with two attributes, ``.width`` and ``.signed``. It can be constructed directly:
88
89 .. doctest::
90
91 >>> Shape(width=5, signed=False)
92 unsigned(5)
93 >>> Shape(width=12, signed=True)
94 signed(12)
95
96 However, in most cases, the shape is always constructed with the same signedness, and the aliases ``signed`` and ``unsigned`` are more convenient:
97
98 .. doctest::
99
100 >>> unsigned(5) == Shape(width=5, signed=False)
101 True
102 >>> signed(12) == Shape(width=12, signed=True)
103 True
104
105
106 Shapes of values
107 ----------------
108
109 All values have a ``.shape()`` method that computes their shape. The width of a value ``v``, ``v.shape().width``, can also be retrieved with ``len(v)``.
110
111 .. doctest::
112
113 >>> Const(5).shape()
114 unsigned(3)
115 >>> len(Const(5))
116 3
117
118
119 .. _lang-shapecasting:
120
121 Shape casting
122 =============
123
124 Shapes can be *cast* from other objects, which are called *shape-castable*. Casting is a convenient way to specify a shape indirectly, for example, by a range of numbers representable by values with that shape.
125
126 Casting to a shape can be done explicitly with ``Shape.cast``, but is usually implicit, since shape-castable objects are accepted anywhere shapes are.
127
128
129 Shapes from integers
130 --------------------
131
132 Casting a shape from an integer ``i`` is a shorthand for constructing a shape with ``unsigned(i)``:
133
134 .. doctest::
135
136 >>> Shape.cast(5)
137 unsigned(5)
138 >>> C(0, 3).shape()
139 unsigned(3)
140
141
142 Shapes from ranges
143 ------------------
144
145 Casting a shape from a :py:class:`range` ``r`` produces a shape that:
146
147 * has a width large enough to represent both ``min(r)`` and ``max(r)``, and
148 * is signed if either ``min(r)`` or ``max(r)`` are negative, unsigned otherwise.
149
150 Specifying a shape with a range is convenient for counters, indexes, and all other values whose width is derived from a set of numbers they must be able to fit:
151
152 .. doctest::
153
154 >>> Const(0, range(100)).shape()
155 unsigned(7)
156 >>> items = [1, 2, 3]
157 >>> C(1, range(len(items))).shape()
158 unsigned(2)
159
160 .. _lang-exclrange:
161
162 .. warning::
163
164 Python ranges are *exclusive* or *half-open*, meaning they do not contain their ``.stop`` element. Because of this, values with shapes cast from a ``range(stop)`` where ``stop`` is a power of 2 are not wide enough to represent ``stop`` itself:
165
166 .. doctest::
167
168 >>> fencepost = C(256, range(256))
169 >>> fencepost.shape()
170 unsigned(8)
171 >>> fencepost.value
172 0
173
174 Be mindful of this edge case!
175
176
177 Shapes from enumerations
178 ------------------------
179
180 Casting a shape from an :py:class:`enum.Enum` subclass ``E``:
181
182 * fails if any of the enumeration members have non-integer values,
183 * has a width large enough to represent both ``min(m.value for m in E)`` and ``max(m.value for m in E)``, and
184 * is signed if either ``min(m.value for m in E)`` or ``max(m.value for m in E)`` are negative, unsigned otherwise.
185
186 Specifying a shape with an enumeration is convenient for finite state machines, multiplexers, complex control signals, and all other values whose width is derived from a few distinct choices they must be able to fit:
187
188 .. testsetup::
189
190 import enum
191
192 .. testcode::
193
194 class Direction(enum.Enum):
195 TOP = 0
196 LEFT = 1
197 BOTTOM = 2
198 RIGHT = 3
199
200 .. doctest::
201
202 >>> Shape.cast(Direction)
203 unsigned(2)
204
205 .. note::
206
207 The enumeration does not have to subclass :py:class:`enum.IntEnum`; it only needs to have integers as values of every member. Using enumerations based on :py:class:`enum.Enum` rather than :py:class:`enum.IntEnum` prevents unwanted implicit conversion of enum members to integers.
208
209
210 .. _lang-valuecasting:
211
212 Value casting
213 =============
214
215 Like shapes, values may be *cast* from other objects, which are called *value-castable*. Casting allows objects that are not provided by nMigen, such as integers or enumeration members, to be used in nMigen expressions directly.
216
217 .. TODO: link to UserValue
218
219 Casting to a value can be done explicitly with ``Value.cast``, but is usually implicit, since value-castable objects are accepted anywhere values are.
220
221
222 Values from integers
223 --------------------
224
225 Casting a value from an integer ``i`` is a shorthand for ``Const(i)``:
226
227 .. doctest::
228
229 >>> Value.cast(5)
230 (const 3'd5)
231
232
233 Values from enumeration members
234 -------------------------------
235
236 Casting a value from an enumeration member ``m`` is a shorthand for ``Const(m.value, type(m))``:
237
238 .. doctest::
239
240 >>> Value.cast(Direction.LEFT)
241 (const 2'd1)
242
243
244 .. _lang-signals:
245
246 Signals
247 =======
248
249 .. |emph:assigned| replace:: *assigned*
250 .. _emph:assigned: #lang-assigns
251
252 A *signal* is a value representing a (potentially) varying number. Signals can be |emph:assigned|_ in a :ref:`combinatorial <lang-comb>` or :ref:`synchronous <lang-sync>` domain, in which case they are generated as wires or registers, respectively. Signals always have a well-defined value; they cannot be uninitialized or undefined.
253
254
255 Signal shapes
256 -------------
257
258 A signal can be created with an explicitly specified shape (any :ref:`shape-castable <lang-shapecasting>` object); if omitted, the shape defaults to ``unsigned(1)``. Although rarely useful, 0-bit signals are permitted.
259
260 .. doctest::
261
262 >>> Signal().shape()
263 unsigned(1)
264 >>> Signal(4).shape()
265 unsigned(4)
266 >>> Signal(range(-8, 7)).shape()
267 signed(4)
268 >>> Signal(Direction).shape()
269 unsigned(2)
270 >>> Signal(0).shape()
271 unsigned(0)
272
273
274 .. _lang-signalname:
275
276 Signal names
277 ------------
278
279 Each signal has a *name*, which is used in the waveform viewer, diagnostic messages, Verilog output, and so on. In most cases, the name is omitted and inferred from the name of the variable or attribute the signal is placed into:
280
281 .. testsetup::
282
283 class dummy(object): pass
284 self = dummy()
285
286 .. doctest::
287
288 >>> foo = Signal()
289 >>> foo.name
290 'foo'
291 >>> self.bar = Signal()
292 >>> self.bar.name
293 'bar'
294
295 However, the name can also be specified explicitly with the ``name=`` parameter:
296
297 .. doctest::
298
299 >>> foo2 = Signal(name="second_foo")
300 >>> foo2.name
301 'second_foo'
302
303 The names do not need to be unique; if two signals with the same name end up in the same namespace while preparing for simulation or synthesis, one of them will be renamed to remove the ambiguity.
304
305
306 .. _lang-initial:
307
308 Initial signal values
309 ---------------------
310
311 Each signal has an *initial value*, specified with the ``reset=`` parameter. If the initial value is not specified explicitly, zero is used by default. An initial value can be specified with an integer or an enumeration member.
312
313 Signals :ref:`assigned <lang-assigns>` in a :ref:`combinatorial <lang-comb>` domain assume their initial value when none of the assignments are :ref:`active <lang-active>`. Signals assigned in a :ref:`synchronous <lang-sync>` domain assume their initial value after *power-on reset* and, unless the signal is :ref:`reset-less <lang-resetless>`, *explicit reset*. Signals that are used but never assigned are equivalent to constants of their initial value.
314
315 .. TODO: using "reset" for "initial value" is awful, let's rename it to "init"
316
317 .. doctest::
318
319 >>> Signal(4).reset
320 0
321 >>> Signal(4, reset=5).reset
322 5
323 >>> Signal(Direction, reset=Direction.LEFT).reset
324 1
325
326
327 .. _lang-resetless:
328
329 Reset-less signals
330 ------------------
331
332 Signals assigned in a :ref:`synchronous <lang-sync>` domain can be *resettable* or *reset-less*, specified with the ``reset_less=`` parameter. If the parameter is not specified, signals are resettable by default. Resettable signals assume their :ref:`initial value <lang-initial>` on explicit reset, which can be asserted via the clock domain or by using ``ResetInserter``. Reset-less signals are not affected by explicit reset.
333
334 .. TODO: link to clock domain and ResetInserter docs
335
336 Signals assigned in a :ref:`combinatorial <lang-comb>` domain are not affected by the ``reset_less`` parameter.
337
338 .. doctest::
339
340 >>> Signal().reset_less
341 False
342 >>> Signal(reset_less=True).reset_less
343 True
344
345
346 .. _lang-operators:
347
348 Operators
349 =========
350
351 To describe computations, nMigen values can be combined with each other or with :ref:`value-castable <lang-valuecasting>` objects using a rich array of arithmetic, bitwise, logical, bit sequence, and other *operators* to form *expressions*, which are themselves values.
352
353
354 .. _lang-abstractexpr:
355
356 Performing or describing computations?
357 --------------------------------------
358
359 Code written in the Python language *performs* computations on concrete objects, like integers, with the goal of calculating a concrete result:
360
361 .. doctest::
362
363 >>> a = 5
364 >>> a + 1
365 6
366
367 In contrast, code written in the nMigen language *describes* computations on abstract objects, like :ref:`signals <lang-signals>`, with the goal of generating a hardware *circuit* that can be simulated, synthesized, and so on. nMigen expressions are ordinary Python objects that represent parts of this circuit:
368
369 .. doctest::
370
371 >>> a = Signal(8, reset=5)
372 >>> a + 1
373 (+ (sig a) (const 1'd1))
374
375 Although the syntax is similar, it is important to remember that nMigen values exist on a higher level of abstraction than Python values. For example, expressions that include nMigen values cannot be used in Python control flow structures:
376
377 .. doctest::
378
379 >>> if a == 0:
380 ... print("Zero!")
381 Traceback (most recent call last):
382 ...
383 TypeError: Attempted to convert nMigen value to Python boolean
384
385 Because the value of ``a``, and therefore ``a == 0``, is not known at the time when the ``if`` statement is executed, there is no way to decide whether the body of the statement should be executed---in fact, if the design is synthesized, by the time ``a`` has any concrete value, the Python program has long finished! To solve this problem, nMigen provides its own :ref:`control structures <lang-control>` that, also, manipulate circuits.
386
387
388 .. _lang-widthext:
389
390 Width extension
391 ---------------
392
393 Many of the operations described below (for example, addition, equality, bitwise OR, and part select) extend the width of one or both operands to match the width of the expression. When this happens, unsigned values are always zero-extended and signed values are always sign-extended regardless of the operation or signedness of the result.
394
395
396 .. _lang-arithops:
397
398 Arithmetic operators
399 --------------------
400
401 Most arithmetic operations on integers provided by Python can be used on nMigen values, too.
402
403 Although Python integers have unlimited precision and nMigen values are represented with a :ref:`finite amount of bits <lang-values>`, arithmetics on nMigen values never overflows because the width of the arithmetic expression is always sufficient to represent all possible results.
404
405 .. doctest::
406
407 >>> a = Signal(8)
408 >>> (a + 1).shape() # needs to represent 1 to 256
409 unsigned(9)
410
411 Similarly, although Python integers are always signed and nMigen values can be either :ref:`signed or unsigned <lang-values>`, if any of the operands of an nMigen arithmetic expression is signed, the expression itself is also signed, matching the behavior of Python.
412
413 .. doctest::
414
415 >>> a = Signal(unsigned(8))
416 >>> b = Signal(signed(8))
417 >>> (a + b).shape() # needs to represent -128 to 382
418 signed(10)
419
420 While arithmetic computations never result in an overflow, :ref:`assigning <lang-assigns>` their results to signals may truncate the most significant bits.
421
422 The following table lists the arithmetic operations provided by nMigen:
423
424 ============ ========================== ======
425 Operation Description Notes
426 ============ ========================== ======
427 ``a + b`` addition
428 ``-a`` negation
429 ``a - b`` subtraction
430 ``a * b`` multiplication
431 ``a // b`` floor division [#opA1]_
432 ``a % b`` modulo [#opA1]_
433 ``abs(a)`` absolute value
434 ============ ========================== ======
435
436 .. [#opA1] Divisor must be unsigned; this is an nMigen limitation that may be lifted in the future.
437
438
439 .. _lang-cmpops:
440
441 Comparison operators
442 --------------------
443
444 All comparison operations on integers provided by Python can be used on nMigen values. However, due to a limitation of Python, chained comparisons (e.g. ``a < b < c``) cannot be used.
445
446 Similar to arithmetic operations, if any operand of a comparison expression is signed, a signed comparison is performed. The result of a comparison is a 1-bit unsigned value.
447
448 The following table lists the comparison operations provided by nMigen:
449
450 ============ ==========================
451 Operation Description
452 ============ ==========================
453 ``a == b`` equality
454 ``a != b`` inequality
455 ``a < b`` less than
456 ``a <= b`` less than or equal
457 ``a > b`` greater than
458 ``a >= b`` greater than or equal
459 ============ ==========================
460
461
462 .. _lang-bitops:
463
464 Bitwise, shift, and rotate operators
465 ------------------------------------
466
467 All bitwise and shift operations on integers provided by Python can be used on nMigen values as well.
468
469 Similar to arithmetic operations, if any operand of a bitwise expression is signed, the expression itself is signed as well. A shift expression is signed if the shifted value is signed. A rotate expression is always unsigned.
470
471 Rotate operations with variable rotate amounts cannot be efficiently synthesized for non-power-of-2 widths of the rotated value. Because of that, the rotate operations are only provided for constant rotate amounts, specified as Python :py:class:`int`\ s.
472
473 The following table lists the bitwise and shift operations provided by nMigen:
474
475 ===================== ========================================== ======
476 Operation Description Notes
477 ===================== ========================================== ======
478 ``~a`` bitwise NOT; complement
479 ``a & b`` bitwise AND
480 ``a | b`` bitwise OR
481 ``a ^ b`` bitwise XOR
482 ``a.implies(b)`` bitwise IMPLY_
483 ``a >> b`` arithmetic right shift by variable amount [#opB1]_, [#opB2]_
484 ``a << b`` left shift by variable amount [#opB2]_
485 ``a.rotate_left(i)`` left rotate by constant amount [#opB3]_
486 ``a.rotate_right(i)`` right rotate by constant amount [#opB3]_
487 ``a.shift_left(i)`` left shift by constant amount [#opB3]_
488 ``a.shift_right(i)`` right shift by constant amount [#opB3]_
489 ===================== ========================================== ======
490
491 .. _IMPLY: https://en.wikipedia.org/wiki/IMPLY_gate
492 .. [#opB1] Logical and arithmetic right shift of an unsigned value are equivalent. Logical right shift of a signed value can be expressed by :ref:`converting it to unsigned <lang-convops>` first.
493 .. [#opB2] Shift amount must be unsigned; integer shifts in Python require the amount to be positive.
494 .. [#opB3] Shift and rotate amounts can be negative, in which case the direction is reversed.
495
496 .. _lang-hugeshift:
497
498 .. note::
499
500 Because nMigen ensures that the width of a variable left shift expression is wide enough to represent any possible result, variable left shift by a wide amount produces exponentially wider intermediate values, stressing the synthesis tools:
501
502 .. doctest::
503
504 >>> (1 << C(0, 32)).shape()
505 unsigned(4294967296)
506
507 Although nMigen will detect and reject expressions wide enough to break other tools, it is a good practice to explicitly limit the width of a shift amount in a variable left shift.
508
509
510 .. _lang-reduceops:
511
512 Reduction operators
513 -------------------
514
515 Bitwise reduction operations on integers are not provided by Python, but are very useful for hardware. They are similar to bitwise operations applied "sideways"; for example, if bitwise AND is a binary operator that applies AND to each pair of bits between its two operands, then reduction AND is an unary operator that applies AND to all of the bits in its sole operand.
516
517 The result of a reduction is a 1-bit unsigned value.
518
519 The following table lists the reduction operations provided by nMigen:
520
521 ============ ============================================= ======
522 Operation Description Notes
523 ============ ============================================= ======
524 ``a.all()`` reduction AND; are all bits set? [#opR1]_
525 ``a.any()`` reduction OR; is any bit set? [#opR1]_
526 ``a.xor()`` reduction XOR; is an odd number of bits set?
527 ``a.bool()`` conversion to boolean; is non-zero? [#opR2]_
528 ============ ============================================= ======
529
530 .. [#opR1] Conceptually the same as applying the Python :py:func:`all` or :py:func:`any` function to the value viewed as a collection of bits.
531 .. [#opR2] Conceptually the same as applying the Python :py:func:`bool` function to the value viewed as an integer.
532
533
534 .. _lang-logicops:
535
536 Logical operators
537 -----------------
538
539 Unlike the arithmetic or bitwise operators, it is not possible to change the behavior of the Python logical operators ``not``, ``and``, and ``or``. Due to that, logical expressions in nMigen are written using bitwise operations on boolean (1-bit unsigned) values, with explicit boolean conversions added where necessary.
540
541 The following table lists the Python logical expressions and their nMigen equivalents:
542
543 ================= ====================================
544 Python expression nMigen expression (any operands)
545 ================= ====================================
546 ``not a`` ``~(a).bool()``
547 ``a and b`` ``(a).bool() & (b).bool()``
548 ``a or b`` ``(a).bool() | (b).bool()``
549 ================= ====================================
550
551 When the operands are known to be boolean values, such as comparisons, reductions, or boolean signals, the ``.bool()`` conversion may be omitted for clarity:
552
553 ================= ====================================
554 Python expression nMigen expression (boolean operands)
555 ================= ====================================
556 ``not p`` ``~(p)``
557 ``p and q`` ``(p) & (q)``
558 ``p or q`` ``(p) | (q)``
559 ================= ====================================
560
561 .. _lang-logicprecedence:
562
563 .. warning::
564
565 Because of Python :ref:`operator precedence <python:operator-summary>`, logical operators bind less tightly than comparison operators whereas bitwise operators bind more tightly than comparison operators. As a result, all logical expressions in nMigen **must** have parenthesized operands.
566
567 Omitting parentheses around operands in an nMigen a logical expression is likely to introduce a subtle bug:
568
569 .. doctest::
570
571 >>> en = Signal()
572 >>> addr = Signal(8)
573 >>> en & (addr == 0) # correct
574 (& (sig en) (== (sig addr) (const 1'd0)))
575 >>> en & addr == 0 # WRONG! addr is truncated to 1 bit
576 (== (& (sig en) (sig addr)) (const 1'd0))
577
578 .. TODO: can we detect this footgun automatically? #380
579
580 .. _lang-negatebool:
581
582 .. warning::
583
584 When applied to nMigen boolean values, the ``~`` operator computes negation, and when applied to Python boolean values, the ``not`` operator also computes negation. However, the ``~`` operator applied to Python boolean values produces an unexpected result:
585
586 .. doctest::
587
588 >>> ~False
589 -1
590 >>> ~True
591 -2
592
593 Because of this, Python booleans used in nMigen logical expressions **must** be negated with the ``not`` operator, not the ``~`` operator. Negating a Python boolean with the ``~`` operator in an nMigen logical expression is likely to introduce a subtle bug:
594
595 .. doctest::
596
597 >>> stb = Signal()
598 >>> use_stb = True
599 >>> (not use_stb) | stb # correct
600 (| (const 1'd0) (sig stb))
601 >>> ~use_stb | stb # WRONG! MSB of 2-bit wide OR expression is always 1
602 (| (const 2'sd-2) (sig stb))
603
604 nMigen automatically detects some cases of misuse of ``~`` and emits a detailed diagnostic message.
605
606 .. TODO: this isn't quite reliable, #380
607
608
609 .. _lang-seqops:
610
611 Bit sequence operators
612 ----------------------
613
614 Apart from acting as numbers, nMigen values can also be treated as bit :ref:`sequences <python:typesseq>`, supporting slicing, concatenation, replication, and other sequence operations. Since some of the operators Python defines for sequences clash with the operators it defines for numbers, nMigen gives these operators a different name. Except for the names, nMigen values follow Python sequence semantics, with the least significant bit at index 0.
615
616 Because every nMigen value has a single fixed width, bit slicing and replication operations require the subscripts and count to be constant, specified as Python :py:class:`int`\ s. It is often useful to slice a value with a constant width and variable offset, but this cannot be expressed with the Python slice notation. To solve this problem, nMigen provides additional *part select* operations with the necessary semantics.
617
618 The result of any bit sequence operation is an unsigned value.
619
620 The following table lists the bit sequence operations provided by nMigen:
621
622 ======================= ================================================ ======
623 Operation Description Notes
624 ======================= ================================================ ======
625 ``len(a)`` bit length; value width [#opS1]_
626 ``a[i:j:k]`` bit slicing by constant subscripts [#opS2]_
627 ``iter(a)`` bit iteration
628 ``a.bit_select(b, i)`` overlapping part select with variable offset
629 ``a.word_select(b, i)`` non-overlapping part select with variable offset
630 ``Cat(a, b)`` concatenation [#opS3]_
631 ``Repl(a, i)`` replication
632 ======================= ================================================ ======
633
634 .. [#opS1] Words "length" and "width" have the same meaning when talking about nMigen values. Conventionally, "width" is used.
635 .. [#opS2] All variations of the Python slice notation are supported, including "extended slicing". E.g. all of ``a[0]``, ``a[1:9]``, ``a[2:]``, ``a[:-2]``, ``a[::-1]``, ``a[0:8:2]`` select bits in the same way as other Python sequence types select their elements.
636 .. [#opS3] In the concatenated value, ``a`` occupies the least significant bits, and ``b`` the most significant bits.
637
638 For the operators introduced by nMigen, the following table explains them in terms of Python code operating on tuples of bits rather than nMigen values:
639
640 ======================= ======================
641 nMigen operation Equivalent Python code
642 ======================= ======================
643 ``Cat(a, b)`` ``a + b``
644 ``Repl(a, i)`` ``a * i``
645 ``a.bit_select(b, i)`` ``a[b:b+i]``
646 ``a.word_select(b, i)`` ``a[b*i:b*i+i]``
647 ======================= ======================
648
649 .. warning::
650
651 In Python, the digits of a number are written right-to-left (0th exponent at the right), and the elements of a sequence are written left-to-right (0th element at the left). This mismatch can cause confusion when numeric operations (like shifts) are mixed with bit sequence operations (like concatenations). For example, ``Cat(C(0b1001), C(0b1010))`` has the same value as ``C(0b1010_1001)``, ``val[4:]`` is equivalent to ``val >> 4``, and ``val[-1]`` refers to the most significant bit.
652
653 Such confusion can often be avoided by not using numeric and bit sequence operations in the same expression. For example, although it may seem natural to describe a shift register with a numeric shift and a sequence slice operations, using sequence operations alone would make it easier to understand.
654
655 .. note::
656
657 Could nMigen have used a different indexing or iteration order for values? Yes, but it would be necessary to either place the most significant bit at index 0, or deliberately break the Python sequence type interface. Both of these options would cause more issues than using different iteration orders for numeric and sequence operations.
658
659
660 .. _lang-convops:
661
662 Conversion operators
663 --------------------
664
665 The ``.as_signed()`` and ``.as_unsigned()`` conversion operators reinterpret the bits of a value with the requested signedness. This is useful when the same value is sometimes treated as signed and sometimes as unsigned, or when a signed value is constructed using slices or concatenations. For example, ``(pc + imm[:7].as_signed()).as_unsigned()`` sign-extends the 7 least significant bits of ``imm`` to the width of ``pc``, performs the addition, and produces an unsigned result.
666
667 .. TODO: more general shape conversion? https://github.com/nmigen/nmigen/issues/381
668
669
670 .. _lang-muxop:
671
672 Choice operator
673 ---------------
674
675 The ``Mux(sel, val1, val0)`` choice expression (similar to the :ref:`conditional expression <python:if_expr>` in Python) is equal to the operand ``val1`` if ``sel`` is non-zero, and to the other operand ``val0`` otherwise. If any of ``val1`` or ``val0`` are signed, the expression itself is signed as well.
676
677
678 .. _lang-modules:
679
680 Modules
681 =======
682
683 A *module* is a unit of the nMigen design hierarchy: the smallest collection of logic that can be independently simulated, synthesized, or otherwise processed. Modules associate signals with :ref:`control domains <lang-domains>`, provide :ref:`control structures <lang-control>`, manage clock domains, and aggregate submodules.
684
685 .. TODO: link to clock domains
686 .. TODO: link to submodules
687
688 Every nMigen design starts with a fresh module:
689
690 .. doctest::
691
692 >>> m = Module()
693
694
695 .. _lang-domains:
696
697 Control domains
698 ---------------
699
700 A *control domain* is a named group of :ref:`signals <lang-signals>` that change their value in identical conditions.
701
702 All designs have a single predefined *combinatorial domain*, containing all signals that change immediately when any value used to compute them changes. The name ``comb`` is reserved for the combinatorial domain.
703
704 A design can also have any amount of user-defined *synchronous domains*, also called *clock domains*, containing signals that change when a specific edge occurs on the domain's clock signal or, for domains with asynchronous reset, on the domain's reset signal. Most modules only use a single synchronous domain, conventionally called ``sync``, but the name ``sync`` does not have to be used, and lacks any special meaning beyond being the default.
705
706 The behavior of assignments differs for signals in :ref:`combinatorial <lang-comb>` and :ref:`synchronous <lang-sync>` domains. Collectively, signals in synchronous domains contain the state of a design, whereas signals in the combinatorial domain cannot form feedback loops or hold state.
707
708 .. TODO: link to clock domains
709
710
711 .. _lang-assigns:
712
713 Assigning to signals
714 --------------------
715
716 *Assignments* are used to change the values of signals. An assignment statement can be introduced with the ``.eq(...)`` syntax:
717
718 .. doctest::
719
720 >>> s = Signal()
721 >>> s.eq(1)
722 (eq (sig s) (const 1'd1))
723
724 Similar to :ref:`how nMigen operators work <lang-abstractexpr>`, an nMigen assignment is an ordinary Python object used to describe a part of a circuit. An assignment does not have any effect on the signal it changes until it is added to a control domain in a module. Once added, it introduces logic into the circuit generated from that module.
725
726
727 .. _lang-assignlhs:
728
729 Assignment targets
730 ------------------
731
732 The target of an assignment can be more complex than a single signal. It is possible to assign to any combination of signals, :ref:`bit slices <lang-seqops>`, :ref:`concatenations <lang-seqops>`, and :ref:`part selects <lang-seqops>` as long as it includes no other values:
733
734 .. TODO: mention arrays, records, user values
735
736 .. doctest::
737
738 >>> a = Signal(8)
739 >>> b = Signal(4)
740 >>> Cat(a, b).eq(0)
741 (eq (cat (sig a) (sig b)) (const 1'd0))
742 >>> a[:4].eq(b)
743 (eq (slice (sig a) 0:4) (sig b))
744 >>> Cat(a, a).bit_select(b, 2).eq(0b11)
745 (eq (part (cat (sig a) (sig a)) (sig b) 2 1) (const 2'd3))
746
747
748 .. _lang-assigndomains:
749
750 Assignment domains
751 ------------------
752
753 The ``m.d.<domain> += ...`` syntax is used to add assignments to a specific control domain in a module. It can add just a single assignment, or an entire sequence of them:
754
755 .. testcode::
756
757 a = Signal()
758 b = Signal()
759 c = Signal()
760 m.d.comb += a.eq(1)
761 m.d.sync += [
762 b.eq(c),
763 c.eq(b),
764 ]
765
766 If the name of a domain is not known upfront, the ``m.d["<domain>"] += ...`` syntax can be used instead:
767
768 .. testcode::
769
770 def add_toggle(num):
771 t = Signal()
772 m.d[f"sync_{num}"] += t.eq(~t)
773 add_toggle(2)
774
775 .. _lang-signalgranularity:
776
777 Every signal included in the target of an assignment becomes a part of the domain, or equivalently, *driven* by that domain. A signal can be either undriven or driven by exactly one domain; it is an error to add two assignments to the same signal to two different domains:
778
779 .. doctest::
780
781 >>> d = Signal()
782 >>> m.d.comb += d.eq(1)
783 >>> m.d.sync += d.eq(0)
784 Traceback (most recent call last):
785 ...
786 nmigen.hdl.dsl.SyntaxError: Driver-driver conflict: trying to drive (sig d) from d.sync, but it is already driven from d.comb
787
788 .. note::
789
790 Clearly, nMigen code that drives a single bit of a signal from two different domains does not describe a meaningful circuit. However, driving two different bits of a signal from two different domains does not inherently cause such a conflict. Would nMigen accept the following code?
791
792 .. testcode::
793
794 e = Signal(2)
795 m.d.comb += e[0].eq(0)
796 m.d.sync += e[1].eq(1)
797
798 The answer is no. While this kind of code is occasionally useful, rejecting it greatly simplifies backends, simulators, and analyzers.
799
800
801 .. _lang-assignorder:
802
803 Assignment order
804 ----------------
805
806 Unlike with two different domains, adding multiple assignments to the same signal to the same domain is well-defined.
807
808 Assignments to different signal bits apply independently. For example, the following two snippets are equivalent:
809
810 .. testcode::
811
812 a = Signal(8)
813 m.d.comb += [
814 a[0:4].eq(C(1, 4)),
815 a[4:8].eq(C(2, 4)),
816 ]
817
818 .. testcode::
819
820 a = Signal(8)
821 m.d.comb += a.eq(Cat(C(1, 4), C(2, 4)))
822
823 If multiple assignments change the value of the same signal bits, the assignment that is added last determines the final value. For example, the following two snippets are equivalent:
824
825 .. testcode::
826
827 b = Signal(9)
828 m.d.comb += [
829 b[0:9].eq(Cat(C(1, 3), C(2, 3), C(3, 3))),
830 b[0:6].eq(Cat(C(4, 3), C(5, 3))),
831 b[3:6].eq(C(6, 3)),
832 ]
833
834 .. testcode::
835
836 b = Signal(9)
837 m.d.comb += b.eq(Cat(C(4, 3), C(6, 3), C(3, 3)))
838
839 Multiple assignments to the same signal bits are more useful when combined with control structures, which can make some of the assignments :ref:`active or inactive <lang-active>`. If all assignments to some signal bits are :ref:`inactive <lang-active>`, their final values are determined by the signal's domain, :ref:`combinatorial <lang-comb>` or :ref:`synchronous <lang-sync>`.
840
841
842 .. _lang-control:
843
844 Control structures
845 ------------------
846
847 Although it is possible to write any decision tree as a combination of :ref:`assignments <lang-assigns>` and :ref:`choice expressions <lang-muxop>`, nMigen provides *control structures* tailored for this task: If, Switch, and FSM. The syntax of all control structures is based on :ref:`context managers <python:context-managers>` and uses ``with`` blocks, for example:
848
849 .. TODO: link to relevant subsections
850
851 .. testcode::
852
853 timer = Signal(8)
854 with m.If(timer == 0):
855 m.d.sync += timer.eq(10)
856 with m.Else():
857 m.d.sync += timer.eq(timer - 1)
858
859 While some nMigen control structures are superficially similar to imperative control flow statements (such as Python's ``if``), their function---together with :ref:`expressions <lang-abstractexpr>` and :ref:`assignments <lang-assigns>`---is to describe circuits. The code above is equivalent to:
860
861 .. testcode::
862
863 timer = Signal(8)
864 m.d.sync += timer.eq(Mux(timer == 0, 10, timer - 1))
865
866 Because all branches of a decision tree affect the generated circuit, all of the Python code inside nMigen control structures is always evaluated in the order in which it appears in the program. This can be observed through Python code with side effects, such as ``print()``:
867
868 .. testcode::
869
870 timer = Signal(8)
871 with m.If(timer == 0):
872 print("inside `If`")
873 m.d.sync += timer.eq(10)
874 with m.Else():
875 print("inside `Else`")
876 m.d.sync += timer.eq(timer - 1)
877
878 .. testoutput::
879
880 inside `If`
881 inside `Else`
882
883
884 .. _lang-active:
885
886 Active and inactive assignments
887 -------------------------------
888
889 An assignment added inside an nMigen control structure, i.e. ``with m.<...>:`` block, is *active* if the condition of the control structure is satisfied, and *inactive* otherwise. For any given set of conditions, the final value of every signal assigned in a module is the same as if the inactive assignments were removed and the active assignments were performed unconditionally, taking into account the :ref:`assignment order <lang-assignorder>`.
890
891 For example, there are two possible cases in the circuit generated from the following code:
892
893 .. testcode::
894
895 timer = Signal(8)
896 m.d.sync += timer.eq(timer - 1)
897 with m.If(timer == 0):
898 m.d.sync += timer.eq(10)
899
900 When ``timer == 0`` is true, the code reduces to:
901
902 .. code-block::
903
904 m.d.sync += timer.eq(timer - 1)
905 m.d.sync += timer.eq(10)
906
907 Due to the :ref:`assignment order <lang-assignorder>`, it further reduces to:
908
909 .. code-block::
910
911 m.d.sync += timer.eq(10)
912
913 When ``timer == 0`` is false, the code reduces to:
914
915 .. code-block::
916
917 m.d.sync += timer.eq(timer - 1)
918
919 Combining these cases together, the code above is equivalent to:
920
921 .. testcode::
922
923 timer = Signal(8)
924 m.d.sync += timer.eq(Mux(timer == 0, 10, timer - 1))
925
926
927 .. _lang-comb:
928
929 Combinatorial evaluation
930 ------------------------
931
932 Signals in the combinatorial :ref:`control domain <lang-domains>` change whenever any value used to compute them changes. The final value of a combinatorial signal is equal to its :ref:`initial value <lang-initial>` updated by the :ref:`active assignments <lang-active>` in the :ref:`assignment order <lang-assignorder>`. Combinatorial signals cannot hold any state.
933
934 Consider the following code:
935
936 .. testsetup::
937 en = Signal()
938 b = Signal(8)
939
940 .. testcode::
941
942 a = Signal(8, reset=1)
943 with m.If(en):
944 m.d.comb += a.eq(b + 1)
945
946 Whenever the signals ``en`` or ``b`` change, the signal ``a`` changes as well. If ``en`` is false, the final value of ``a`` is its initial value, ``1``. If ``en`` is true, the final value of ``a`` is equal to ``b + 1``.
947
948 A combinatorial signal that is computed directly or indirectly based on its own value is a part of a *combinatorial feedback loop*, sometimes shortened to just *feedback loop*. Combinatorial feedback loops can be stable (i.e. implement a constant driver or a transparent latch), or unstable (i.e. implement a ring oscillator). nMigen prohibits using assignments to describe any kind of a combinatorial feedback loop, including transparent latches.
949
950 .. warning::
951
952 The current version of nMigen does not detect combinatorial feedback loops, but processes the design under the assumption that there aren't any. If the design does in fact contain a combinatorial feedback loop, it will likely be **silently miscompiled**, though some cases will be detected during synthesis or place & route.
953
954 This hazard will be eliminated in the future.
955
956 .. TODO: fix this, either as a part of https://github.com/nmigen/nmigen/issues/6 or on its own
957
958 .. note::
959
960 In the exceedingly rare case when a combinatorial feedback loop is desirable, it is possible to implement it by directly instantiating technology primitives (e.g. device-specific LUTs or latches). This is also the only way to introduce a combinatorial feedback loop with well-defined behavior in simulation and synthesis, regardless of the HDL being used.
961
962
963 .. _lang-sync:
964
965 Synchronous evaluation
966 ----------------------
967
968 Signals in synchronous :ref:`control domains <lang-domains>` change whenever a specific transition (positive or negative edge) occurs on the clock of the synchronous domain. In addition, the signals in clock domains with an asynchronous reset change when such a reset is asserted. The final value of a synchronous signal is equal to its :ref:`initial value <lang-initial>` if the reset (of any type) is asserted, or to its current value updated by the :ref:`active assignments <lang-active>` in the :ref:`assignment order <lang-assignorder>` otherwise. Synchronous signals always hold state.
969
970 .. TODO: link to clock domains