1MIGEN(1) Migen MIGEN(1)
2
3
4
6 migen - Migen manual
7
9 Migen is a Python-based tool that aims at automating further the VLSI
10 design process.
11
12 Migen makes it possible to apply modern software concepts such as
13 object-oriented programming and metaprogramming to design hardware.
14 This results in more elegant and easily maintained designs and reduces
15 the incidence of human errors.
16
17 Background
18 Even though the Milkymist system-on-chip [mm] had many successes, it
19 suffers from several limitations stemming from its implementation in
20 manually written Verilog HDL:
21
22 [mm] http://m-labs.hk
23
24 1. The "event-driven" paradigm of today's dominant hardware descrip‐
25 tions languages (Verilog and VHDL, collectively referred to as
26 "V*HDL" in the rest of this document) is often too general. Today's
27 FPGA architectures are optimized for the implementation of fully
28 synchronous circuits. This means that the bulk of the code for an
29 efficient FPGA design falls into three categories:
30
31 1. Combinatorial statements
32
33 2. Synchronous statements
34
35 3. Initialization of registers at reset
36
37 V*HDL do not follow this organization. This means that a lot of
38 repetitive manual coding is needed, which brings sources of human
39 errors, petty issues, and confusion for beginners:
40
41 1. wire vs. reg in Verilog
42
43 2. forgetting to initialize a register at reset
44
45 3. deciding whether a combinatorial statement must go into a
46 process/always block or not
47
48 4. simulation mismatches with combinatorial processes/always blocks
49
50 5. and more...
51
52 A little-known fact about FPGAs is that many of them have the abil‐
53 ity to initialize their registers from the bitstream contents. This
54 can be done in a portable and standard way using an "initial" block
55 in Verilog, and by affecting a value at the signal declaration in
56 VHDL. This renders an explicit reset signal unnecessary in practice
57 in some cases, which opens the way for further design optimization.
58 However, this form of initialization is entirely not synthesizable
59 for ASIC targets, and it is not easy to switch between the two forms
60 of reset using V*HDL.
61
62 2. V*HDL support for composite types is very limited. Signals having a
63 record type in VHDL are unidirectional, which makes them clumsy to
64 use e.g. in bus interfaces. There is no record type support in Ver‐
65 ilog, which means that a lot of copy-and-paste has to be done when
66 forwarding grouped signals.
67
68 3. V*HDL support for procedurally generated logic is extremely limited.
69 The most advanced forms of procedural generation of synthesizable
70 logic that V*HDL offers are CPP-style directives in Verilog, combi‐
71 natorial functions, and generate statements. Nothing really fancy,
72 and it shows. To give a few examples:
73
74 1. Building highly flexible bus interconnect is not possible. Even
75 arbitrating any given number of bus masters for commonplace pro‐
76 tocols such as Wishbone is difficult with the tools that V*HDL
77 puts at our disposal.
78
79 2. Building a memory infrastructure (including bus interconnect,
80 bridges and caches) that can automatically adapt itself at com‐
81 pile-time to any word size of the SDRAM is clumsy and tedious.
82
83 3. Building register banks for control, status and interrupt manage‐
84 ment of cores can also largely benefit from automation.
85
86 4. Many hardware acceleration problems can fit into the dataflow
87 programming model. Manual dataflow implementation in V*HDL has,
88 again, a lot of redundancy and potential for human errors. See
89 the Milkymist texture mapping unit [mthesis] [mxcell] for an
90 example of this. The amount of detail to deal with manually also
91 makes the design space exploration difficult, and therefore hin‐
92 ders the design of efficient architectures.
93
94 5. Pre-computation of values, such as filter coefficients for DSP or
95 even simply trigonometric tables, must often be done using exter‐
96 nal tools whose results are copy-and-pasted (in the best case,
97 automatically) into the V*HDL source.
98
99 [mthesis]
100 http://m-labs.hk/thesis/thesis.pdf
101
102 [mxcell]
103 http://www.xilinx.com/publications/archives/xcell/Xcell77.pdf
104 p30-35
105
106 Enter Migen, a Python toolbox for building complex digital hard‐
107 ware. We could have designed a brand new programming language, but
108 that would have been reinventing the wheel instead of being able
109 to benefit from Python's rich features and immense library. The
110 price to pay is a slightly cluttered syntax at times when writing
111 descriptions in FHDL, but we believe this is totally acceptable,
112 particularly when compared to VHDL ;-)
113
114 Migen is made up of several related components:
115
116 1. the base language, FHDL
117
118 2. a library of small generic cores
119
120 3. a simulator
121
122 4. a build system
123
124 Installing Migen
125 Either run the setup.py installation script or simply set PYTHONPATH to
126 the root of the source directory.
127
128 If you wish to contribute patches, the suggest way to install is;
129
130 1. Clone from the git repository at
131 http://github.com/m-labs/migen
132
133 2. Install using python3 ./setup.py develop --user
134
135 3. Edit the code in your git checkout.
136
137 Alternative install methods
138 · Migen is available for the Anaconda Python distribution. The pack‐
139 age can be found at at https://anaconda.org/m-labs/migen
140
141 · Migen can be referenced in a requirements.txt file (used for pip
142 install -r requirements.txt) via -e
143 git+http://github.com/m-labs/migen.git#egg=migen. See the pip doc‐
144 umentation for more information.
145
146 Feedback
147 Feedback concerning Migen or this manual should be sent to the M-Labs
148 developers' mailing list devel on lists.m-labs.hk.
149
151 The Fragmented Hardware Description Language (FHDL) is the basis of
152 Migen. It consists of a formal system to describe signals, and combina‐
153 torial and synchronous statements operating on them. The formal system
154 itself is low level and close to the synthesizable subset of Verilog,
155 and we then rely on Python algorithms to build complex structures by
156 combining FHDL elements. The FHDL module also contains a back-end to
157 produce synthesizable Verilog, and some structure analysis and manipu‐
158 lation functionality.
159
160 FHDL differs from MyHDL [myhdl] in fundamental ways. MyHDL follows the
161 event-driven paradigm of traditional HDLs (see background) while FHDL
162 separates the code into combinatorial statements, synchronous state‐
163 ments, and reset values. In MyHDL, the logic is described directly in
164 the Python AST. The converter to Verilog or VHDL then examines the
165 Python AST and recognizes a subset of Python that it translates into
166 V*HDL statements. This seriously impedes the capability of MyHDL to
167 generate logic procedurally. With FHDL, you manipulate a custom AST
168 from Python, and you can more easily design algorithms that operate on
169 it.
170
171 [myhdl]
172 http://www.myhdl.org
173
174 FHDL is made of several elements, which are briefly explained
175 below. They all can be imported directly from the migen module.
176
177 Expressions
178 Constants
179 The Constant object represents a constant, HDL-literal integer. It
180 behaves like specifying integers and booleans but also supports slicing
181 and can have a bit width or signedness different from what is implied
182 by the value it represents.
183
184 True and False are interpreted as 1 and 0, respectively.
185
186 Negative integers are explicitly supported. As with MyHDL [countin],
187 arithmetic operations return the natural results.
188
189 To lighten the syntax, assignments and operators automatically wrap
190 Python integers and booleans into Constant. Additionally, Constant is
191 aliased to C. The following are valid Migen statements: a.eq(0), a.eq(a
192 + 1), a.eq(C(42)[0:1]).
193
194 [countin]
195 http://www.jandecaluwe.com/hdldesign/counting.html
196
197 Signal
198 The signal object represents a value that is expected to change in the
199 circuit. It does exactly what Verilog's "wire" and "reg" and VHDL's
200 "signal" do.
201
202 The main point of the signal object is that it is identified by its
203 Python ID (as returned by the id() function), and nothing else. It is
204 the responsibility of the V*HDL back-end to establish an injective map‐
205 ping between Python IDs and the V*HDL namespace. It should perform name
206 mangling to ensure this. The consequence of this is that signal objects
207 can safely become members of arbitrary Python classes, or be passed as
208 parameters to functions or methods that generate logic involving them.
209
210 The properties of a signal object are:
211
212 · An integer or a (integer, boolean) pair that defines the number of
213 bits and whether the bit of higher index of the signal is a sign bit
214 (i.e. the signal is signed). The defaults are one bit and unsigned.
215 Alternatively, the min and max parameters can be specified to define
216 the range of the signal and determine its bit width and signedness.
217 As with Python ranges, min is inclusive and defaults to 0, max is
218 exclusive and defaults to 2.
219
220 · A name, used as a hint for the V*HDL back-end name mangler.
221
222 · The signal's reset value. It must be an integer, and defaults to 0.
223 When the signal's value is modified with a synchronous statement, the
224 reset value is the initialization value of the associated register.
225 When the signal is assigned to in a conditional combinatorial state‐
226 ment (If or Case), the reset value is the value that the signal has
227 when no condition that causes the signal to be driven is verified.
228 This enforces the absence of latches in designs. If the signal is
229 permanently driven using a combinatorial statement, the reset value
230 has no effect.
231
232 The sole purpose of the name property is to make the generated V*HDL
233 code easier to understand and debug. From a purely functional point of
234 view, it is perfectly OK to have several signals with the same name
235 property. The back-end will generate a unique name for each object. If
236 no name property is specified, Migen will analyze the code that created
237 the signal object, and try to extract the variable or member name from
238 there. For example, the following statements will create one or several
239 signals named "bar":
240
241 bar = Signal()
242 self.bar = Signal()
243 self.baz.bar = Signal()
244 bar = [Signal() for x in range(42)]
245
246 In case of conflicts, Migen tries first to resolve the situation by
247 prefixing the identifiers with names from the class and module hierar‐
248 chy that created them. If the conflict persists (which can be the case
249 if two signal objects are created with the same name in the same con‐
250 text), it will ultimately add number suffixes.
251
252 Operators
253 Operators are represented by the _Operator object, which generally
254 should not be used directly. Instead, most FHDL objects overload the
255 usual Python logic and arithmetic operators, which allows a much
256 lighter syntax to be used. For example, the expression:
257
258 a * b + c
259
260 is equivalent to:
261
262 _Operator("+", [_Operator("*", [a, b]), c])
263
264 Slices
265 Likewise, slices are represented by the _Slice object, which often
266 should not be used in favor of the Python slice operation [x:y].
267 Implicit indices using the forms [x], [x:] and [:y] are supported.
268 Beware! Slices work like Python slices, not like VHDL or Verilog
269 slices. The first bound is the index of the LSB and is inclusive. The
270 second bound is the index of MSB and is exclusive. In V*HDL, bounds are
271 MSB:LSB and both are inclusive.
272
273 Concatenations
274 Concatenations are done using the Cat object. To make the syntax
275 lighter, its constructor takes a variable number of arguments, which
276 are the signals to be concatenated together (you can use the Python "*"
277 operator to pass a list instead). To be consistent with slices, the
278 first signal is connected to the bits with the lowest indices in the
279 result. This is the opposite of the way the "{}" construct works in
280 Verilog.
281
282 Replications
283 The Replicate object represents the equivalent of {count{expression}}
284 in Verilog. For example, the expression:
285
286 Replicate(0, 4)
287
288 is equivalent to:
289
290 Cat(0, 0, 0, 0)
291
292 Statements
293 Assignment
294 Assignments are represented with the _Assign object. Since using it
295 directly would result in a cluttered syntax, the preferred technique
296 for assignments is to use the eq() method provided by objects that can
297 have a value assigned to them. They are signals, and their combinations
298 with the slice and concatenation operators. As an example, the state‐
299 ment:
300
301 a[0].eq(b)
302
303 is equivalent to:
304
305 _Assign(_Slice(a, 0, 1), b)
306
307 If
308 The If object takes a first parameter which must be an expression (com‐
309 bination of the Constant, Signal, _Operator, _Slice, etc. objects) rep‐
310 resenting the condition, then a variable number of parameters repre‐
311 senting the statements (_Assign, If, Case, etc. objects) to be executed
312 when the condition is verified.
313
314 The If object defines a Else() method, which when called defines the
315 statements to be executed when the condition is not true. Those state‐
316 ments are passed as parameters to the variadic method.
317
318 For convenience, there is also a Elif() method.
319
320 Example:
321
322 If(tx_count16 == 0,
323 tx_bitcount.eq(tx_bitcount + 1),
324 If(tx_bitcount == 8,
325 self.tx.eq(1)
326 ).Elif(tx_bitcount == 9,
327 self.tx.eq(1),
328 tx_busy.eq(0)
329 ).Else(
330 self.tx.eq(tx_reg[0]),
331 tx_reg.eq(Cat(tx_reg[1:], 0))
332 )
333 )
334
335 Case
336 The Case object constructor takes as first parameter the expression to
337 be tested, and a dictionary whose keys are the values to be matched,
338 and values the statements to be executed in the case of a match. The
339 special value "default" can be used as match value, which means the
340 statements should be executed whenever there is no other match.
341
342 Arrays
343 The Array object represents lists of other objects that can be indexed
344 by FHDL expressions. It is explicitly possible to:
345
346 · nest Array objects to create multidimensional tables.
347
348 · list any Python object in a Array as long as every expression appear‐
349 ing in a module ultimately evaluates to a Signal for all possible
350 values of the indices. This allows the creation of lists of struc‐
351 tured data.
352
353 · use expressions involving Array objects in both directions (assign‐
354 ment and reading).
355
356 For example, this creates a 4x4 matrix of 1-bit signals:
357
358 my_2d_array = Array(Array(Signal() for a in range(4)) for b in range(4))
359
360 You can then read the matrix with (x and y being 2-bit signals):
361
362 out.eq(my_2d_array[x][y])
363
364 and write it with:
365
366 my_2d_array[x][y].eq(inp)
367
368 Since they have no direct equivalent in Verilog, Array objects are low‐
369 ered into multiplexers and conditional statements before the actual
370 conversion takes place. Such lowering happens automatically without any
371 user intervention.
372
373 Any out-of-bounds access performed on an Array object will refer to the
374 last element.
375
376 Specials
377 Tri-state I/O
378 A triplet (O, OE, I) of one-way signals defining a tri-state I/O port
379 is represented by the TSTriple object. Such objects are only containers
380 for signals that are intended to be later connected to a tri-state I/O
381 buffer, and cannot be used as module specials. Such objects, however,
382 should be kept in the design as long as possible as they allow the
383 individual one-way signals to be manipulated in a non-ambiguous way.
384
385 The object that can be used in as a module special is Tristate, and it
386 behaves exactly like an instance of a tri-state I/O buffer that would
387 be defined as follows:
388
389 Instance("Tristate",
390 io_target=target,
391 i_o=o,
392 i_oe=oe,
393 o_i=i
394 )
395
396 Signals target, o and i can have any width, while oe is 1-bit wide. The
397 target signal should go to a port and not be used elsewhere in the
398 design. Like modern FPGA architectures, Migen does not support internal
399 tri-states.
400
401 A Tristate object can be created from a TSTriple object by calling the
402 get_tristate method.
403
404 By default, Migen emits technology-independent behavioral code for a
405 tri-state buffer. If a specific code is needed, the tristate handler
406 can be overriden using the appropriate parameter of the V*HDL conver‐
407 sion function.
408
409 Instances
410 Instance objects represent the parametrized instantiation of a V*HDL
411 module, and the connection of its ports to FHDL signals. They are use‐
412 ful in a number of cases:
413
414 · Reusing legacy or third-party V*HDL code.
415
416 · Using special FPGA features (DCM, ICAP, ...).
417
418 · Implementing logic that cannot be expressed with FHDL (e.g. latches).
419
420 · Breaking down a Migen system into multiple sub-systems.
421
422 The instance object constructor takes the type (i.e. name of the
423 instantiated module) of the instance, then multiple parameters describ‐
424 ing how to connect and parametrize the instance.
425
426 These parameters can be:
427
428 · Instance.Input, Instance.Output or Instance.InOut to describe signal
429 connections with the instance. The parameters are the name of the
430 port at the instance, and the FHDL expression it should be connected
431 to.
432
433 · Instance.Parameter sets a parameter (with a name and value) of the
434 instance.
435
436 · Instance.ClockPort and Instance.ResetPort are used to connect clock
437 and reset signals to the instance. The only mandatory parameter is
438 the name of the port at the instance. Optionally, a clock domain name
439 can be specified, and the invert option can be used to interface to
440 those modules that require a 180-degree clock or a active-low reset.
441
442 Memories
443 Memories (on-chip SRAM) are supported using a mechanism similar to
444 instances.
445
446 A memory object has the following parameters:
447
448 · The width, which is the number of bits in each word.
449
450 · The depth, which represents the number of words in the memory.
451
452 · An optional list of integers used to initialize the memory.
453
454 To access the memory in hardware, ports can be obtained by calling the
455 get_port method. A port always has an address signal a and a data read
456 signal dat_r. Other signals may be available depending on the port's
457 configuration.
458
459 Options to get_port are:
460
461 · write_capable (default: False): if the port can be used to write to
462 the memory. This creates an additional we signal.
463
464 · async_read (default: False): whether reads are asychronous (combina‐
465 torial) or synchronous (registered).
466
467 · has_re (default: False): adds a read clock-enable signal re (ignored
468 for asychronous ports).
469
470 · we_granularity (default: 0): if non-zero, writes of less than a mem‐
471 ory word can occur. The width of the we signal is increased to act as
472 a selection signal for the sub-words.
473
474 · mode (default: WRITE_FIRST, ignored for aynchronous ports). It can
475 be:
476
477 · READ_FIRST: during a write, the previous value is read.
478
479 · WRITE_FIRST: the written value is returned.
480
481 · NO_CHANGE: the data read signal keeps its previous value on a
482 write.
483
484 · clock_domain (default: "sys"): the clock domain used for reading and
485 writing from this port.
486
487 Migen generates behavioural V*HDL code that should be compatible with
488 all simulators and, if the number of ports is <= 2, most FPGA synthe‐
489 sizers. If a specific code is needed, the memory handler can be overri‐
490 den using the appropriate parameter of the V*HDL conversion function.
491
492 Modules
493 Modules play the same role as Verilog modules and VHDL entities. Simi‐
494 larly, they are organized in a tree structure. A FHDL module is a
495 Python object that derives from the Module class. This class defines
496 special attributes to be used by derived classes to describe their
497 logic. They are explained below.
498
499 Combinatorial statements
500 A combinatorial statement is a statement that is executed whenever one
501 of its inputs changes.
502
503 Combinatorial statements are added to a module by using the comb spe‐
504 cial attribute. Like most module special attributes, it must be
505 accessed using the += incrementation operator, and either a single
506 statement, a tuple of statements or a list of statements can appear on
507 the right hand side.
508
509 For example, the module below implements a OR gate:
510
511 class ORGate(Module):
512 def __init__(self):
513 self.a = Signal()
514 self.b = Signal()
515 self.x = Signal()
516
517 ###
518
519 self.comb += self.x.eq(self.a | self.b)
520
521 To improve code readability, it is recommended to place the interface
522 of the module at the beginning of the __init__ function, and separate
523 it from the implementation using three hash signs.
524
525 Synchronous statements
526 A synchronous statements is a statement that is executed at each edge
527 of some clock signal.
528
529 They are added to a module by using the sync special attribute, which
530 has the same properties as the comb attribute.
531
532 The sync special attribute also has sub-attributes that correspond to
533 abstract clock domains. For example, to add a statement to the clock
534 domain named foo, one would write self.sync.foo += statement. The
535 default clock domain is sys and writing self.sync += statement is
536 equivalent to writing self.sync.sys += statement.
537
538 Submodules and specials
539 Submodules and specials can be added by using the submodules and spe‐
540 cials attributes respectively. This can be done in two ways:
541
542 1. anonymously, by using the += operator on the special attribute
543 directly, e.g. self.submodules += some_other_module. Like with the
544 comb and sync attributes, a single module/special or a tuple or list
545 can be specified.
546
547 2. by naming the submodule/special using a subattribute of the submod‐
548 ules or specials attribute, e.g. self.submodules.foo = module_foo.
549 The submodule/special is then accessible as an attribute of the
550 object, e.g. self.foo (and not self.submodules.foo). Only one sub‐
551 module/special can be added at a time using this form.
552
553 Clock domains
554 Specifying the implementation of a clock domain is done using the
555 ClockDomain object. It contains the name of the clock domain, a clock
556 signal that can be driven like any other signal in the design (for
557 example, using a PLL instance), and optionally a reset signal. Clock
558 domains without a reset signal are reset using e.g. initial statements
559 in Verilog, which in many FPGA families initalize the registers during
560 configuration.
561
562 The name can be omitted if it can be extracted from the variable name.
563 When using this automatic naming feature, prefixes _, cd_ and _cd_ are
564 removed.
565
566 Clock domains are then added to a module using the clock_domains spe‐
567 cial attribute, which behaves exactly like submodules and specials.
568
569 Summary of special attributes
570 ┌───────────────────────────┬────────────────────────────┐
571 │Syntax │ Action │
572 ├───────────────────────────┼────────────────────────────┤
573 │self.comb += stmt │ Add combinatorial state‐ │
574 │ │ ment to current module. │
575 ├───────────────────────────┼────────────────────────────┤
576 │self.comb += stmtA, stmtB │ Add combinatorial state‐ │
577 │ │ ments A and B to current │
578 │self.comb += [stmtA, │ module. │
579 │stmtB] │ │
580 ├───────────────────────────┼────────────────────────────┤
581 │self.sync += stmt │ Add synchronous statement │
582 │ │ to current module, in │
583 │ │ default clock domain sys. │
584 ├───────────────────────────┼────────────────────────────┤
585 │self.sync.foo += stmt │ Add synchronous statement │
586 │ │ to current module, in │
587 │ │ clock domain foo. │
588 ├───────────────────────────┼────────────────────────────┤
589 │self.sync.foo += stmtA, │ Add synchronous statements │
590 │stmtB │ A and B to current module, │
591 │ │ in clock domain foo. │
592 │self.sync.foo += [stmtA, │ │
593 │stmtB] │ │
594 ├───────────────────────────┼────────────────────────────┤
595 │self.submodules += mod │ Add anonymous submodule to │
596 │ │ current module. │
597 ├───────────────────────────┼────────────────────────────┤
598 │self.submodules += modA, │ Add anonymous submodules A │
599 │modB │ and B to current module. │
600 │ │ │
601 │self.submodules += [modA, │ │
602 │modB] │ │
603 └───────────────────────────┴────────────────────────────┘
604
605 │self.submodules.bar = mod │ Add submodule named bar to │
606 │ │ current module. The sub‐ │
607 │ │ module can then be │
608 │ │ accessed using self.bar. │
609 ├───────────────────────────┼────────────────────────────┤
610 │self.specials += spe │ Add anonymous special to │
611 │ │ current module. │
612 ├───────────────────────────┼────────────────────────────┤
613 │self.specials += speA, │ Add anonymous specials A │
614 │speB │ and B to current module. │
615 │ │ │
616 │self.specials += [speA, │ │
617 │speB] │ │
618 ├───────────────────────────┼────────────────────────────┤
619 │self.specials.bar = spe │ Add special named bar to │
620 │ │ current module. The spe‐ │
621 │ │ cial can then be accessed │
622 │ │ using self.bar. │
623 ├───────────────────────────┼────────────────────────────┤
624 │self.clock_domains += cd │ Add clock domain to cur‐ │
625 │ │ rent module. │
626 ├───────────────────────────┼────────────────────────────┤
627 │self.clock_domains += cdA, │ Add clock domains A and B │
628 │cdB │ to current module. │
629 │ │ │
630 │self.clock_domains += │ │
631 │[cdA, cdB] │ │
632 ├───────────────────────────┼────────────────────────────┤
633 │self.clock_domains.pix = │ Create and add clock │
634 │ClockDomain() │ domain pix to current mod‐ │
635 │ │ ule. The clock domain name │
636 │self.clock_domains._pix = │ is pix in all cases. It │
637 │ClockDomain() │ can be accessed using │
638 │ │ self.pix, self._pix, │
639 │self.clock_domains.cd_pix │ self.cd_pix and │
640 │= ClockDomain() │ self._cd_pix, respec‐ │
641 │ │ tively. │
642 │self.clock_domains._cd_pix │ │
643 │= ClockDomain() │ │
644 └───────────────────────────┴────────────────────────────┘
645
646 Clock domain management
647 When a module has named submodules that define one or several clock
648 domains with the same name, those clock domain names are prefixed with
649 the name of each submodule plus an underscore.
650
651 An example use case of this feature is a system with two independent
652 video outputs. Each video output module is made of a clock generator
653 module that defines a clock domain pix and drives the clock signal,
654 plus a driver module that has synchronous statements and other elements
655 in clock domain pix. The designer of the video output module can simply
656 use the clock domain name pix in that module. In the top-level system
657 module, the video output submodules are named video0 and video1. Migen
658 then automatically renames the pix clock domain of each module to
659 video0_pix and video1_pix. Note that happens only because the clock
660 domain is defined (using ClockDomain objects), not simply referenced
661 (using e.g. synchronous statements) in the video output modules.
662
663 Clock domain name overlap is an error condition when any of the submod‐
664 ules that defines the clock domains is anonymous.
665
666 Finalization mechanism
667 Sometimes, it is desirable that some of a module logic be created only
668 after the user has finished manipulating that module. For example, the
669 FSM module supports that states be defined dynamically, and the width
670 of the state signal can be known only after all states have been added.
671 One solution is to declare the final number of states in the FSM con‐
672 structor, but this is not user-friendly. A better solution is to auto‐
673 matically create the state signal just before the FSM module is con‐
674 verted to V*HDL. Migen supports this using the so-called finalization
675 mechanism.
676
677 Modules can overload a do_finalize method that can create logic and is
678 called using the algorithm below:
679
680 1. Finalization of the current module begins.
681
682 2. If the module has already been finalized (e.g. manually), the proce‐
683 dure stops here.
684
685 3. Submodules of the current module are recursively finalized.
686
687 4. do_finalize is called for the current module.
688
689 5. Any new submodules created by the current module's do_finalize are
690 recursively finalized.
691
692 Finalization is automatically invoked at V*HDL conversion and at simu‐
693 lation. It can be manually invoked for any module by calling its final‐
694 ize method.
695
696 The clock domain management mechanism explained above happens during
697 finalization.
698
699 Conversion for synthesis
700 Any FHDL module can be converted into synthesizable Verilog HDL. This
701 is accomplished by using the convert function in the migen.fhdl.verilog
702 module:
703
704 # define FHDL module MyDesign here
705
706 if __name__ == "__main__":
707 from migen.fhdl.verilog import convert
708 convert(MyDesign()).write("my_design.v")
709
710 The migen.build component provides scripts to interface third-party
711 FPGA tools (from Xilinx, Altera and Lattice) to Migen, and a database
712 of boards for the easy deployment of designs.
713
715 Migen allows you to easily simulate your FHDL design and interface it
716 with arbitrary Python code. The simulator is written in pure Python and
717 interprets the FHDL structure directly without using an external Ver‐
718 ilog simulator.
719
720 Migen lets you write testbenches using Python's generator functions.
721 Such testbenches execute concurrently with the FHDL simulator, and com‐
722 municate with it using the yield statement. There are four basic pat‐
723 terns:
724
725 1. Reads: the state of the signal at the current time can be queried
726 using (yield signal);
727
728 2. Writes: the state of the signal after the next clock cycle can be
729 set using (yield signal.eq(value));
730
731 3. Clocking: simulation can be advanced by one clock cycle using
732 yield;
733
734 4. Composition: control can be transferred to another testbench
735 function using yield from run_other().
736
737 A testbench can be run using the run_simulation function from
738 migen.sim; run_simulation(dut, bench) runs the generator function bench
739 against the logic defined in an FHDL module dut.
740
741 Passing the vcd_name="file.vcd" argument to run_simulation will cause
742 it to write a VCD dump of the signals inside dut to file.vcd.
743
744 Examples
745 For example, consider this module:
746
747 class ORGate(Module):
748 def __init__(self):
749 self.a = Signal()
750 self.b = Signal()
751 self.x = Signal()
752
753 ###
754
755 self.comb += self.x.eq(self.a | self.b)
756
757 It could be simulated together with the following testbench:
758
759 dut = ORGate()
760
761 def testbench():
762 yield dut.a.eq(0)
763 yield dut.b.eq(0)
764 yield
765 assert (yield dut.x) == 0
766
767 yield dut.a.eq(0)
768 yield dut.b.eq(1)
769 yield
770 assert (yield dut.x) == 1
771
772 run_simulation(dut, testbench())
773
774 This is, of course, quite verbose, and individual steps can be factored
775 into a separate function:
776
777 dut = ORGate()
778
779 def check_case(a, b, x):
780 yield dut.a.eq(a)
781 yield dut.b.eq(b)
782 yield
783 assert (yield dut.x) == x
784
785 def testbench():
786 yield from check_case(0, 0, 0)
787 yield from check_case(0, 1, 1)
788 yield from check_case(1, 0, 1)
789 yield from check_case(1, 1, 1)
790
791 run_simulation(dut, testbench())
792
793 Pitfalls
794 There are, unfortunately, some basic mistakes that can produce very
795 puzzling results.
796
797 When calling other testbenches, it is important to not forget the yield
798 from. If it is omitted, the call would silently do nothing.
799
800 When writing to a signal, it is important that nothing else should
801 drive the signal concurrently. If that is not the case, the write would
802 silently do nothing.
803
805 [To be written]
806
808 fhdl.structure module
809 class migen.fhdl.structure.Array(iterable=(), /)
810 Bases: list
811
812 Addressable multiplexer
813
814 An array is created from an iterable of values and indexed using
815 the usual Python simple indexing notation (no negative indices
816 or slices). It can be indexed by numeric constants, _Value s, or
817 Signal s.
818
819 The result of indexing the array is a proxy for the entry at the
820 given index that can be used on either RHS or LHS of assign‐
821 ments.
822
823 An array can be indexed multiple times.
824
825 Multidimensional arrays are supported by packing inner arrays
826 into outer arrays.
827
828 Parameters
829 values (iterable of ints, _Values, Signals) -- Entries of
830 the array. Each entry can be a numeric constant, a Signal
831 or a Record.
832
833 Examples
834
835 >>> a = Array(range(10))
836 >>> b = Signal(max=10)
837 >>> c = Signal(max=10)
838 >>> b.eq(a[9 - c])
839
840 migen.fhdl.structure.C
841 alias of migen.fhdl.structure.Constant
842
843 class migen.fhdl.structure.Case(test, cases)
844 Bases: migen.fhdl.structure._Statement
845
846 Case/Switch statement
847
848 Parameters
849
850 · test (_Value, in) -- Selector value used to decide
851 which block to execute
852
853 · cases (dict) -- Dictionary of cases. The keys are
854 numeric constants to compare with test. The values are
855 statements to be executed the corresponding key matches
856 test. The dictionary may contain a string key "default"
857 to mark a fall-through case that is executed if no
858 other key matches.
859
860 Examples
861
862 >>> a = Signal()
863 >>> b = Signal()
864 >>> Case(a, {
865 ... 0: b.eq(1),
866 ... 1: b.eq(0),
867 ... "default": b.eq(0),
868 ... })
869
870 makedefault(key=None)
871 Mark a key as the default case
872
873 Deletes/substitutes any previously existing default case.
874
875 Parameters
876 key (int, Constant or None) -- Key to use as
877 default case if no other key matches. By default,
878 the largest key is the default key.
879
880 class migen.fhdl.structure.Cat(*args)
881 Bases: migen.fhdl.structure._Value
882
883 Concatenate values
884
885 Form a compound _Value from several smaller ones by concatena‐
886 tion. The first argument occupies the lower bits of the result.
887 The return value can be used on either side of an assignment,
888 that is, the concatenated value can be used as an argument on
889 the RHS or as a target on the LHS. If it is used on the LHS, it
890 must solely consist of Signal s, slices of Signal s, and other
891 concatenations meeting these properties. The bit length of the
892 return value is the sum of the bit lengths of the arguments:
893
894 len(Cat(args)) == sum(len(arg) for arg in args)
895
896 Parameters
897 *args (_Values or iterables of _Values, inout) -- _Value
898 s to be concatenated.
899
900 Returns
901 Resulting _Value obtained by concatentation.
902
903 Return type
904 Cat, inout
905
906 class migen.fhdl.structure.ClockDomain(name=None, reset_less=False)
907 Bases: object
908
909 Synchronous domain
910
911 Parameters
912
913 · name (str or None) -- Domain name. If None (the
914 default) the name is inferred from the variable name
915 this ClockDomain is assigned to (stripping any "cd_"
916 prefix).
917
918 · reset_less (bool) -- The domain does not use a reset
919 signal. Registers within this domain are still all ini‐
920 tialized to their reset state once, e.g. through Ver‐
921 ilog "initial" statements.
922
923 clk The clock for this domain. Can be driven or used to drive
924 other signals (preferably in combinatorial context).
925
926 Type Signal, inout
927
928 rst Reset signal for this domain. Can be driven or used to
929 drive.
930
931 Type Signal or None, inout
932
933 rename(new_name)
934 Rename the clock domain
935
936 Parameters
937 new_name (str) -- New name
938
939 class migen.fhdl.structure.ClockSignal(cd='sys')
940 Bases: migen.fhdl.structure._Value
941
942 Clock signal for a given clock domain
943
944 ClockSignal s for a given clock domain can be retrieved multiple
945 times. They all ultimately refer to the same signal.
946
947 Parameters
948 cd (str) -- Clock domain to obtain a clock signal for.
949 Defaults to "sys".
950
951 class migen.fhdl.structure.Constant(value, bits_sign=None)
952 Bases: migen.fhdl.structure._Value
953
954 A constant, HDL-literal integer _Value
955
956 Parameters
957
958 · value (int) --
959
960 · bits_sign (int or tuple or None) -- Either an integer
961 bits or a tuple (bits, signed) specifying the number of
962 bits in this Constant and whether it is signed (can
963 represent negative values). bits_sign defaults to the
964 minimum width and signedness of value.
965
966 class migen.fhdl.structure.DUID
967 Bases: object
968
969 Deterministic Unique IDentifier
970
971 class migen.fhdl.structure.If(cond, *t)
972 Bases: migen.fhdl.structure._Statement
973
974 Conditional execution of statements
975
976 Parameters
977
978 · cond (_Value(1), in) -- Condition
979
980 · *t (Statements) -- Statements to execute if cond is
981 asserted.
982
983 Examples
984
985 >>> a = Signal()
986 >>> b = Signal()
987 >>> c = Signal()
988 >>> d = Signal()
989 >>> If(a,
990 ... b.eq(1)
991 ... ).Elif(c,
992 ... b.eq(0)
993 ... ).Else(
994 ... b.eq(d)
995 ... )
996
997 Elif(cond, *t)
998 Add an else if conditional block
999
1000 Parameters
1001
1002 · cond (_Value(1), in) -- Condition
1003
1004 · *t (Statements) -- Statements to execute if pre‐
1005 vious conditions fail and cond is asserted.
1006
1007 Else(*f)
1008 Add an else conditional block
1009
1010 Parameters
1011 *f (Statements) -- Statements to execute if all
1012 previous conditions fail.
1013
1014 migen.fhdl.structure.Mux(sel, val1, val0)
1015 Multiplex between two values
1016
1017 Parameters
1018
1019 · sel (_Value(1), in) -- Selector.
1020
1021 · val1 (_Value(N), in) --
1022
1023 · val0 (_Value(N), in) -- Input values.
1024
1025 Returns
1026 Output _Value. If sel is asserted, the Mux returns val1,
1027 else val0.
1028
1029 Return type
1030 _Value(N), out
1031
1032 class migen.fhdl.structure.Replicate(v, n)
1033 Bases: migen.fhdl.structure._Value
1034
1035 Replicate a value
1036
1037 An input value is replicated (repeated) several times to be used
1038 on the RHS of assignments:
1039
1040 len(Replicate(s, n)) == len(s)*n
1041
1042 Parameters
1043
1044 · v (_Value, in) -- Input value to be replicated.
1045
1046 · n (int) -- Number of replications.
1047
1048 Returns
1049 Replicated value.
1050
1051 Return type
1052 Replicate, out
1053
1054 class migen.fhdl.structure.ResetSignal(cd='sys',
1055 allow_reset_less=False)
1056 Bases: migen.fhdl.structure._Value
1057
1058 Reset signal for a given clock domain
1059
1060 ResetSignal s for a given clock domain can be retrieved multiple
1061 times. They all ultimately refer to the same signal.
1062
1063 Parameters
1064
1065 · cd (str) -- Clock domain to obtain a reset signal for.
1066 Defaults to "sys".
1067
1068 · allow_reset_less (bool) -- If the clock domain is
1069 resetless, return 0 instead of reporting an error.
1070
1071 class migen.fhdl.structure.Signal(bits_sign=None, name=None, vari‐
1072 able=False, reset=0, reset_less=False, name_override=None, min=None,
1073 max=None, related=None, attr=None)
1074 Bases: migen.fhdl.structure._Value
1075
1076 A _Value that can change
1077
1078 The Signal object represents a value that is expected to change
1079 in the circuit. It does exactly what Verilog's wire and reg and
1080 VHDL's signal do.
1081
1082 A Signal can be indexed to access a subset of its bits. Negative
1083 indices (signal[-1]) and the extended Python slicing notation
1084 (signal[start:stop:step]) are supported. The indices 0 and -1
1085 are the least and most significant bits respectively.
1086
1087 Parameters
1088
1089 · bits_sign (int or tuple) -- Either an integer bits or a
1090 tuple (bits, signed) specifying the number of bits in
1091 this Signal and whether it is signed (can represent
1092 negative values). signed defaults to False.
1093
1094 · name (str or None) -- Name hint for this signal. If
1095 None (default) the name is inferred from the variable
1096 name this Signal is assigned to. Name collisions are
1097 automatically resolved by prepending names of objects
1098 that contain this Signal and by appending integer
1099 sequences.
1100
1101 · variable (bool) -- Deprecated.
1102
1103 · reset (int) -- Reset (synchronous) or default (combina‐
1104 torial) value. When this Signal is assigned to in syn‐
1105 chronous context and the corresponding clock domain is
1106 reset, the Signal assumes the given value. When this
1107 Signal is unassigned in combinatorial context (due to
1108 conditional assignments not being taken), the Signal
1109 assumes its reset value. Defaults to 0.
1110
1111 · reset_less (bool) -- If True, do not generate reset
1112 logic for this Signal in synchronous statements. The
1113 reset value is only used as a combinatorial default or
1114 as the initial value. Defaults to False.
1115
1116 · name_override (str or None) -- Do not use the inferred
1117 name but the given one.
1118
1119 · min (int or None) --
1120
1121 · max (int or None) -- If bits_sign is None, the signal
1122 bit width and signedness are determined by the integer
1123 range given by min (inclusive, defaults to 0) and max
1124 (exclusive, defaults to 2).
1125
1126 · related (Signal or None) --
1127
1128 · attr (set of synthesis attributes) --
1129
1130 classmethod like(other, **kwargs)
1131 Create Signal based on another.
1132
1133 Parameters
1134
1135 · other (_Value) -- Object to base this Signal on.
1136
1137 · migen.fhdl.bitcontainer.value_bits_sign for
1138 details. (See) --
1139
1140 migen.fhdl.structure.wrap(value)
1141 Ensures that the passed object is a Migen value. Booleans and
1142 integers are automatically wrapped into Constant.
1143
1144 fhdl.bitcontainer module
1145 migen.fhdl.bitcontainer.value_bits_sign(v)
1146 Bit length and signedness of a value.
1147
1148 Parameters
1149 v (Value) --
1150
1151 Returns
1152 Number of bits required to store v or available in v,
1153 followed by whether v has a sign bit (included in the bit
1154 count).
1155
1156 Return type
1157 int, bool
1158
1159 Examples
1160
1161 >>> value_bits_sign(f.Signal(8))
1162 8, False
1163 >>> value_bits_sign(C(0xaa))
1164 8, False
1165
1166 genlib.fifo module
1167 class migen.genlib.fifo.AsyncFIFO(width, depth)
1168 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1169 face
1170
1171 Asynchronous FIFO (first in, first out)
1172
1173 Read and write interfaces are accessed from different clock
1174 domains, named read and write. Use ClockDomainsRenamer to rename
1175 to other names.
1176
1177 Data written to the input interface (din, we, writable) is
1178 buffered and can be read at the output interface (dout, re,
1179 readable). The data entry written first to the input also
1180 appears first on the output.
1181
1182 Parameters
1183
1184 · width (int) -- Bit width for the data.
1185
1186 · depth (int) -- Depth of the FIFO.
1187
1188 din Input data
1189
1190 Type in, width
1191
1192 writable
1193 There is space in the FIFO and we can be asserted to load
1194 new data.
1195
1196 Type out
1197
1198 we Write enable signal to latch din into the FIFO. Does
1199 nothing if writable is not asserted.
1200
1201 Type in
1202
1203 dout Output data. Only valid if readable is asserted.
1204
1205 Type out, width
1206
1207 readable
1208 Output data dout valid, FIFO not empty.
1209
1210 Type out
1211
1212 re Acknowledge dout. If asserted, the next entry will be
1213 available on the next cycle (if readable is high then).
1214
1215 Type in
1216
1217 class migen.genlib.fifo.AsyncFIFOBuffered(width, depth)
1218 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1219 face
1220
1221 Improves timing when it breaks due to sluggish clock-to-output
1222 delay in e.g. Xilinx block RAMs. Increases latency by one cycle.
1223
1224 class migen.genlib.fifo.SyncFIFO(width, depth, fwft=True)
1225 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1226 face
1227
1228 Synchronous FIFO (first in, first out)
1229
1230 Read and write interfaces are accessed from the same clock
1231 domain. If different clock domains are needed, use AsyncFIFO.
1232
1233 Data written to the input interface (din, we, writable) is
1234 buffered and can be read at the output interface (dout, re,
1235 readable). The data entry written first to the input also
1236 appears first on the output.
1237
1238 Parameters
1239
1240 · width (int) -- Bit width for the data.
1241
1242 · depth (int) -- Depth of the FIFO.
1243
1244 din Input data
1245
1246 Type in, width
1247
1248 writable
1249 There is space in the FIFO and we can be asserted to load
1250 new data.
1251
1252 Type out
1253
1254 we Write enable signal to latch din into the FIFO. Does
1255 nothing if writable is not asserted.
1256
1257 Type in
1258
1259 dout Output data. Only valid if readable is asserted.
1260
1261 Type out, width
1262
1263 readable
1264 Output data dout valid, FIFO not empty.
1265
1266 Type out
1267
1268 re Acknowledge dout. If asserted, the next entry will be
1269 available on the next cycle (if readable is high then).
1270
1271 Type in
1272
1273 level Number of unread entries.
1274
1275 Type out
1276
1277 replace
1278 Replaces the last entry written into the FIFO with din.
1279 Does nothing if that entry has already been read (i.e.
1280 the FIFO is empty). Assert in conjunction with we.
1281
1282 Type in
1283
1284 class migen.genlib.fifo.SyncFIFOBuffered(width, depth)
1285 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1286 face
1287
1288 Has an interface compatible with SyncFIFO with fwft=True, but
1289 does not use asynchronous RAM reads that are not compatible with
1290 block RAMs. Increases latency by one cycle.
1291
1292 genlib.coding module
1293 Encoders and decoders between binary and one-hot representation
1294
1295 class migen.genlib.coding.Decoder(width)
1296 Bases: migen.fhdl.module.Module
1297
1298 Decode binary to one-hot
1299
1300 If n is low, the i th bit in o is asserted, the others are not,
1301 else o == 0.
1302
1303 Parameters
1304 width (int) -- Bit width of the output
1305
1306 i Input binary
1307
1308 Type Signal(max=width), in
1309
1310 o Decoded one-hot
1311
1312 Type Signal(width), out
1313
1314 n Invalid, no output bits are to be asserted
1315
1316 Type [22mSignal(1), in
1317
1318 class migen.genlib.coding.Encoder(width)
1319 Bases: migen.fhdl.module.Module
1320
1321 Encode one-hot to binary
1322
1323 If n is low, the o th bit in i is asserted, else none or multi‐
1324 ple bits are asserted.
1325
1326 Parameters
1327 width (int) -- Bit width of the input
1328
1329 i One-hot input
1330
1331 Type Signal(width), in
1332
1333 o Encoded binary
1334
1335 Type Signal(max=width), out
1336
1337 n Invalid, either none or multiple input bits are asserted
1338
1339 Type [22mSignal(1), out
1340
1341 class migen.genlib.coding.PriorityDecoder(width)
1342 Bases: migen.genlib.coding.Decoder
1343
1344 class migen.genlib.coding.PriorityEncoder(width)
1345 Bases: migen.fhdl.module.Module
1346
1347 Priority encode requests to binary
1348
1349 If n is low, the o th bit in i is asserted and the bits below o
1350 are unasserted, else o == 0. The LSB has priority.
1351
1352 Parameters
1353 width (int) -- Bit width of the input
1354
1355 i Input requests
1356
1357 Type Signal(width), in
1358
1359 o Encoded binary
1360
1361 Type Signal(max=width), out
1362
1363 n Invalid, no input bits are asserted
1364
1365 Type [22mSignal(1), out
1366
1367 genlib.sort module
1368 class migen.genlib.sort.BitonicSort(n, m, ascending=True)
1369 Bases: migen.fhdl.module.Module
1370
1371 Combinatorial sorting network
1372
1373 The Bitonic sort is implemented as a combinatorial sort using
1374 comparators and multiplexers. Its asymptotic complexity (in
1375 terms of number of comparators/muxes) is O(n log(n)**2), like
1376 mergesort or shellsort.
1377
1378 http://www.dps.uibk.ac.at/~cosenza/teaching/gpu/sort-batcher.pdf
1379
1380 http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm
1381
1382 http://www.myhdl.org/doku.php/cookbook:bitonic
1383
1384 Parameters
1385
1386 · n (int) -- Number of inputs and output signals.
1387
1388 · m (int) -- Bit width of inputs and outputs. Or a tuple
1389 of (m, signed).
1390
1391 · ascending (bool) -- Sort direction. True if input is to
1392 be sorted ascending, False for descending. Defaults to
1393 ascending.
1394
1395 i Input values, each m wide.
1396
1397 Type list of Signals, in
1398
1399 o Output values, sorted, each m bits wide.
1400
1401 Type list of Signals, out
1402
1403 genlib.fsm module
1404 class migen.genlib.fsm.FSM(reset_state=None)
1405 Bases: migen.fhdl.module.Module
1406
1407 Finite state machine
1408
1409 Any Python objects can be used as states, e.g. strings.
1410
1411 Parameters
1412 reset_state -- Reset state. Defaults to the first added
1413 state.
1414
1415 Examples
1416
1417 >>> self.active = Signal()
1418 >>> self.bitno = Signal(3)
1419 >>>
1420 >>> fsm = FSM(reset_state="START")
1421 >>> self.submodules += fsm
1422 >>>
1423 >>> fsm.act("START",
1424 ... self.active.eq(1),
1425 ... If(strobe,
1426 ... NextState("DATA")
1427 ... )
1428 ... )
1429 >>> fsm.act("DATA",
1430 ... self.active.eq(1),
1431 ... If(strobe,
1432 ... NextValue(self.bitno, self.bitno + 1),
1433 ... If(self.bitno == 7,
1434 ... NextState("END")
1435 ... )
1436 ... )
1437 ... )
1438 >>> fsm.act("END",
1439 ... self.active.eq(0),
1440 ... NextState("STOP")
1441 ... )
1442
1443 act(state, *statements)
1444 Schedules statements to be executed in state. Statements
1445 may include:
1446
1447 · combinatorial statements of form a.eq(b), equivalent
1448 to self.comb += a.eq(b) when the FSM is in the given
1449 state;
1450
1451 · synchronous statements of form NextValue(a, b),
1452 equivalent to self.sync += a.eq(b) when the FSM is
1453 in the given state;
1454
1455 · a statement of form NextState(new_state), selecting
1456 the next state;
1457
1458 · If, Case, etc.
1459
1460 ongoing(state)
1461 Returns a signal that has the value 1 when the FSM is in
1462 the given state, and 0 otherwise.
1463
1465 Sebastien Bourdeauducq
1466
1468 2011-2021, M-Labs Limited
1469
1470
1471
1472
14730.9 Mar 07, 2021 MIGEN(1)