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
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 Examples.sp
833 >>> a = Array(range(10))
834 >>> b = Signal(max=10)
835 >>> c = Signal(max=10)
836 >>> b.eq(a[9 - c])
837
838 migen.fhdl.structure.C
839 alias of migen.fhdl.structure.Constant
840
841 class migen.fhdl.structure.Case(test, cases)
842 Bases: migen.fhdl.structure._Statement
843
844 Case/Switch statement
845
846 Parameters
847
848 · test (_Value, in) -- Selector value used to decide
849 which block to execute
850
851 · cases (dict) -- Dictionary of cases. The keys are
852 numeric constants to compare with test. The values are
853 statements to be executed the corresponding key matches
854 test. The dictionary may contain a string key "default"
855 to mark a fall-through case that is executed if no
856 other key matches.
857 Examples.sp
858 >>> a = Signal()
859 >>> b = Signal()
860 >>> Case(a, {
861 ... 0: b.eq(1),
862 ... 1: b.eq(0),
863 ... "default": b.eq(0),
864 ... })
865
866 makedefault(key=None)
867 Mark a key as the default case
868
869 Deletes/substitutes any previously existing default case.
870
871 Parameters
872 key (int, Constant or None) -- Key to use as
873 default case if no other key matches. By default,
874 the largest key is the default key.
875
876 class migen.fhdl.structure.Cat(*args)
877 Bases: migen.fhdl.structure._Value
878
879 Concatenate values
880
881 Form a compound _Value from several smaller ones by concatena‐
882 tion. The first argument occupies the lower bits of the result.
883 The return value can be used on either side of an assignment,
884 that is, the concatenated value can be used as an argument on
885 the RHS or as a target on the LHS. If it is used on the LHS, it
886 must solely consist of Signal s, slices of Signal s, and other
887 concatenations meeting these properties. The bit length of the
888 return value is the sum of the bit lengths of the arguments:
889
890 len(Cat(args)) == sum(len(arg) for arg in args)
891
892 Parameters
893 *args (_Values or iterables of _Values, inout) -- _Value
894 s to be concatenated.
895
896 Returns
897 Resulting _Value obtained by concatentation.
898
899 Return type
900 Cat, inout
901
902 class migen.fhdl.structure.ClockDomain(name=None, reset_less=False)
903 Bases: object
904
905 Synchronous domain
906
907 Parameters
908
909 · name (str or None) -- Domain name. If None (the
910 default) the name is inferred from the variable name
911 this ClockDomain is assigned to (stripping any "cd_"
912 prefix).
913
914 · reset_less (bool) -- The domain does not use a reset
915 signal. Registers within this domain are still all ini‐
916 tialized to their reset state once, e.g. through Ver‐
917 ilog "initial" statements.
918
919 clk Signal, inout -- The clock for this domain. Can be driven
920 or used to drive other signals (preferably in combinato‐
921 rial context).
922
923 rst Signal or None, inout -- Reset signal for this domain.
924 Can be driven or used to drive.
925
926 rename(new_name)
927 Rename the clock domain
928
929 Parameters
930 new_name (str) -- New name
931
932 class migen.fhdl.structure.ClockSignal(cd='sys')
933 Bases: migen.fhdl.structure._Value
934
935 Clock signal for a given clock domain
936
937 ClockSignal s for a given clock domain can be retrieved multiple
938 times. They all ultimately refer to the same signal.
939
940 Parameters
941 cd (str) -- Clock domain to obtain a clock signal for.
942 Defaults to "sys".
943
944 class migen.fhdl.structure.Constant(value, bits_sign=None)
945 Bases: migen.fhdl.structure._Value
946
947 A constant, HDL-literal integer _Value
948
949 Parameters
950
951 · value (int) --
952
953 · bits_sign (int or tuple or None) -- Either an integer
954 bits or a tuple (bits, signed) specifying the number of
955 bits in this Constant and whether it is signed (can
956 represent negative values). bits_sign defaults to the
957 minimum width and signedness of value.
958
959 class migen.fhdl.structure.DUID
960 Bases: object
961
962 Deterministic Unique IDentifier
963
964 class migen.fhdl.structure.If(cond, *t)
965 Bases: migen.fhdl.structure._Statement
966
967 Conditional execution of statements
968
969 Parameters
970
971 · cond (_Value(1), in) -- Condition
972
973 · *t (Statements) -- Statements to execute if cond is
974 asserted.
975 Examples.sp
976 >>> a = Signal()
977 >>> b = Signal()
978 >>> c = Signal()
979 >>> d = Signal()
980 >>> If(a,
981 ... b.eq(1)
982 ... ).Elif(c,
983 ... b.eq(0)
984 ... ).Else(
985 ... b.eq(d)
986 ... )
987
988 Elif(cond, *t)
989 Add an else if conditional block
990
991 Parameters
992
993 · cond (_Value(1), in) -- Condition
994
995 · *t (Statements) -- Statements to execute if pre‐
996 vious conditions fail and cond is asserted.
997
998 Else(*f)
999 Add an else conditional block
1000
1001 Parameters
1002 *f (Statements) -- Statements to execute if all
1003 previous conditions fail.
1004
1005 migen.fhdl.structure.Mux(sel, val1, val0)
1006 Multiplex between two values
1007
1008 Parameters
1009
1010 · sel (_Value(1), in) -- Selector.
1011
1012 · val1 (_Value(N), in) --
1013
1014 · val0 (_Value(N), in) -- Input values.
1015
1016 Returns
1017 Output _Value. If sel is asserted, the Mux returns val1,
1018 else val0.
1019
1020 Return type
1021 _Value(N), out
1022
1023 class migen.fhdl.structure.Replicate(v, n)
1024 Bases: migen.fhdl.structure._Value
1025
1026 Replicate a value
1027
1028 An input value is replicated (repeated) several times to be used
1029 on the RHS of assignments:
1030
1031 len(Replicate(s, n)) == len(s)*n
1032
1033 Parameters
1034
1035 · v (_Value, in) -- Input value to be replicated.
1036
1037 · n (int) -- Number of replications.
1038
1039 Returns
1040 Replicated value.
1041
1042 Return type
1043 Replicate, out
1044
1045 class migen.fhdl.structure.ResetSignal(cd='sys',
1046 allow_reset_less=False)
1047 Bases: migen.fhdl.structure._Value
1048
1049 Reset signal for a given clock domain
1050
1051 ResetSignal s for a given clock domain can be retrieved multiple
1052 times. They all ultimately refer to the same signal.
1053
1054 Parameters
1055
1056 · cd (str) -- Clock domain to obtain a reset signal for.
1057 Defaults to "sys".
1058
1059 · allow_reset_less (bool) -- If the clock domain is
1060 resetless, return 0 instead of reporting an error.
1061
1062 class migen.fhdl.structure.Signal(bits_sign=None, name=None, vari‐
1063 able=False, reset=0, reset_less=False, name_override=None, min=None,
1064 max=None, related=None, attr=None)
1065 Bases: migen.fhdl.structure._Value
1066
1067 A _Value that can change
1068
1069 The Signal object represents a value that is expected to change
1070 in the circuit. It does exactly what Verilog's wire and reg and
1071 VHDL's signal do.
1072
1073 A Signal can be indexed to access a subset of its bits. Negative
1074 indices (signal[-1]) and the extended Python slicing notation
1075 (signal[start:stop:step]) are supported. The indices 0 and -1
1076 are the least and most significant bits respectively.
1077
1078 Parameters
1079
1080 · bits_sign (int or tuple) -- Either an integer bits or a
1081 tuple (bits, signed) specifying the number of bits in
1082 this Signal and whether it is signed (can represent
1083 negative values). signed defaults to False.
1084
1085 · name (str or None) -- Name hint for this signal. If
1086 None (default) the name is inferred from the variable
1087 name this Signal is assigned to. Name collisions are
1088 automatically resolved by prepending names of objects
1089 that contain this Signal and by appending integer
1090 sequences.
1091
1092 · variable (bool) -- Deprecated.
1093
1094 · reset (int) -- Reset (synchronous) or default (combina‐
1095 torial) value. When this Signal is assigned to in syn‐
1096 chronous context and the corresponding clock domain is
1097 reset, the Signal assumes the given value. When this
1098 Signal is unassigned in combinatorial context (due to
1099 conditional assignments not being taken), the Signal
1100 assumes its reset value. Defaults to 0.
1101
1102 · reset_less (bool) -- If True, do not generate reset
1103 logic for this Signal in synchronous statements. The
1104 reset value is only used as a combinatorial default or
1105 as the initial value. Defaults to False.
1106
1107 · name_override (str or None) -- Do not use the inferred
1108 name but the given one.
1109
1110 · min (int or None) --
1111
1112 · max (int or None) -- If bits_sign is None, the signal
1113 bit width and signedness are determined by the integer
1114 range given by min (inclusive, defaults to 0) and max
1115 (exclusive, defaults to 2).
1116
1117 · related (Signal or None) --
1118
1119 · attr (set of synthesis attributes) --
1120
1121 classmethod like(other, **kwargs)
1122 Create Signal based on another.
1123
1124 Parameters
1125
1126 · other (_Value) -- Object to base this Signal on.
1127
1128 · migen.fhdl.bitcontainer.value_bits_sign for
1129 details. (See) --
1130
1131 migen.fhdl.structure.wrap(value)
1132 Ensures that the passed object is a Migen value. Booleans and
1133 integers are automatically wrapped into Constant.
1134
1135 fhdl.bitcontainer module
1136 migen.fhdl.bitcontainer.value_bits_sign(v)
1137 Bit length and signedness of a value.
1138
1139 Parameters
1140 v (Value) --
1141
1142 Returns
1143 Number of bits required to store v or available in v,
1144 followed by whether v has a sign bit (included in the bit
1145 count).
1146
1147 Return type
1148 int, bool
1149 Examples.sp
1150 >>> value_bits_sign(f.Signal(8))
1151 8, False
1152 >>> value_bits_sign(C(0xaa))
1153 8, False
1154
1155 genlib.fifo module
1156 class migen.genlib.fifo.SyncFIFO(width, depth, fwft=True)
1157 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1158 face
1159
1160 Synchronous FIFO (first in, first out)
1161
1162 Read and write interfaces are accessed from the same clock
1163 domain. If different clock domains are needed, use AsyncFIFO.
1164
1165 Data written to the input interface (din, we, writable) is
1166 buffered and can be read at the output interface (dout, re,
1167 readable). The data entry written first to the input also
1168 appears first on the output.
1169
1170 Parameters
1171
1172 · width (int) -- Bit width for the data.
1173
1174 · depth (int) -- Depth of the FIFO.
1175
1176 din in, width -- Input data
1177
1178 writable
1179 out -- There is space in the FIFO and we can be asserted
1180 to load new data.
1181
1182 we in -- Write enable signal to latch din into the FIFO.
1183 Does nothing if writable is not asserted.
1184
1185 dout out, width -- Output data. Only valid if readable is
1186 asserted.
1187
1188 readable
1189 out -- Output data dout valid, FIFO not empty.
1190
1191 re in -- Acknowledge dout. If asserted, the next entry will
1192 be available on the next cycle (if readable is high
1193 then).
1194
1195 level out -- Number of unread entries.
1196
1197 replace
1198 in -- Replaces the last entry written into the FIFO with
1199 din. Does nothing if that entry has already been read
1200 (i.e. the FIFO is empty). Assert in conjunction with we.
1201
1202 class migen.genlib.fifo.SyncFIFOBuffered(width, depth)
1203 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1204 face
1205
1206 Has an interface compatible with SyncFIFO with fwft=True, but
1207 does not use asynchronous RAM reads that are not compatible with
1208 block RAMs. Increases latency by one cycle.
1209
1210 class migen.genlib.fifo.AsyncFIFO(width, depth)
1211 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1212 face
1213
1214 Asynchronous FIFO (first in, first out)
1215
1216 Read and write interfaces are accessed from different clock
1217 domains, named read and write. Use ClockDomainsRenamer to rename
1218 to other names.
1219
1220 Data written to the input interface (din, we, writable) is
1221 buffered and can be read at the output interface (dout, re,
1222 readable). The data entry written first to the input also
1223 appears first on the output.
1224
1225 Parameters
1226
1227 · width (int) -- Bit width for the data.
1228
1229 · depth (int) -- Depth of the FIFO.
1230
1231 din in, width -- Input data
1232
1233 writable
1234 out -- There is space in the FIFO and we can be asserted
1235 to load new data.
1236
1237 we in -- Write enable signal to latch din into the FIFO.
1238 Does nothing if writable is not asserted.
1239
1240 dout out, width -- Output data. Only valid if readable is
1241 asserted.
1242
1243 readable
1244 out -- Output data dout valid, FIFO not empty.
1245
1246 re in -- Acknowledge dout. If asserted, the next entry will
1247 be available on the next cycle (if readable is high
1248 then).
1249
1250 class migen.genlib.fifo.AsyncFIFOBuffered(width, depth)
1251 Bases: migen.fhdl.module.Module, migen.genlib.fifo._FIFOInter‐
1252 face
1253
1254 Improves timing when it breaks due to sluggish clock-to-output
1255 delay in e.g. Xilinx block RAMs. Increases latency by one cycle.
1256
1257 genlib.coding module
1258 Encoders and decoders between binary and one-hot representation
1259
1260 class migen.genlib.coding.Decoder(width)
1261 Bases: migen.fhdl.module.Module
1262
1263 Decode binary to one-hot
1264
1265 If n is low, the i th bit in o is asserted, the others are not,
1266 else o == 0.
1267
1268 Parameters
1269 width (int) -- Bit width of the output
1270
1271 i Signal(max=width), in -- Input binary
1272
1273 o Signal(width), out -- Decoded one-hot
1274
1275 n [22mSignal(1), in -- Invalid, no output bits are to be
1276 asserted
1277
1278 class migen.genlib.coding.Encoder(width)
1279 Bases: migen.fhdl.module.Module
1280
1281 Encode one-hot to binary
1282
1283 If n is low, the o th bit in i is asserted, else none or multi‐
1284 ple bits are asserted.
1285
1286 Parameters
1287 width (int) -- Bit width of the input
1288
1289 i Signal(width), in -- One-hot input
1290
1291 o Signal(max=width), out -- Encoded binary
1292
1293 n [22mSignal(1), out -- Invalid, either none or multiple input
1294 bits are asserted
1295
1296 class migen.genlib.coding.PriorityDecoder(width)
1297 Bases: migen.genlib.coding.Decoder
1298
1299 class migen.genlib.coding.PriorityEncoder(width)
1300 Bases: migen.fhdl.module.Module
1301
1302 Priority encode requests to binary
1303
1304 If n is low, the o th bit in i is asserted and the bits below o
1305 are unasserted, else o == 0. The LSB has priority.
1306
1307 Parameters
1308 width (int) -- Bit width of the input
1309
1310 i Signal(width), in -- Input requests
1311
1312 o Signal(max=width), out -- Encoded binary
1313
1314 n [22mSignal(1), out -- Invalid, no input bits are asserted
1315
1316 genlib.sort module
1317 class migen.genlib.sort.BitonicSort(n, m, ascending=True)
1318 Bases: migen.fhdl.module.Module
1319
1320 Combinatorial sorting network
1321
1322 The Bitonic sort is implemented as a combinatorial sort using
1323 comparators and multiplexers. Its asymptotic complexity (in
1324 terms of number of comparators/muxes) is O(n log(n)**2), like
1325 mergesort or shellsort.
1326
1327 http://www.dps.uibk.ac.at/~cosenza/teaching/gpu/sort-batcher.pdf
1328
1329 http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm
1330
1331 http://www.myhdl.org/doku.php/cookbook:bitonic
1332
1333 Parameters
1334
1335 · n (int) -- Number of inputs and output signals.
1336
1337 · m (int) -- Bit width of inputs and outputs. Or a tuple
1338 of (m, signed).
1339
1340 · ascending (bool) -- Sort direction. True if input is to
1341 be sorted ascending, False for descending. Defaults to
1342 ascending.
1343
1344 i list of Signals, in -- Input values, each m wide.
1345
1346 o list of Signals, out -- Output values, sorted, each m
1347 bits wide.
1348
1349 genlib.fsm module
1350 class migen.genlib.fsm.FSM(reset_state=None)
1351 Bases: migen.fhdl.module.Module
1352
1353 Finite state machine
1354
1355 Any Python objects can be used as states, e.g. strings.
1356
1357 Parameters
1358 reset_state -- Reset state. Defaults to the first added
1359 state.
1360 Examples.sp
1361 >>> self.active = Signal()
1362 >>> self.bitno = Signal(3)
1363 >>>
1364 >>> fsm = FSM(reset_state="START")
1365 >>> self.submodules += fsm
1366 >>>
1367 >>> fsm.act("START",
1368 ... self.active.eq(1),
1369 ... If(strobe,
1370 ... NextState("DATA")
1371 ... )
1372 ... )
1373 >>> fsm.act("DATA",
1374 ... self.active.eq(1),
1375 ... If(strobe,
1376 ... NextValue(self.bitno, self.bitno + 1),
1377 ... If(self.bitno == 7,
1378 ... NextState("END")
1379 ... )
1380 ... )
1381 ... )
1382 >>> fsm.act("END",
1383 ... self.active.eq(0),
1384 ... NextState("STOP")
1385 ... )
1386
1387 act(state, *statements)
1388 Schedules statements to be executed in state. Statements
1389 may include:
1390
1391 · combinatorial statements of form a.eq(b), equivalent
1392 to self.comb += a.eq(b) when the FSM is in the given
1393 state;
1394
1395 · synchronous statements of form NextValue(a, b),
1396 equivalent to self.sync += a.eq(b) when the FSM is
1397 in the given state;
1398
1399 · a statement of form NextState(new_state), selecting
1400 the next state;
1401
1402 · If, Case, etc.
1403
1404 ongoing(state)
1405 Returns a signal that has the value 1 when the FSM is in
1406 the given state, and 0 otherwise.
1407
1409 Sebastien Bourdeauducq
1410
1412 2011-2015, M-Labs Limited
1413
1414
1415
1416
14170.9 Jun 06, 2019 MIGEN(1)