build/generic_platform: use list for sources instead of set
[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
67 # For backwards compatibility with ISE paths, also
68 # look for a version in a subdirectory named "Vivado"
69 # under the current directory.
70 paths_to_try = [vivado_path, os.path.join(vivado_path, "Vivado")]
71 for p in paths_to_try:
72 try:
73 settings = common.settings(p, ver)
74 except OSError:
75 continue
76 break
77 else:
78 raise OSError("Unable to locate Vivado directory or settings.")
79
80 build_script_contents += "source " + settings + "\n"
81 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
82 build_script_file = "build_" + build_name + ".sh"
83 tools.write_to_file(build_script_file, build_script_contents)
84 command = ["bash", build_script_file]
85 r = tools.subprocess_call_filtered(command, common.colors)
86 if r != 0:
87 raise OSError("Subprocess failed")
88
89
90 class XilinxVivadoToolchain:
91 attr_translate = {
92 "keep": ("dont_touch", "true"),
93 "no_retiming": ("dont_touch", "true"),
94 "async_reg": ("async_reg", "true"),
95 "mr_ff": ("mr_ff", "true"), # user-defined attribute
96 "ars_ff1": ("ars_ff1", "true"), # user-defined attribute
97 "ars_ff2": ("ars_ff2", "true"), # user-defined attribute
98 "no_shreg_extract": None
99 }
100
101 def __init__(self):
102 self.bitstream_commands = []
103 self.additional_commands = []
104 self.pre_synthesis_commands = []
105 self.with_phys_opt = False
106 self.clocks = dict()
107 self.false_paths = set()
108
109 def _build_batch(self, platform, sources, edifs, ips, build_name):
110 tcl = []
111 tcl.append("create_project -force -name {} -part {}".format(build_name, platform.device))
112 for filename, language, library in sources:
113 filename_tcl = "{" + filename + "}"
114 tcl.append("add_files " + filename_tcl)
115 tcl.append("set_property library {} [get_files {}]"
116 .format(library, filename_tcl))
117 for filename in edifs:
118 filename_tcl = "{" + filename + "}"
119 tcl.append("read_edif " + filename_tcl)
120
121 for filename in ips:
122 filename_tcl = "{" + filename + "}"
123 ip = os.path.splitext(os.path.basename(filename))[0]
124 tcl.append("read_ip " + filename_tcl)
125 tcl.append("upgrade_ip [get_ips {}]".format(ip))
126 tcl.append("generate_target all [get_ips {}]".format(ip))
127 tcl.append("synth_ip [get_ips {}] -force".format(ip))
128 tcl.append("get_files -all -of_objects [get_files {}]".format(filename_tcl))
129
130 tcl.append("read_xdc {}.xdc".format(build_name))
131 tcl.extend(c.format(build_name=build_name) for c in self.pre_synthesis_commands)
132 # "-include_dirs {}" crashes Vivado 2016.4
133 if platform.verilog_include_paths:
134 tcl.append("synth_design -top {} -part {} -include_dirs {{{}}}".format(build_name, platform.device, " ".join(platform.verilog_include_paths)))
135 else:
136 tcl.append("synth_design -top {} -part {}".format(build_name, platform.device))
137 tcl.append("report_timing_summary -file {}_timing_synth.rpt".format(build_name))
138 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_synth.rpt".format(build_name))
139 tcl.append("report_utilization -file {}_utilization_synth.rpt".format(build_name))
140 tcl.append("opt_design")
141 tcl.append("place_design")
142 if self.with_phys_opt:
143 tcl.append("phys_opt_design -directive AddRetime")
144 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_place.rpt".format(build_name))
145 tcl.append("report_utilization -file {}_utilization_place.rpt".format(build_name))
146 tcl.append("report_io -file {}_io.rpt".format(build_name))
147 tcl.append("report_control_sets -verbose -file {}_control_sets.rpt".format(build_name))
148 tcl.append("report_clock_utilization -file {}_clock_utilization.rpt".format(build_name))
149 tcl.append("route_design")
150 tcl.append("write_checkpoint -force {}_route.dcp".format(build_name))
151 tcl.append("report_route_status -file {}_route_status.rpt".format(build_name))
152 tcl.append("report_drc -file {}_drc.rpt".format(build_name))
153 tcl.append("report_timing_summary -datasheet -max_paths 10 -file {}_timing.rpt".format(build_name))
154 tcl.append("report_power -file {}_power.rpt".format(build_name))
155 for bitstream_command in self.bitstream_commands:
156 tcl.append(bitstream_command.format(build_name=build_name))
157 tcl.append("write_bitstream -force {}.bit ".format(build_name))
158 for additional_command in self.additional_commands:
159 tcl.append(additional_command.format(build_name=build_name))
160 tcl.append("quit")
161 tools.write_to_file(build_name + ".tcl", "\n".join(tcl))
162
163 def _convert_clocks(self, platform):
164 for clk, period in sorted(self.clocks.items(), key=lambda x: x[0].duid):
165 platform.add_platform_command(
166 "create_clock -name {clk} -period " + str(period) +
167 " [get_nets {clk}]", clk=clk)
168 for from_, to in sorted(self.false_paths,
169 key=lambda x: (x[0].duid, x[1].duid)):
170 platform.add_platform_command(
171 "set_clock_groups "
172 "-group [get_clocks -include_generated_clocks -of [get_nets {from_}]] "
173 "-group [get_clocks -include_generated_clocks -of [get_nets {to}]] "
174 "-asynchronous",
175 from_=from_, to=to)
176
177 # make sure add_*_constraint cannot be used again
178 del self.clocks
179 del self.false_paths
180
181 def _constrain(self, platform):
182 # The asynchronous input to a MultiReg is a false path
183 platform.add_platform_command(
184 "set_false_path -quiet "
185 "-to [get_nets -filter {{mr_ff == TRUE}}]"
186 )
187 # The asychronous reset input to the AsyncResetSynchronizer is a false
188 # path
189 platform.add_platform_command(
190 "set_false_path -quiet "
191 "-to [get_pins -filter {{REF_PIN_NAME == PRE}} "
192 "-of [get_cells -filter {{ars_ff1 == TRUE || ars_ff2 == TRUE}}]]"
193 )
194 # clock_period-2ns to resolve metastability on the wire between the
195 # AsyncResetSynchronizer FFs
196 platform.add_platform_command(
197 "set_max_delay 2 -quiet "
198 "-from [get_pins -filter {{REF_PIN_NAME == Q}} "
199 "-of [get_cells -filter {{ars_ff1 == TRUE}}]] "
200 "-to [get_pins -filter {{REF_PIN_NAME == D}} "
201 "-of [get_cells -filter {{ars_ff2 == TRUE}}]]"
202 )
203
204 def build(self, platform, fragment, build_dir="build", build_name="top",
205 toolchain_path=None, source=True, run=True, **kwargs):
206 if toolchain_path is None:
207 if sys.platform == "win32":
208 toolchain_path = "C:\\Xilinx\\Vivado"
209 elif sys.platform == "cygwin":
210 toolchain_path = "/cygdrive/c/Xilinx/Vivado"
211 else:
212 toolchain_path = "/opt/Xilinx/Vivado"
213 os.makedirs(build_dir, exist_ok=True)
214 cwd = os.getcwd()
215 os.chdir(build_dir)
216
217 if not isinstance(fragment, _Fragment):
218 fragment = fragment.get_fragment()
219 platform.finalize(fragment)
220 self._convert_clocks(platform)
221 self._constrain(platform)
222 v_output = platform.get_verilog(fragment, name=build_name, **kwargs)
223 named_sc, named_pc = platform.resolve_signals(v_output.ns)
224 v_file = build_name + ".v"
225 v_output.write(v_file)
226 sources = platform.sources + [(v_file, "verilog", "work")]
227 edifs = platform.edifs
228 ips = platform.ips
229 self._build_batch(platform, sources, edifs, ips, build_name)
230 tools.write_to_file(build_name + ".xdc", _build_xdc(named_sc, named_pc))
231 if run:
232 _run_vivado(build_name, toolchain_path, source)
233
234 os.chdir(cwd)
235
236 return v_output.ns
237
238 def add_period_constraint(self, platform, clk, period):
239 if clk in self.clocks:
240 raise ValueError("A period constraint already exists")
241 self.clocks[clk] = period
242
243 def add_false_path_constraint(self, platform, from_, to):
244 if (to, from_) not in self.false_paths:
245 self.false_paths.add((from_, to))