vendor.lattice_{ice40,ecp5}: Support .il (RTLIL) files in extra_files
[nmigen.git] / nmigen / vendor / lattice_ecp5.py
1 from abc import abstractproperty
2
3 from ..hdl import *
4 from ..build import *
5
6
7 __all__ = ["LatticeECP5Platform"]
8
9
10 class LatticeECP5Platform(TemplatedPlatform):
11 """
12 Trellis toolchain
13 -----------------
14
15 Required tools:
16 * ``yosys``
17 * ``nextpnr-ecp5``
18 * ``ecppack``
19
20 The environment is populated by running the script specified in the environment variable
21 ``NMIGEN_ENV_Trellis``, if present.
22
23 Available overrides:
24 * ``verbose``: enables logging of informational messages to standard error.
25 * ``read_verilog_opts``: adds options for ``read_verilog`` Yosys command.
26 * ``synth_opts``: adds options for ``synth_ecp5`` Yosys command.
27 * ``script_after_read``: inserts commands after ``read_ilang`` in Yosys script.
28 * ``script_after_synth``: inserts commands after ``synth_ecp5`` in Yosys script.
29 * ``yosys_opts``: adds extra options for ``yosys``.
30 * ``nextpnr_opts``: adds extra options for ``nextpnr-ecp5``.
31 * ``ecppack_opts``: adds extra options for ``ecppack``.
32 * ``add_preferences``: inserts commands at the end of the LPF file.
33
34 Build products:
35 * ``{{name}}.rpt``: Yosys log.
36 * ``{{name}}.json``: synthesized RTL.
37 * ``{{name}}.tim``: nextpnr log.
38 * ``{{name}}.config``: ASCII bitstream.
39 * ``{{name}}.bit``: binary bitstream.
40 * ``{{name}}.svf``: JTAG programming vector.
41
42 Diamond toolchain
43 -----------------
44
45 Required tools:
46 * ``pnmainc``
47 * ``ddtcmd``
48
49 The environment is populated by running the script specified in the environment variable
50 ``NMIGEN_ENV_Diamond``, if present.
51
52 Available overrides:
53 * ``script_project``: inserts commands before ``prj_project save`` in Tcl script.
54 * ``script_after_export``: inserts commands after ``prj_run Export`` in Tcl script.
55 * ``add_preferences``: inserts commands at the end of the LPF file.
56 * ``add_constraints``: inserts commands at the end of the XDC file.
57
58 Build products:
59 * ``{{name}}_impl/{{name}}_impl.htm``: consolidated log.
60 * ``{{name}}.bit``: binary bitstream.
61 * ``{{name}}.svf``: JTAG programming vector.
62 """
63
64 toolchain = None # selected when creating platform
65
66 device = abstractproperty()
67 package = abstractproperty()
68 speed = abstractproperty()
69 grade = "C" # [C]ommercial, [I]ndustrial
70
71 # Trellis templates
72
73 _nextpnr_device_options = {
74 "LFE5U-12F": "--25k",
75 "LFE5U-25F": "--25k",
76 "LFE5U-45F": "--45k",
77 "LFE5U-85F": "--85k",
78 "LFE5UM-12F": "--um-25k",
79 "LFE5UM-25F": "--um-25k",
80 "LFE5UM-45F": "--um-45k",
81 "LFE5UM-85F": "--um-85k",
82 "LFE5UM5G-12F": "--um5g-25k",
83 "LFE5UM5G-25F": "--um5g-25k",
84 "LFE5UM5G-45F": "--um5g-45k",
85 "LFE5UM5G-85F": "--um5g-85k",
86 }
87 _nextpnr_package_options = {
88 "BG256": "caBGA256",
89 "MG285": "csfBGA285",
90 "BG381": "caBGA381",
91 "BG554": "caBGA554",
92 "BG756": "caBGA756",
93 }
94
95 _trellis_required_tools = [
96 "yosys",
97 "nextpnr-ecp5",
98 "ecppack"
99 ]
100 _trellis_file_templates = {
101 **TemplatedPlatform.build_script_templates,
102 "{{name}}.il": r"""
103 # {{autogenerated}}
104 {{emit_rtlil()}}
105 """,
106 "{{name}}.debug.v": r"""
107 /* {{autogenerated}} */
108 {{emit_debug_verilog()}}
109 """,
110 "{{name}}.ys": r"""
111 # {{autogenerated}}
112 {% for file in platform.iter_extra_files(".v") -%}
113 read_verilog {{get_override("read_verilog_opts")|options}} {{file}}
114 {% endfor %}
115 {% for file in platform.iter_extra_files(".sv") -%}
116 read_verilog -sv {{get_override("read_verilog_opts")|options}} {{file}}
117 {% endfor %}
118 {% for file in platform.iter_extra_files(".il") -%}
119 read_ilang {{file}}
120 {% endfor %}
121 read_ilang {{name}}.il
122 {{get_override("script_after_read")|default("# (script_after_read placeholder)")}}
123 synth_ecp5 {{get_override("synth_opts")|options}} -top {{name}}
124 {{get_override("script_after_synth")|default("# (script_after_synth placeholder)")}}
125 write_json {{name}}.json
126 """,
127 "{{name}}.lpf": r"""
128 # {{autogenerated}}
129 BLOCK ASYNCPATHS;
130 BLOCK RESETPATHS;
131 {% for port_name, pin_name, extras in platform.iter_port_constraints_bits() -%}
132 LOCATE COMP "{{port_name}}" SITE "{{pin_name}}";
133 {% if extras -%}
134 IOBUF PORT "{{port_name}}"
135 {%- for key, value in extras.items() %} {{key}}={{value}}{% endfor %};
136 {% endif %}
137 {% endfor %}
138 {% for signal, frequency in platform.iter_clock_constraints() -%}
139 FREQUENCY NET "{{signal|hierarchy(".")}}" {{frequency}} HZ;
140 {% endfor %}
141 {{get_override("add_preferences")|default("# (add_preferences placeholder)")}}
142 """
143 }
144 _trellis_command_templates = [
145 r"""
146 {{invoke_tool("yosys")}}
147 {{quiet("-q")}}
148 {{get_override("yosys_opts")|options}}
149 -l {{name}}.rpt
150 {{name}}.ys
151 """,
152 r"""
153 {{invoke_tool("nextpnr-ecp5")}}
154 {{quiet("--quiet")}}
155 {{get_override("nextpnr_opts")|options}}
156 --log {{name}}.tim
157 {{platform._nextpnr_device_options[platform.device]}}
158 --package {{platform._nextpnr_package_options[platform.package]|upper}}
159 --speed {{platform.speed}}
160 --json {{name}}.json
161 --lpf {{name}}.lpf
162 --textcfg {{name}}.config
163 """,
164 r"""
165 {{invoke_tool("ecppack")}}
166 {{verbose("--verbose")}}
167 {{get_override("ecppack_opts")|options}}
168 --input {{name}}.config
169 --bit {{name}}.bit
170 --svf {{name}}.svf
171 """
172 ]
173
174 # Diamond templates
175
176 _diamond_required_tools = [
177 "yosys",
178 "pnmainc",
179 "ddtcmd"
180 ]
181 _diamond_file_templates = {
182 **TemplatedPlatform.build_script_templates,
183 "build_{{name}}.sh": r"""
184 # {{autogenerated}}
185 set -e{{verbose("x")}}
186 if [ -z "$BASH" ] ; then exec /bin/bash "$0" "$@"; fi
187 if [ -n "${{platform._toolchain_env_var}}" ]; then
188 bindir=$(dirname "${{platform._toolchain_env_var}}")
189 . "${{platform._toolchain_env_var}}"
190 fi
191 {{emit_commands("sh")}}
192 """,
193 "{{name}}.v": r"""
194 /* {{autogenerated}} */
195 {{emit_verilog()}}
196 """,
197 "{{name}}.debug.v": r"""
198 /* {{autogenerated}} */
199 {{emit_debug_verilog()}}
200 """,
201 "{{name}}.tcl": r"""
202 prj_project new -name {{name}} -impl impl -impl_dir top_impl \
203 -dev {{platform.device}}-{{platform.speed}}{{platform.package}}{{platform.grade}} \
204 -lpf {{name}}.lpf \
205 -synthesis synplify
206 {% for file in platform.iter_extra_files(".v", ".sv", ".vhd", ".vhdl") -%}
207 prj_src add "{{file}}"
208 {% endfor %}
209 prj_src add {{name}}.v
210 prj_impl option top {{name}}
211 prj_src add {{name}}.sdc
212 {{get_override("script_project")|default("# (script_project placeholder)")}}
213 prj_project save
214 prj_run Synthesis -impl impl -forceAll
215 prj_run Translate -impl impl -forceAll
216 prj_run Map -impl impl -forceAll
217 prj_run PAR -impl impl -forceAll
218 prj_run Export -impl "impl" -forceAll -task Bitgen
219 {{get_override("script_after_export")|default("# (script_after_export placeholder)")}}
220 """,
221 "{{name}}.lpf": r"""
222 # {{autogenerated}}
223 BLOCK ASYNCPATHS;
224 BLOCK RESETPATHS;
225 {% for port_name, pin_name, extras in platform.iter_port_constraints_bits() -%}
226 LOCATE COMP "{{port_name}}" SITE "{{pin_name}}";
227 IOBUF PORT "{{port_name}}"
228 {%- for key, value in extras.items() %} {{key}}={{value}}{% endfor %};
229 {% endfor %}
230 {% for signal, frequency in platform.iter_clock_constraints() -%}
231 FREQUENCY NET "{{signal|hierarchy("/")}}" {{frequency/1000000}} MHZ;
232 {% endfor %}
233 {{get_override("add_preferences")|default("# (add_preferences placeholder)")}}
234 """,
235 "{{name}}.sdc": r"""
236 {% for signal, frequency in platform.iter_clock_constraints() -%}
237 create_clock -period {{1000000000/frequency}} [get_nets {{signal|hierarchy("/")}}]
238 {% endfor %}
239 {{get_override("add_constraints")|default("# (add_constraints placeholder)")}}
240 """,
241 }
242 _diamond_command_templates = [
243 # These don't have any usable command-line option overrides.
244 r"""
245 {{invoke_tool("pnmainc")}}
246 {{name}}.tcl
247 """,
248 r"""
249 {{invoke_tool("ddtcmd")}}
250 -oft -bit
251 -if {{name}}_impl/{{name}}_impl.bit -of {{name}}.bit
252 """,
253 r"""
254 {{invoke_tool("ddtcmd")}}
255 -oft -svfsingle -revd -op "Fast Program"
256 -if {{name}}_impl/{{name}}_impl.bit -of {{name}}.svf
257 """,
258 ]
259
260 # Common logic
261
262 def __init__(self, *, toolchain="Trellis"):
263 super().__init__()
264
265 assert toolchain in ("Trellis", "Diamond")
266 self.toolchain = toolchain
267
268 @property
269 def required_tools(self):
270 if self.toolchain == "Trellis":
271 return self._trellis_required_tools
272 if self.toolchain == "Diamond":
273 return self._diamond_required_tools
274 assert False
275
276 @property
277 def file_templates(self):
278 if self.toolchain == "Trellis":
279 return self._trellis_file_templates
280 if self.toolchain == "Diamond":
281 return self._diamond_file_templates
282 assert False
283
284 @property
285 def command_templates(self):
286 if self.toolchain == "Trellis":
287 return self._trellis_command_templates
288 if self.toolchain == "Diamond":
289 return self._diamond_command_templates
290 assert False
291
292 def create_missing_domain(self, name):
293 # Lattice ECP5 devices have two global set/reset signals: PUR, which is driven at startup
294 # by the configuration logic and unconditionally resets every storage element, and GSR,
295 # which is driven by user logic and each storage element may be configured as affected or
296 # unaffected by GSR. PUR is purely asynchronous, so even though it is a low-skew global
297 # network, its deassertion may violate a setup/hold constraint with relation to a user
298 # clock. To avoid this, a GSR/SGSR instance should be driven synchronized to user clock.
299 if name == "sync" and self.default_clk is not None:
300 clk_i = self.request(self.default_clk).i
301 if self.default_rst is not None:
302 rst_i = self.request(self.default_rst).i
303 else:
304 rst_i = Const(0)
305
306 gsr0 = Signal()
307 gsr1 = Signal()
308 m = Module()
309 # There is no end-of-startup signal on ECP5, but PUR is released after IOB enable, so
310 # a simple reset synchronizer (with PUR as the asynchronous reset) does the job.
311 m.submodules += [
312 Instance("FD1S3AX", p_GSR="DISABLED", i_CK=clk_i, i_D=~rst_i, o_Q=gsr0),
313 Instance("FD1S3AX", p_GSR="DISABLED", i_CK=clk_i, i_D=gsr0, o_Q=gsr1),
314 # Although we already synchronize the reset input to user clock, SGSR has dedicated
315 # clock routing to the center of the FPGA; use that just in case it turns out to be
316 # more reliable. (None of this is documented.)
317 Instance("SGSR", i_CLK=clk_i, i_GSR=gsr1),
318 ]
319 # GSR implicitly connects to every appropriate storage element. As such, the sync
320 # domain is reset-less; domains driven by other clocks would need to have dedicated
321 # reset circuitry or otherwise meet setup/hold constraints on their own.
322 m.domains += ClockDomain("sync", reset_less=True)
323 m.d.comb += ClockSignal("sync").eq(clk_i)
324 return m
325
326 _single_ended_io_types = [
327 "HSUL12", "LVCMOS12", "LVCMOS15", "LVCMOS18", "LVCMOS25", "LVCMOS33", "LVTTL33",
328 "SSTL135_I", "SSTL135_II", "SSTL15_I", "SSTL15_II", "SSTL18_I", "SSTL18_II",
329 ]
330 _differential_io_types = [
331 "BLVDS25", "BLVDS25E", "HSUL12D", "LVCMOS18D", "LVCMOS25D", "LVCMOS33D",
332 "LVDS", "LVDS25E", "LVPECL33", "LVPECL33E", "LVTTL33D", "MLVDS", "MLVDS25E",
333 "SLVS", "SSTL135D_II", "SSTL15D_II", "SSTL18D_II", "SUBLVDS",
334 ]
335
336 def should_skip_port_component(self, port, attrs, component):
337 # On ECP5, a differential IO is placed by only instantiating an IO buffer primitive at
338 # the PIOA or PIOC location, which is always the non-inverting pin.
339 if attrs.get("IO_TYPE", "LVCMOS25") in self._differential_io_types and component == "n":
340 return True
341 return False
342
343 def _get_xdr_buffer(self, m, pin, *, i_invert=False, o_invert=False):
344 def get_ireg(clk, d, q):
345 for bit in range(len(q)):
346 m.submodules += Instance("IFS1P3DX",
347 i_SCLK=clk,
348 i_SP=Const(1),
349 i_CD=Const(0),
350 i_D=d[bit],
351 o_Q=q[bit]
352 )
353
354 def get_oreg(clk, d, q):
355 for bit in range(len(q)):
356 m.submodules += Instance("OFS1P3DX",
357 i_SCLK=clk,
358 i_SP=Const(1),
359 i_CD=Const(0),
360 i_D=d[bit],
361 o_Q=q[bit]
362 )
363
364 def get_iddr(sclk, d, q0, q1):
365 for bit in range(len(d)):
366 m.submodules += Instance("IDDRX1F",
367 i_SCLK=sclk,
368 i_RST=Const(0),
369 i_D=d[bit],
370 o_Q0=q0[bit], o_Q1=q1[bit]
371 )
372
373 def get_oddr(sclk, d0, d1, q):
374 for bit in range(len(q)):
375 m.submodules += Instance("ODDRX1F",
376 i_SCLK=sclk,
377 i_RST=Const(0),
378 i_D0=d0[bit], i_D1=d1[bit],
379 o_Q=q[bit]
380 )
381
382 def get_ineg(z, invert):
383 if invert:
384 a = Signal.like(z, name_suffix="_n")
385 m.d.comb += z.eq(~a)
386 return a
387 else:
388 return z
389
390 def get_oneg(a, invert):
391 if invert:
392 z = Signal.like(a, name_suffix="_n")
393 m.d.comb += z.eq(~a)
394 return z
395 else:
396 return a
397
398 if "i" in pin.dir:
399 if pin.xdr < 2:
400 pin_i = get_ineg(pin.i, i_invert)
401 elif pin.xdr == 2:
402 pin_i0 = get_ineg(pin.i0, i_invert)
403 pin_i1 = get_ineg(pin.i1, i_invert)
404 if "o" in pin.dir:
405 if pin.xdr < 2:
406 pin_o = get_oneg(pin.o, o_invert)
407 elif pin.xdr == 2:
408 pin_o0 = get_oneg(pin.o0, o_invert)
409 pin_o1 = get_oneg(pin.o1, o_invert)
410
411 i = o = t = None
412 if "i" in pin.dir:
413 i = Signal(pin.width, name="{}_xdr_i".format(pin.name))
414 if "o" in pin.dir:
415 o = Signal(pin.width, name="{}_xdr_o".format(pin.name))
416 if pin.dir in ("oe", "io"):
417 t = Signal(1, name="{}_xdr_t".format(pin.name))
418
419 if pin.xdr == 0:
420 if "i" in pin.dir:
421 i = pin_i
422 if "o" in pin.dir:
423 o = pin_o
424 if pin.dir in ("oe", "io"):
425 t = ~pin.oe
426 elif pin.xdr == 1:
427 # Note that currently nextpnr will not pack an FF (*FS1P3DX) into the PIO.
428 if "i" in pin.dir:
429 get_ireg(pin.i_clk, i, pin_i)
430 if "o" in pin.dir:
431 get_oreg(pin.o_clk, pin_o, o)
432 if pin.dir in ("oe", "io"):
433 get_oreg(pin.o_clk, ~pin.oe, t)
434 elif pin.xdr == 2:
435 if "i" in pin.dir:
436 get_iddr(pin.i_clk, i, pin_i0, pin_i1)
437 if "o" in pin.dir:
438 get_oddr(pin.o_clk, pin_o0, pin_o1, o)
439 if pin.dir in ("oe", "io"):
440 # It looks like Diamond will not pack an OREG as a tristate register in a DDR PIO.
441 # It is not clear what is the recommended set of primitives for this task.
442 # Similarly, nextpnr will not pack anything as a tristate register in a DDR PIO.
443 get_oreg(pin.o_clk, ~pin.oe, t)
444 else:
445 assert False
446
447 return (i, o, t)
448
449 def get_input(self, pin, port, attrs, invert):
450 self._check_feature("single-ended input", pin, attrs,
451 valid_xdrs=(0, 1, 2), valid_attrs=True)
452 m = Module()
453 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert)
454 for bit in range(len(port)):
455 m.submodules["{}_{}".format(pin.name, bit)] = Instance("IB",
456 i_I=port[bit],
457 o_O=i[bit]
458 )
459 return m
460
461 def get_output(self, pin, port, attrs, invert):
462 self._check_feature("single-ended output", pin, attrs,
463 valid_xdrs=(0, 1, 2), valid_attrs=True)
464 m = Module()
465 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
466 for bit in range(len(port)):
467 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OB",
468 i_I=o[bit],
469 o_O=port[bit]
470 )
471 return m
472
473 def get_tristate(self, pin, port, attrs, invert):
474 self._check_feature("single-ended tristate", pin, attrs,
475 valid_xdrs=(0, 1, 2), valid_attrs=True)
476 m = Module()
477 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
478 for bit in range(len(port)):
479 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OBZ",
480 i_T=t,
481 i_I=o[bit],
482 o_O=port[bit]
483 )
484 return m
485
486 def get_input_output(self, pin, port, attrs, invert):
487 self._check_feature("single-ended input/output", pin, attrs,
488 valid_xdrs=(0, 1, 2), valid_attrs=True)
489 m = Module()
490 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert, o_invert=invert)
491 for bit in range(len(port)):
492 m.submodules["{}_{}".format(pin.name, bit)] = Instance("BB",
493 i_T=t,
494 i_I=o[bit],
495 o_O=i[bit],
496 io_B=port[bit]
497 )
498 return m
499
500 def get_diff_input(self, pin, p_port, n_port, attrs, invert):
501 self._check_feature("differential input", pin, attrs,
502 valid_xdrs=(0, 1, 2), valid_attrs=True)
503 m = Module()
504 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert)
505 for bit in range(len(p_port)):
506 m.submodules["{}_{}".format(pin.name, bit)] = Instance("IB",
507 i_I=p_port[bit],
508 o_O=i[bit]
509 )
510 return m
511
512 def get_diff_output(self, pin, p_port, n_port, attrs, invert):
513 self._check_feature("differential output", pin, attrs,
514 valid_xdrs=(0, 1, 2), valid_attrs=True)
515 m = Module()
516 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
517 for bit in range(len(p_port)):
518 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OB",
519 i_I=o[bit],
520 o_O=p_port[bit],
521 )
522 return m
523
524 def get_diff_tristate(self, pin, p_port, n_port, attrs, invert):
525 self._check_feature("differential tristate", pin, attrs,
526 valid_xdrs=(0, 1, 2), valid_attrs=True)
527 m = Module()
528 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
529 for bit in range(len(p_port)):
530 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OBZ",
531 i_T=t,
532 i_I=o[bit],
533 o_O=p_port[bit],
534 )
535 return m
536
537 def get_diff_input_output(self, pin, p_port, n_port, attrs, invert):
538 self._check_feature("differential input/output", pin, attrs,
539 valid_xdrs=(0, 1, 2), valid_attrs=True)
540 m = Module()
541 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert, o_invert=invert)
542 for bit in range(len(p_port)):
543 m.submodules["{}_{}".format(pin.name, bit)] = Instance("BB",
544 i_T=t,
545 i_I=o[bit],
546 o_O=i[bit],
547 io_B=p_port[bit],
548 )
549 return m
550
551 # CDC primitives are not currently specialized for ECP5.
552 # While Diamond supports false path constraints; nextpnr-ecp5 does not.