034dcc70142887cd2b1aaad3c17414ad2994f4b2
[litex.git] / litex / build / xilinx / vivado.py
1 # This file is Copyright (c) 2014 Florent Kermarrec <florent@enjoy-digital.fr>
2 # License: BSD
3
4 import os
5 import subprocess
6 import sys
7
8 from migen.fhdl.structure import _Fragment
9
10 from litex.build.generic_platform import *
11 from litex.build import tools
12 from litex.build.xilinx import common
13
14
15 def _format_constraint(c):
16 if isinstance(c, Pins):
17 return "set_property LOC " + c.identifiers[0]
18 elif isinstance(c, IOStandard):
19 return "set_property IOSTANDARD " + c.name
20 elif isinstance(c, Drive):
21 return "set_property DRIVE " + str(c.strength)
22 elif isinstance(c, Misc):
23 return "set_property " + c.misc.replace("=", " ")
24 elif isinstance(c, Inverted):
25 return None
26 else:
27 raise ValueError("unknown constraint {}".format(c))
28
29
30 def _format_xdc(signame, resname, *constraints):
31 fmt_c = [_format_constraint(c) for c in constraints]
32 fmt_r = resname[0] + ":" + str(resname[1])
33 if resname[2] is not None:
34 fmt_r += "." + resname[2]
35 r = " ## {}\n".format(fmt_r)
36 for c in fmt_c:
37 if c is not None:
38 r += c + " [get_ports " + signame + "]\n"
39 return r
40
41
42 def _build_xdc(named_sc, named_pc):
43 r = ""
44 for sig, pins, others, resname in named_sc:
45 if len(pins) > 1:
46 for i, p in enumerate(pins):
47 r += _format_xdc(sig + "[" + str(i) + "]", resname, Pins(p), *others)
48 elif pins:
49 r += _format_xdc(sig, resname, Pins(pins[0]), *others)
50 else:
51 r += _format_xdc(sig, resname, *others)
52 if named_pc:
53 r += "\n" + "\n\n".join(named_pc)
54 return r
55
56
57 def _run_vivado(build_name, vivado_path, source, ver=None):
58 if sys.platform == "win32" or sys.platform == "cygwin":
59 build_script_contents = "REM Autogenerated by LiteX\n"
60 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
61 build_script_file = "build_" + build_name + ".bat"
62 tools.write_to_file(build_script_file, build_script_contents)
63 command = build_script_file
64 else:
65 build_script_contents = "# Autogenerated by LiteX\nset -e\n"
66 settings = common.settings(vivado_path, ver)
67 build_script_contents += "source " + settings + "\n"
68 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
69 build_script_file = "build_" + build_name + ".sh"
70 tools.write_to_file(build_script_file, build_script_contents)
71 command = ["bash", build_script_file]
72 r = tools.subprocess_call_filtered(command, common.colors)
73 if r != 0:
74 raise OSError("Subprocess failed")
75
76
77 class XilinxVivadoToolchain:
78 attr_translate = {
79 "keep": ("dont_touch", "true"),
80 "no_retiming": ("dont_touch", "true"),
81 "async_reg": ("async_reg", "true"),
82 "mr_ff": ("mr_ff", "true"), # user-defined attribute
83 "ars_ff1": ("ars_ff1", "true"), # user-defined attribute
84 "ars_ff2": ("ars_ff2", "true"), # user-defined attribute
85 "no_shreg_extract": None
86 }
87
88 def __init__(self):
89 self.bitstream_commands = []
90 self.additional_commands = []
91 self.pre_synthesis_commands = []
92 self.with_phys_opt = False
93 self.clocks = dict()
94 self.false_paths = set()
95
96 def _build_batch(self, platform, sources, edifs, build_name):
97 tcl = []
98 tcl.append("create_project -force -name {} -part {}".format(build_name, platform.device))
99 for filename, language, library in sources:
100 filename_tcl = "{" + filename + "}"
101 tcl.append("add_files " + filename_tcl)
102 tcl.append("set_property library {} [get_files {}]"
103 .format(library, filename_tcl))
104 for filename in edifs:
105 filename_tcl = "{" + filename + "}"
106 tcl.append("read_edif " + filename_tcl)
107 tcl.append("read_xdc {}.xdc".format(build_name))
108 tcl.extend(c.format(build_name=build_name) for c in self.pre_synthesis_commands)
109 # "-include_dirs {}" crashes Vivado 2016.4
110 if platform.verilog_include_paths:
111 tcl.append("synth_design -top {} -part {} -include_dirs {{{}}}".format(build_name, platform.device, " ".join(platform.verilog_include_paths)))
112 else:
113 tcl.append("synth_design -top {} -part {}".format(build_name, platform.device))
114 tcl.append("report_timing_summary -file {}_timing_synth.rpt".format(build_name))
115 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_synth.rpt".format(build_name))
116 tcl.append("report_utilization -file {}_utilization_synth.rpt".format(build_name))
117 tcl.append("opt_design")
118 tcl.append("place_design")
119 if self.with_phys_opt:
120 tcl.append("phys_opt_design -directive AddRetime")
121 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_place.rpt".format(build_name))
122 tcl.append("report_utilization -file {}_utilization_place.rpt".format(build_name))
123 tcl.append("report_io -file {}_io.rpt".format(build_name))
124 tcl.append("report_control_sets -verbose -file {}_control_sets.rpt".format(build_name))
125 tcl.append("report_clock_utilization -file {}_clock_utilization.rpt".format(build_name))
126 tcl.append("route_design")
127 tcl.append("write_checkpoint -force {}_route.dcp".format(build_name))
128 tcl.append("report_route_status -file {}_route_status.rpt".format(build_name))
129 tcl.append("report_drc -file {}_drc.rpt".format(build_name))
130 tcl.append("report_timing_summary -datasheet -max_paths 10 -file {}_timing.rpt".format(build_name))
131 tcl.append("report_power -file {}_power.rpt".format(build_name))
132 for bitstream_command in self.bitstream_commands:
133 tcl.append(bitstream_command.format(build_name=build_name))
134 tcl.append("write_bitstream -force {}.bit ".format(build_name))
135 for additional_command in self.additional_commands:
136 tcl.append(additional_command.format(build_name=build_name))
137 tcl.append("quit")
138 tools.write_to_file(build_name + ".tcl", "\n".join(tcl))
139
140 def _convert_clocks(self, platform):
141 for clk, period in sorted(self.clocks.items(), key=lambda x: x[0].duid):
142 platform.add_platform_command(
143 "create_clock -name {clk} -period " + str(period) +
144 " [get_nets {clk}]", clk=clk)
145 for from_, to in sorted(self.false_paths,
146 key=lambda x: (x[0].duid, x[1].duid)):
147 platform.add_platform_command(
148 "set_clock_groups "
149 "-group [get_clocks -include_generated_clocks -of [get_nets {from_}]] "
150 "-group [get_clocks -include_generated_clocks -of [get_nets {to}]] "
151 "-asynchronous",
152 from_=from_, to=to)
153
154 # make sure add_*_constraint cannot be used again
155 del self.clocks
156 del self.false_paths
157
158 def _constrain(self, platform):
159 # The asynchronous input to a MultiReg is a false path
160 platform.add_platform_command(
161 "set_false_path -quiet "
162 "-to [get_nets -filter {{mr_ff == TRUE}}]"
163 )
164 # The asychronous reset input to the AsyncResetSynchronizer is a false
165 # path
166 platform.add_platform_command(
167 "set_false_path -quiet "
168 "-to [get_pins -filter {{REF_PIN_NAME == PRE}} "
169 "-of [get_cells -filter {{ars_ff1 == TRUE || ars_ff2 == TRUE}}]]"
170 )
171 # clock_period-2ns to resolve metastability on the wire between the
172 # AsyncResetSynchronizer FFs
173 platform.add_platform_command(
174 "set_max_delay 2 -quiet "
175 "-from [get_pins -filter {{REF_PIN_NAME == Q}} "
176 "-of [get_cells -filter {{ars_ff1 == TRUE}}]] "
177 "-to [get_pins -filter {{REF_PIN_NAME == D}} "
178 "-of [get_cells -filter {{ars_ff2 == TRUE}}]]"
179 )
180
181 def build(self, platform, fragment, build_dir="build", build_name="top",
182 toolchain_path=None, source=True, run=True, **kwargs):
183 if toolchain_path is None:
184 if sys.platform == "win32":
185 toolchain_path = "C:\\Xilinx"
186 elif sys.platform == "cygwin":
187 toolchain_path = "/cygdrive/c/Xilinx"
188 else:
189 toolchain_path = "/opt/Xilinx/Vivado"
190 os.makedirs(build_dir, exist_ok=True)
191 cwd = os.getcwd()
192 os.chdir(build_dir)
193
194 if not isinstance(fragment, _Fragment):
195 fragment = fragment.get_fragment()
196 platform.finalize(fragment)
197 self._convert_clocks(platform)
198 self._constrain(platform)
199 v_output = platform.get_verilog(fragment, name=build_name, **kwargs)
200 named_sc, named_pc = platform.resolve_signals(v_output.ns)
201 v_file = build_name + ".v"
202 v_output.write(v_file)
203 sources = platform.sources | {(v_file, "verilog", "work")}
204 edifs = platform.edifs
205 self._build_batch(platform, sources, edifs, build_name)
206 tools.write_to_file(build_name + ".xdc", _build_xdc(named_sc, named_pc))
207 if run:
208 _run_vivado(build_name, toolchain_path, source)
209
210 os.chdir(cwd)
211
212 return v_output.ns
213
214 def add_period_constraint(self, platform, clk, period):
215 if clk in self.clocks:
216 raise ValueError("A period constraint already exists")
217 self.clocks[clk] = period
218
219 def add_false_path_constraint(self, platform, from_, to):
220 if (to, from_) not in self.false_paths:
221 self.false_paths.add((from_, to))