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