Hog v10.58.0
hog.tcl
Go to the documentation of this file.
1 # Copyright 2018-2026 The University of Birmingham
2 # Copyright 2018-2026 Max-Planck-Institute for Physics
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 ## @file hog.tcl
17 
18 if {![info exists tcl_path]} {
19  set tcl_path [file normalize "[file dirname [info script]]"]
20 }
21 
22 set hog_path [file normalize "[file dirname [info script]]"]
23 
24 source "$hog_path/utils/Logger.tcl"
25 
26 
27 #### GLOBAL CONSTANTS
28 set CI_STAGES {"generate_project" "simulate_project"}
29 set CI_PROPS {"-synth_only"}
30 
31 #### FUNCTIONS
32 
33 ## @brief Add a new file to a fileset in Vivado
34 #
35 # @param[in] file The name of the file to add. NOTE: directories are not supported.
36 # @param[in] fileset The fileset name
37 #
38 proc AddFile {file fileset} {
39  if {[IsXilinx]} {
40  add_files -norecurse -fileset $fileset $file
41  }
42 }
43 
44 ## @brief Add libraries, properties and filesets to the project
45 #
46 # @param[in] libraries has library name as keys and a list of filenames as values
47 # @param[in] properties has as file names as keys and a list of properties as values
48 # @param[in] filesets has fileset name as keys and a list of libraries as values
49 #
50 proc AddHogFiles {libraries properties filesets} {
51  Msg Info "Adding source files to project..."
52  Msg Debug "Filesets: $filesets"
53  Msg Debug "Libraries: $libraries"
54  Msg Debug "Properties: $properties"
55 
56  if {[IsLibero]} {
57  set synth_conf_command "organize_tool_files -tool {SYNTHESIZE} -input_type {constraint}"
58  set synth_conf 0
59  set timing_conf_command "organize_tool_files -tool {VERIFYTIMING} -input_type {constraint}"
60  set timing_conf 0
61  set place_conf_command "organize_tool_files -tool {PLACEROUTE} -input_type {constraint}"
62  set place_conf 0
63  }
64 
65  # Vitis: the workspace apps do not change while files are added, and querying
66  # them opens and locks the workspace, so get them once for all the filesets.
67  # Only the vitis_only pass adds files to the apps: while Vivado is adding the
68  # HDL sources the workspace is still empty, so do not even open it
69  set ws_apps ""
70  if {![IsVivado] || ([info exists globalSettings::vitis_only_pass] && $globalSettings::vitis_only_pass == 1)} {
71  if {[IsVitisClassic]} {
72  set ws_apps [GetVitisApps]
73  } elseif {[IsVitisUnified]} {
74  set ws_apps [GetVitisApps "$globalSettings::build_dir/vitis_unified" \
75  "$globalSettings::repo_path/Hog/Other/Python/VitisUnified/AppCommands.py"]
76  }
77  }
78 
79  foreach fileset [dict keys $filesets] {
80  Msg Debug "Fileset: $fileset"
81  # Create fileset if it doesn't exist yet
82  if {[IsVivado]} {
83  if {[string equal [get_filesets -quiet $fileset] ""]} {
84  # Simulation list files supported only by Vivado
85  create_fileset -simset $fileset
86  # Set active when creating, by default it will be the latest simset to be created,
87  # unless is specified in the sim.conf
88  current_fileset -simset [get_filesets $fileset]
89  set simulation [get_filesets $fileset]
90  foreach simulator [GetSimulators] {
91  set_property -name {$simulator.compile.vhdl_syntax} -value {2008} -objects $simulation
92  }
93  set_property SOURCE_SET sources_1 $simulation
94  }
95  }
96  # Check if ips.src is in $fileset
97  set libs_in_fileset [DictGet $filesets $fileset]
98  if {[IsInList "ips.src" $libs_in_fileset]} {
99  set libs_in_fileset [MoveElementToEnd $libs_in_fileset "ips.src"]
100  }
101 
102  # Vitis: Check if defined apps have a corresponding source file
103  if {$ws_apps ne ""} {
104  dict for {app_name app_config} $ws_apps {
105  set app_lib [string tolower "app_$app_name\.src"]
106  if {![IsInList $app_lib $libs_in_fileset 0 1]} {
107  Msg Warning "App '$app_name' exists in workspace but no corresponding sourcefile '$app_lib' found. \
108  Make sure you have a list file with the correct naming convention: \[app_<app_name>\.src\]"
109  }
110  }
111  }
112 
113  # For Vitis Unified, create app_files_dict once before processing libraries
114  # This allows us to collect files from all libraries before importing
115  if {[IsVitisUnified]} {
116  set app_files_dict [dict create]
117  }
118 
119  # Loop over libraries in fileset
120  set reapply_targets [dict create]
121  foreach lib $libs_in_fileset {
122  Msg Debug "lib: $lib \n"
123  set lib_files [DictGet $libraries $lib]
124  Msg Debug "Files in $lib: $lib_files"
125  set rootlib [file rootname [file tail $lib]]
126  set ext [file extension $lib]
127  Msg Debug "lib: $lib ext: $ext fileset: $fileset"
128  # ADD NOW LISTS TO VIVADO PROJECT
129  if {[IsXilinx] && !([info exists globalSettings::vitis_only_pass] && $globalSettings::vitis_only_pass == 1)} {
130  # Skip Vitis application libraries
131  if {[string match "app_*" [string tolower $lib]]} {
132  continue
133  }
134  Msg Debug "Adding $lib to $fileset"
135  add_files -norecurse -fileset $fileset $lib_files
136  # Add Properties
137  foreach f $lib_files {
138  set file_obj [get_files -of_objects [get_filesets $fileset] [list "*$f"]]
139  #ADDING LIBRARY
140  if {[file extension $f] == ".vhd" || [file extension $f] == ".vhdl"} {
141  set_property -name "library" -value $rootlib -objects $file_obj
142  }
143 
144  # ADDING FILE PROPERTIES
145  set props [DictGet $properties $f]
146  if {[file extension $f] == ".vhd" || [file extension $f] == ".vhdl"} {
147  # VHDL 93 property
148  if {[lsearch -inline -regexp $props "93"] < 0} {
149  # ISE does not support vhdl2008
150  if {[IsVivado]} {
151  if {[lsearch -inline -regexp $props "2008"] >= 0} {
152  set vhdl_year "VHDL 2008"
153  } elseif {[lsearch -inline -regexp $props "2019"] >= 0} {
154  if {[GetIDEVersion] >= 2023.2} {
155  set vhdl_year "VHDL 2019"
156  } else {
157  Msg CriticalWarning "VHDL 2019 is not supported\
158  in Vivado version older than 2023.2.\
159  Using VHDL 2008, but this might not work."
160  set vhdl_year "VHDL 2008"
161  }
162  } else {
163  # The default VHDL year is 2008
164  set vhdl_year "VHDL 2008"
165  }
166  Msg Debug "File type for $f is $vhdl_year"
167  set_property -name "file_type" -value $vhdl_year -objects $file_obj
168  }
169  } else {
170  Msg Debug "Filetype is VHDL 93 for $f"
171  }
172  }
173 
174  # SystemVerilog property
175  if {[lsearch -inline -regexp $props "SystemVerilog"] > 0} {
176  # ISE does not support SystemVerilog
177  if {[IsVivado]} {
178  set_property -name "file_type" -value "SystemVerilog" -objects $file_obj
179  Msg Debug "Filetype is SystemVerilog for $f"
180  } else {
181  Msg Warning "Xilinx PlanAhead/ISE does not support SystemVerilog.\
182  Property not set for $f"
183  }
184  }
185 
186  # Top synthesis module
187  set top [lindex [regexp -inline {\ytop\s*=\s*(.+?)\y.*} $props] 1]
188  if {$top != ""} {
189  Msg Info "Setting $top as top module for file set $fileset..."
190  set globalSettings::synth_top_module $top
191  }
192 
193  # Verilog headers
194  if {[lsearch -inline -regexp $props "verilog_header"] >= 0} {
195  Msg Debug "Setting verilog header type for $f..."
196  set_property file_type {Verilog Header} [get_files $f]
197  } elseif {[lsearch -inline -regexp $props "verilog_template"] >= 0} {
198  # Verilog Template
199  Msg Debug "Setting verilog template type for $f..."
200  set_property file_type {Verilog Template} [get_files $f]
201  } elseif {[lsearch -inline -regexp $props "verilog"] >= 0} {
202  # Normal Verilog
203  Msg Debug "Setting verilog type for $f..."
204  set_property file_type {Verilog} [get_files $f]
205  }
206 
207  # Not used in synthesis
208  if {[lsearch -inline -regexp $props "nosynth"] >= 0} {
209  Msg Debug "Setting not used in synthesis for $f..."
210  set_property -name "used_in_synthesis" -value "false" -objects $file_obj
211  }
212 
213  # Not used in implementation
214  if {[lsearch -inline -regexp $props "noimpl"] >= 0} {
215  Msg Debug "Setting not used in implementation for $f..."
216  set_property -name "used_in_implementation" -value "false" -objects $file_obj
217  }
218 
219  # Not used in simulation
220  if {[lsearch -inline -regexp $props "nosim"] >= 0} {
221  Msg Debug "Setting not used in simulation for $f..."
222  set_property -name "used_in_simulation" -value "false" -objects $file_obj
223  }
224 
225  ## Simulation properties
226  # Top simulation module
227  set top_sim [lindex [regexp -inline {\ytopsim\s*=\s*(.+?)\y.*} $props] 1]
228  if {$top_sim != ""} {
229  Msg Warning "Setting the simulation top module with the topsim property is deprecated.\
230  Please set this property in the \[properties\] section of your .sim list file,
231  or in the \[$fileset\] section of your sim.conf,\
232  by adding the following line.\ntop=$top_sim"
233  }
234 
235  # Simulation runtime
236  set sim_runtime [lindex [regexp -inline {\yruntime\s*=\s*(.+?)\y.*} $props] 1]
237  if {$sim_runtime != ""} {
238  Msg Warning "Setting the simulation runtime using the runtime= property is deprecated.\
239  Please set this property in the \[properties\] section of your .sim list file,\
240  or in the \[$fileset\] section of your sim.conf,\
241  by adding the following line.\n<simulator_name>.simulate.runtime=$sim_runtime"
242  }
243 
244  # Wave do file
245  if {[lsearch -inline -regexp $props "wavefile"] >= 0} {
246  Msg Warning "Setting a wave do file using the wavefile property is deprecated.\
247  Set this property in the sim.conf file under the \[$fileset\] section,\
248  or in the \[properties\] section of the .sim list file,\
249  by adding the following line .\n<simulator_name>.simulate.custom_wave_do=[file tail $f]"
250  }
251 
252  # Do file
253  if {[lsearch -inline -regexp $props "dofile"] >= 0} {
254  Msg Warning "Setting a wave do file using the dofile property is deprecated.\
255  Set this property in the sim.conf file under the \[$fileset\] section,\
256  or in the \[properties\] section of the .sim list file,\
257  by adding the following line .\n<simulator_name>.simulate.custom_do=[file tail $f]"
258  }
259 
260  # Lock the IP
261  if {[lsearch -inline -regexp $props "locked"] >= 0 && $ext == ".ip"} {
262  Msg Info "Locking IP $f..."
263  set_property IS_MANAGED 0 [get_files $f]
264  }
265 
266  # Generating Target for BD File
267  if {[file extension $f] == ".bd"} {
268  Msg Info "Generating Target for [file tail $f],\
269  please remember to commit the (possible) changed file."
270  generate_target all [get_files $f]
271 
272  # If elf is saved in the bd, vivado appends to the props instead of setting
273  dict for {fo pd} $reapply_targets {
274  set ref [dict get $pd ref]
275  set cell [dict get $pd cell]
276  Msg Debug "Reapplying ref: $ref and cell:$cell to $fo"
277  set_property SCOPED_TO_REF $ref $fo
278  set_property SCOPED_TO_CELLS [split $cell ","] $fo
279  }
280  }
281 
282  # Tcl
283  if {[file extension $f] == ".tcl" && $ext != ".con"} {
284  if {[lsearch -inline -regexp $props "source"] >= 0} {
285  Msg Info "Sourcing Tcl script $f,\
286  and setting it not used in synthesis, implementation and simulation..."
287  source $f
288  set_property -name "used_in_synthesis" -value "false" -objects $file_obj
289  set_property -name "used_in_implementation" -value "false" -objects $file_obj
290  set_property -name "used_in_simulation" -value "false" -objects $file_obj
291  }
292  }
293 
294  # Constraint Properties
295  set ref [lindex [regexp -inline {\yscoped_to_ref\s*=\s*([^ ]+)} $props] 1]
296  set cell [lindex [regexp -inline {\yscoped_to_cells\s*=\s*([^ ]+)} $props] 1]
297  if {[file extension $f] == ".elf" || (([file extension $f] == ".tcl" || [file extension $f] == ".xdc") && $ext == ".con")} {
298  if {[file extension $f] == ".elf"} {dict set reapply_targets $file_obj [dict create ref $ref cell $cell]}
299  if {$ref != ""} {
300  set_property SCOPED_TO_REF $ref $file_obj
301  }
302  if {$cell != ""} {
303  set_property SCOPED_TO_CELLS [split $cell ","] $file_obj
304  }
305  }
306  }
307  Msg Info "[llength $lib_files] file/s added to library $rootlib..."
308  } elseif {[IsQuartus]} {
309  #QUARTUS ONLY
310  if {$ext == ".sim"} {
311  Msg Warning "Simulation files not supported in Quartus Prime mode... Skipping $lib"
312  } else {
313  if {![is_project_open]} {
314  Msg Error "Project is closed"
315  }
316  foreach cur_file $lib_files {
317  set file_type [FindFileType $cur_file]
318 
319  #ADDING FILE PROPERTIES
320  set props [DictGet $properties $cur_file]
321 
322  # Top synthesis module
323  set top [lindex [regexp -inline {\ytop\s*=\s*(.+?)\y.*} $props] 1]
324  if {$top != ""} {
325  Msg Info "Setting $top as top module for file set $fileset..."
326  set globalSettings::synth_top_module $top
327  }
328  # VHDL file properties
329  if {[string first "VHDL" $file_type] != -1} {
330  if {[string first "1987" $props] != -1} {
331  set hdl_version "VHDL_1987"
332  } elseif {[string first "1993" $props] != -1} {
333  set hdl_version "VHDL_1993"
334  } elseif {[string first "2008" $props] != -1} {
335  set hdl_version "VHDL_2008"
336  } else {
337  set hdl_version "default"
338  }
339  if {$hdl_version == "default"} {
340  set_global_assignment -name $file_type $cur_file -library $rootlib
341  } else {
342  set_global_assignment -name $file_type $cur_file -hdl_version $hdl_version -library $rootlib
343  }
344  } elseif {[string first "SYSTEMVERILOG" $file_type] != -1} {
345  # SystemVerilog file properties
346  if {[string first "2005" $props] != -1} {
347  set hdl_version "systemverilog_2005"
348  } elseif {[string first "2009" $props] != -1} {
349  set hdl_version "systemverilog_2009"
350  } else {
351  set hdl_version "default"
352  }
353  if {$hdl_version == "default"} {
354  set_global_assignment -name $file_type $cur_file
355  } else {
356  set_global_assignment -name $file_type $cur_file -hdl_version $hdl_version
357  }
358  } elseif {[string first "VERILOG" $file_type] != -1} {
359  # Verilog file properties
360  if {[string first "1995" $props] != -1} {
361  set hdl_version "verilog_1995"
362  } elseif {[string first "2001" $props] != -1} {
363  set hdl_version "verilog_2001"
364  } else {
365  set hdl_version "default"
366  }
367  if {$hdl_version == "default"} {
368  set_global_assignment -name $file_type $cur_file
369  } else {
370  set_global_assignment -name $file_type $cur_file -hdl_version $hdl_version
371  }
372  } elseif {[string first "SOURCE" $file_type] != -1 || [string first "COMMAND_MACRO" $file_type] != -1} {
373  set_global_assignment -name $file_type $cur_file
374  if {$ext == ".con"} {
375  source $cur_file
376  } elseif {$ext == ".src"} {
377  # If this is a Platform Designer file then generate the system
378  if {[string first "qsys" $props] != -1} {
379  # remove qsys from options since we used it
380  set emptyString ""
381  regsub -all {\{||qsys||\}} $props $emptyString props
382 
383  set qsysPath [file dirname $cur_file]
384  set qsysName "[file rootname [file tail $cur_file]].qsys"
385  set qsysFile "$qsysPath/$qsysName"
386  set qsysLogFile "$qsysPath/[file rootname [file tail $cur_file]].qsys-script.log"
387 
388  set qsys_rootdir ""
389  if {![info exists ::env(QSYS_ROOTDIR)]} {
390  if {[info exists ::env(QUARTUS_ROOTDIR)]} {
391  set qsys_rootdir "$::env(QUARTUS_ROOTDIR)/sopc_builder/bin"
392  Msg Warning "The QSYS_ROOTDIR environment variable is not set! I will use $qsys_rootdir"
393  } else {
394  Msg CriticalWarning "The QUARTUS_ROOTDIR environment variable is not set! Assuming all quartus executables are contained in your PATH!"
395  }
396  } else {
397  set qsys_rootdir $::env(QSYS_ROOTDIR)
398  }
399 
400  set cmd "$qsys_rootdir/qsys-script"
401  set cmd_options " --script=$cur_file"
402  if {![catch {"exec $cmd -version"}] || [lindex $::errorCode 0] eq "NONE"} {
403  Msg Info "Executing: $cmd $cmd_options"
404  Msg Info "Saving logfile in: $qsysLogFile"
405  if {[catch {eval exec -ignorestderr "$cmd $cmd_options >>& $qsysLogFile"} ret opt]} {
406  set makeRet [lindex [dict get $opt -errorcode] end]
407  Msg CriticalWarning "$cmd returned with $makeRet"
408  }
409  } else {
410  Msg Error " Could not execute command $cmd"
411  exit 1
412  }
413  # Check the system is generated correctly and move file to correct directory
414  if {[file exists $qsysName] != 0} {
415  file rename -force $qsysName $qsysFile
416  # Write checksum to file
417  set qsysMd5Sum [Md5Sum $qsysFile]
418  # open file for writing
419  set fileDir [file normalize "./hogTmp"]
420  set fileName "$fileDir/.hogQsys.md5"
421  if {![file exists $fileDir]} {
422  file mkdir $fileDir
423  }
424  set hogQsysFile [open $fileName "a"]
425  set fileEntry "$qsysFile\t$qsysMd5Sum"
426  puts $hogQsysFile $fileEntry
427  close $hogQsysFile
428  } else {
429  Msg ERROR "Error while moving the generated qsys file to final location: $qsysName not found!"
430  }
431  if {[file exists $qsysFile] != 0} {
432  if {[string first "noadd" $props] == -1} {
433  set qsysFileType [FindFileType $qsysFile]
434  set_global_assignment -name $qsysFileType $qsysFile
435  } else {
436  regsub -all {noadd} $props $emptyString props
437  }
438  if {[string first "nogenerate" $props] == -1} {
439  GenerateQsysSystem $qsysFile $props
440  }
441  } else {
442  Msg ERROR "Error while generating ip variations from qsys: $qsysFile not found!"
443  }
444  }
445  }
446  } elseif {[string first "QSYS" $file_type] != -1} {
447  set emptyString ""
448  regsub -all {\{||\}} $props $emptyString props
449  if {[string first "noadd" $props] == -1} {
450  set_global_assignment -name $file_type $cur_file
451  } else {
452  regsub -all {noadd} $props $emptyString props
453  }
454 
455  #Generate IPs
456  if {[string first "nogenerate" $props] == -1} {
457  GenerateQsysSystem $cur_file $props
458  }
459  } else {
460  set_global_assignment -name $file_type $cur_file -library $rootlib
461  }
462  }
463  }
464  } elseif {[IsLibero]} {
465  if {$ext == ".con"} {
466  set vld_exts {.sdc .pin .dcf .gcf .pdc .ndc .fdc .crt .vcd }
467  foreach con_file $lib_files {
468  # Check for valid constrain files
469  set con_ext [file extension $con_file]
470  if {[IsInList [file extension $con_file] $vld_exts]} {
471  set option [string map {. -} $con_ext]
472  set option [string map {fdc net_fdc} $option]
473  set option [string map {pdc io_pdc} $option]
474  create_links -convert_EDN_to_HDL 0 -library {work} $option $con_file
475 
476  set props [DictGet $properties $con_file]
477 
478  if {$con_ext == ".sdc"} {
479  if {[lsearch $props "notiming"] >= 0} {
480  Msg Info "Excluding $con_file from timing verification..."
481  } else {
482  Msg Info "Adding $con_file to time verification"
483  append timing_conf_command " -file $con_file"
484  set timing_conf 1
485  }
486 
487  if {[lsearch $props "nosynth"] >= 0} {
488  Msg Info "Excluding $con_file from synthesis..."
489  } else {
490  Msg Info "Adding $con_file to synthesis"
491  append synth_conf_command " -file $con_file"
492  set synth_conf 1
493  }
494  }
495 
496  if {$con_ext == ".pdc" || $con_ext == ".sdc"} {
497  if {[lsearch $props "noplace"] >= 0} {
498  Msg Info "Excluding $con_file from place and route..."
499  } else {
500  Msg Info "Adding $con_file to place and route"
501  append place_conf_command " -file $con_file"
502  set place_conf 1
503  }
504  }
505  } else {
506  Msg CriticalWarning "Constraint file $con_file does not have a valid extension. Allowed extensions are: \n $vld_exts"
507  }
508  }
509  } elseif {$ext == ".src"} {
510  foreach f $lib_files {
511  Msg Debug "Adding source $f to library $rootlib..."
512  create_links -library $rootlib -hdl_source $f
513  }
514  } elseif {$ext == ".sim"} {
515  Msg Debug "Adding stimulus file $f to library..."
516  create_links -library $rootlib -stimulus $f
517  }
518  build_design_hierarchy
519  foreach cur_file $lib_files {
520  set file_type [FindFileType $cur_file]
521 
522  # ADDING FILE PROPERTIES
523  set props [DictGet $properties $cur_file]
524 
525  # Top synthesis module
526  set top [lindex [regexp -inline {\ytop\s*=\s*(.+?)\y.*} $props] 1]
527  if {$top != ""} {
528  Msg Info "Setting $top as top module for file set $rootlib..."
529  set globalSettings::synth_top_module "${top}::$rootlib"
530  }
531  }
532  # Closing IDE if cascade
533  } elseif {[IsDiamond]} {
534  if {$ext == ".src" || $ext == ".con" || $ext == ".ext"} {
535  foreach f $lib_files {
536  Msg Debug "Diamond: adding source file $f to library $rootlib..."
537  prj_src add -work $rootlib $f
538  set props [DictGet $properties $f]
539  # Top synthesis module
540  set top [lindex [regexp -inline {\ytop\s*=\s*(.+?)\y.*} $props] 1]
541  if {$top != ""} {
542  Msg Info "Setting $top as top module for the project..."
543  set globalSettings::synth_top_module $top
544  }
545 
546  # Active LPF property
547  if {[lsearch -inline -regexp $props "enable"] >= 0} {
548  Msg Debug "Setting $f as active Logic Preference file"
549  prj_src enable $f
550  }
551  }
552  } elseif {$ext == ".sim"} {
553  foreach f $lib_files {
554  Msg Debug "Diamond Adding simulation file $f to library $rootlib..."
555  prj_src add -work $rootlib -simulate_only $f
556  }
557  }
558  } elseif {[IsVitisClassic] || [IsVitisUnified]} {
559  if {[IsVitisClassic]} {
560  # Vitis Classic: import files one by one
561  foreach app_name [dict keys $ws_apps] {
562  foreach f $lib_files {
563  if {[string tolower $rootlib] != [string tolower "app_$app_name"]} {
564  continue
565  }
566 
567  Msg Info "Adding source file $f from lib: $lib to vitis app \[$app_name\]..."
568  set proj_f_path [regsub "^$globalSettings::repo_path" $f ""]
569  set proj_f_path [regsub "[file tail $f]$" $proj_f_path ""]
570  Msg Debug "Project_f_path is $proj_f_path"
571 
572  importsources -name $app_name -soft-link -path $f -target $proj_f_path
573  }
574  }
575  } elseif {[IsVitisUnified]} {
576  Msg Debug "Vitis Unified: Collecting files for apps from library $rootlib..."
577  # For Vitis Unified, collect files per app from all libraries
578  # Files will be imported after all libraries are processed
579 
580  if {[dict size $ws_apps] == 0} {
581  Msg Debug "No apps found in workspace, skipping file collection"
582  } else {
583  Msg Debug "Found [dict size $ws_apps] app(s) in workspace"
584  Msg Debug "Processing library: $rootlib with [llength $lib_files] file(s)"
585  foreach app_name [dict keys $ws_apps] {
586  set expected_lib [string tolower "app_$app_name"]
587  Msg Debug "Checking files for app: $app_name (looking for lib: $expected_lib, current lib: [string tolower $rootlib])"
588  foreach f $lib_files {
589  if {[string tolower $rootlib] != $expected_lib} {
590  continue
591  }
592  Msg Debug "File $f matches app $app_name"
593  set proj_f_path [regsub "^$globalSettings::repo_path" $f ""]
594  set proj_f_path [regsub "[file tail $f]$" $proj_f_path ""]
595  set proj_f_path [string trimleft $proj_f_path "/"]
596  # Store file info for this app
597  if {![dict exists $app_files_dict $app_name]} {
598  dict set app_files_dict $app_name files [list]
599  dict set app_files_dict $app_name target $proj_f_path
600  Msg Debug "Initialized app_files_dict for $app_name with target: $proj_f_path"
601  }
602  # Get current files list, append new file, and set it back
603  set current_files [dict get $app_files_dict $app_name files]
604  lappend current_files $f
605  dict set app_files_dict $app_name files $current_files
606  set current_count [llength [dict get $app_files_dict $app_name files]]
607  Msg Debug "Added file $f to app_files_dict for $app_name, current count: $current_count"
608  }
609  }
610  }
611  }
612  }
613  }
614 
615  # For Vitis Unified, import all collected files after processing all libraries
616  if {[IsVitisUnified] && [dict size $app_files_dict] > 0} {
617  set python_script "$globalSettings::repo_path/Hog/Other/Python/VitisUnified/AppCommands.py"
618  set vitis_workspace "$globalSettings::build_dir/vitis_unified"
619 
620  # Get Vitis version and set as environment variable for Python script
621  set vitis_version [GetIDEVersion]
622  set ::env(HOG_VITIS_VER) $vitis_version
623  Msg Debug "Vitis version: $vitis_version (set in HOG_VITIS_VER environment variable)"
624 
625  dict for {app_name app_data} $app_files_dict {
626  set files_list [dict get $app_data files]
627  set target_path [dict get $app_data target]
628 
629  if {[llength $files_list] > 0} {
630  Msg Info "Adding [llength $files_list] source file(s) to vitis app \[$app_name\]..."
631  Msg Debug "Files: $files_list"
632  Msg Debug "Target path: $target_path"
633 
634  # Convert Tcl list to JSON array for Python
635  set files_json "\["
636  set first 1
637  foreach f $files_list {
638  if {!$first} {
639  append files_json ", "
640  }
641  # Escape backslashes and quotes in file paths
642  set escaped_f [string map {\\ \\\\ \" \\\"} $f]
643  append files_json "\"$escaped_f\""
644  set first 0
645  }
646  append files_json "\]"
647 
648  Msg Debug "JSON string: $files_json"
649 
650  # The file list contains spaces: pass it in the environment, as a command
651  # line argument it would be split by the Windows shell that runs vitis.bat
652  set ::env(HOG_VITIS_APP_FILES) $files_json
653  set error_msg "Failed to add files to app $app_name"
654  if {
655  ![ExecuteVitisUnifiedCommand $python_script "add_app_files" \
656  [list $app_name $vitis_workspace $target_path] \
657  $error_msg]
658  } {
659  Msg Error "Failed to add files to Vitis Unified app '$app_name'"
660  exit 1
661  }
662  } else {
663  Msg Warning "No files to add for app '$app_name'"
664  }
665  }
666  }
667  }
668 
669  if {[IsVivado]} {
670  if {[DictGet $filesets "sim_1"] == ""} {
671  delete_fileset -quiet [get_filesets -quiet "sim_1"]
672  }
673  }
674 
675  # Add constraints to workflow in Libero
676  if {[IsLibero]} {
677  if {$synth_conf == 1} {
678  Msg Info $synth_conf_command
679  eval $synth_conf_command
680  }
681  if {$timing_conf == 1} {
682  Msg Info $timing_conf_command
683  eval $timing_conf_command
684  }
685  if {$place_conf == 1} {
686  Msg Info $place_conf_command
687  eval $place_conf_command
688  }
689  }
690 }
691 
692 ## @brief Returns a dictionary for the allowed properties for each file type
693 proc ALLOWED_PROPS {} {
694  return [dict create ".vhd" [list "93" "nosynth" "noimpl" "nosim" "1987" "1993" "2008" "2019"] \
695  ".vhdl" [list "93" "nosynth" "noimpl" "nosim" "1987" "1993" "2008" "2019"] \
696  ".bd" [list "nosim"] \
697  ".v" [list "SystemVerilog" "verilog_header" "nosynth" "noimpl" "nosim" "1995" "2001"] \
698  ".sv" [list "verilog" "verilog_header" "nosynth" "noimpl" "nosim" "2005" "2009"] \
699  ".svp" [list "verilog" "verilog_header" "nosynth" "noimpl" "nosim" "2005" "2009"] \
700  ".do" [list "nosim"] \
701  ".udo" [list "nosim"] \
702  ".xci" [list "nosynth" "noimpl" "nosim" "locked"] \
703  ".xdc" [list "nosynth" "noimpl" "scoped_to_ref" "scoped_to_cells"] \
704  ".tcl" [list "nosynth" "noimpl" "nosim" "scoped_to_ref" "scoped_to_cells" "source" "qsys" "noadd" \
705  "--block-symbol-file" "--clear-output-directory" "--example-design" \
706  "--export-qsys-script" "--family" "--greybox" "--ipxact" \
707  "--jvm-max-heap-size" "--parallel" "--part" "--search-path" \
708  "--simulation" "--synthesis" "--testbench" "--testbench-simulation" \
709  "--upgrade-ip-cores" "--upgrade-variation-file"] \
710  ".qsys" [list "nogenerate" "noadd" "--block-symbol-file" "--clear-output-directory" "--example-design" \
711  "--export-qsys-script" "--family" "--greybox" "--ipxact" "--jvm-max-heap-size" "--parallel" \
712  "--part" "--search-path" "--simulation" "--synthesis" "--testbench" "--testbench-simulation" \
713  "--upgrade-ip-cores" "--upgrade-variation-file"] \
714  ".sdc" [list "notiming" "nosynth" "noplace"] \
715  ".elf" [list "scoped_to_ref" "scoped_to_cells" "nosim" "noimpl"] \
716  ".pdc" [list "nosynth" "noplace"] \
717  ".lpf" [list "enable"]]
718 }
719 
720 ## @brief # Returns the step name for the stage that produces the binary file
721 #
722 # Projects using Versal chips have a different step for producing the
723 # binary file, we use this function to take that into account
724 #
725 # @param[out] 1 if it's Versal 0 if it's not
726 # @param[in] part The FPGA part
727 #
728 proc BinaryStepName {part} {
729  if {[IsVersal $part]} {
730  return "WRITE_DEVICE_IMAGE"
731  } elseif {[IsISE]} {
732  return "Bitgen"
733  } else {
734  return "WRITE_BITSTREAM"
735  }
736 }
737 
738 ## @brief Check common environmentatl variables to run the Hog-CI
739 proc CheckCIEnv {} {
740  global env
741  set essential_vars [dict create \
742  "HOG_USER" "NOT defined. This variable is essential for git to work properly. \
743  It should be set to the username for your service account (a valid git account)." \
744  "HOG_EMAIL" "NOT defined. This variable is essential for git to work properly. It should be set to your service's account email." \
745  "HOG_PUSH_TOKEN" "NOT defined. This variable is essential for git to work properly. \
746  It should be set to a Gitlab/GitHub API token for your service account."]
747 
748  set missing_vars 0
749  dict for {var msg} $essential_vars {
750  if {![info exists env($var)]} {
751  Msg CriticalWarning "Essential environment variable $var is $msg"
752  set missing_vars 1
753  } else {
754  Msg Info "Found environment variable $var."
755  }
756  }
757 
758  set additional_vars [dict create \
759  "HOG_CHECK_YAMLREF" "NOT defined. Set this variable to '1' to make CI fail if there is not coherence between the ref and the Hog." \
760  "HOG_TARGET_BRANCH" "NOT defined. Default branch for merge is \"master\"" \
761  "HOG_CREATE_OFFICIAL_RELEASE" "NOT defined. \
762  Set this variable to '1' to make Hog create an official release in GitHub/Gitlab with the binaries generated in the CI." \
763  "HOG_USE_DOXYGEN" "NOT defined. \
764  Set this variable to 1 to make Hog-CI run Doxygen and copy the official documentation over when you merge to the official branch."]
765 
766  if {
767  ([info exists env(HOG_OFFICIAL_BIN_EOS_PATH)] && $env(HOG_OFFICIAL_BIN_EOS_PATH) ne "") ||
768  ([info exists env(HOG_OFFICIAL_BIN_PATH)] && [string match "/eos/*" $env(HOG_OFFICIAL_BIN_PATH)])
769  } {
770  Msg Info "Official binary path points to EOS. Checking EOS environment variables for uploads..."
771  if {[info exists env(HOG_OFFICIAL_BIN_PATH)]} {
772  Msg CriticalWarning "Variable HOG_OFFICIAL_BIN_EOS_PATH is defined. \
773  From Hog2026.2 this variable will be deprecated. Please, use HOG_OFFICIAL_BIN_PATH instead."
774  }
775  if {![info exists env(EOS_PASSWORD)]} {
776  if {![info exists env(HOG_PASSWORD)]} {
777  Msg Warning "Neither EOS_PASSWORD nor HOG_PASSWORD environment variable is defined. \
778  This variable is essential for Hog to be able to upload files to EOS. Please set one of them to the password for your EOS account."
779  } else {
780  Msg Info "HOG_PASSWORD environment variable is defined and will be used as password for EOS uploads. \
781  If you want to use a different password for EOS uploads, please set the EOS_PASSWORD environment variable."
782  }
783  } else {
784  Msg Info "EOS_PASSWORD environment variable is defined and will be used as password for EOS uploads."
785  }
786 
787  if {![info exists env(EOS_USER)]} {
788  Msg Info "EOS_USER environment variable is not defined. Assuming EOS username is the same as HOG_USER."
789  } else {
790  Msg Info "EOS_USER environment variable is defined and will be used as username for EOS uploads."
791  }
792 
793  if {![info exists env(EOS_MGM_URL)]} {
794  Msg Info "EOS_MGM_URL environment variable is not defined. Assuming default value of root://eosuser.cern.ch."
795  } else {
796  Msg Info "EOS_MGM_URL environment variable is defined and will be used as MGM URL for EOS uploads."
797  }
798  } elseif {[info exists env(HOG_OFFICIAL_BIN_PATH)]} {
799  Msg Info "Variable HOG_OFFICIAL_BIN_PATH is defined. Hog will copy the official binary files to the path defined in this variable. \
800  Please make sure this path is correct and has enough space to store the binaries."
801  } else {
802  Msg Info "No official binary path defined. Hog will not be able to upload binaries."
803  }
804 
805 
806  if {$missing_vars} {
807  Msg Error "One or more essential environment variables are missing. Hog-CI cannot run!"
808  exit 1
809  }
810 }
811 
812 ## brief Check environment to execute chosen project
813 # @param[in] project_name The name of the project
814 # @param[in] ide The IDE to build the chosen project
815 proc CheckEnv {project_name ide} {
816  global env
817  set has_error 0
818  set essential_commands [dict create "git" "--version" "$ide" "-version"]
819  set additional_commands [dict create \
820  "vsim" "-version" \
821  "eos" "" \
822  "kinit" "" \
823  "rclone" "--version"]
824 
825  set additional_vars [dict create \
826  "HOG_PATH" "NOT defined. Hog might work as long as all the necessary executable are in the PATH variable." \
827  "HOG_XIL_LICENSE" "NOT defined. If this variable is not set to the license servers separated by comas, \
828  you need some alternative way of getting your Xilinx license (for example a license file on the machine)." \
829  "LM_LICENSE_FILE" "NOT defined. This variable should be set the Quartus/Libero license servers separated by semicolon. \
830  If not, you need an alternative way of getting your Quartus/Libero license." \
831  "HOG_LD_LIBRARY_PATH" "NOT defined. Hog might work as long as all the necessary library are found." \
832  "HOG_SIMULATION_LIB_PATH" "NOT defined. Hog-CI will not be able to run simulations using third-party simulators." \
833  "HOG_CHECK_PROJVER" "NOT defined. Hog will NOT check the CI project version. \
834  Set this variable to '1' if you want Hog to check the CI project version before creating the HDL project in Create_Project stage. \
835  If the project has not been changed with respect to the target branch, the CI will skip this project" \
836  "HOG_CHECK_SYNTAX" "NOT defined. Hog will NOT check the syntax. \
837  Set this variable to '1' if you want Hog to check the syntax after creating the HDL project in Create_Project stage." \
838  "HOG_NO_BITSTREAM" "NOT defined. Hog-CI will run the implementation up to the write_bitstream stage and create bit files." \
839  "HOG_NO_RESET_BD" "NOT defined or not equal to 1. Hog will reset .bd files (if any) before starting synthesis." \
840  "HOG_IP_PATH" "NOT defined. Hog-CI will NOT use an EOS/LOCAL IP repository to speed up the IP synthesis." \
841  "HOG_RESET_FILES" "NOT defined. Hog-CI will NOT reset any files." \
842  "HOG_NJOBS" "NOT defined. Hog-CI will build IPs with default number of jobs (4)." \
843  "HOG_SAVE_DCP" "NOT defined. Set this variable to 1, 2 or 3 to make Hog-CI save the run checkpoint DCP files (Vivado only) in the artifacts.\nCheck the official documentation for more details. https://cern.ch/hog"]
844  Msg Info "Checking environment to run Hog-CI for project $project_name with IDE $ide..."
845 
846  Msg Info "Checking essential commands..."
847  dict for {cmd ver} $essential_commands {
848  if {[catch {exec which $cmd}]} {
849  Msg CriticalWarning "$cmd executable not found. Hog-CI cannot run!"
850  set has_error 1
851  } else {
852  Msg Info "Found executable $cmd."
853  if {$cmd == "ghdl"} {
854  Msg Info [exec $cmd --version]
855  } elseif {$cmd != "diamond"} {
856  Msg Info [exec $cmd $ver]
857  }
858  }
859  }
860 
861  Msg Info "Checking additional commands..."
862  dict for {cmd ver} $additional_commands {
863  if {[catch {exec which $cmd}]} {
864  Msg Warning "$cmd executable not found."
865  } else {
866  Msg Info "Found executable $cmd."
867  if {$ver != ""} {
868  Msg Info [exec $cmd $ver]
869  }
870  }
871  }
872 
873  if {$ide == "libero"} {
874  Msg Info "Checking essential environment variables..."
875  # Check if HOG_TCLLIB_PATH is defined
876  if {![info exists env(HOG_TCLLIB_PATH)]} {
877  Msg Error "Environmnental variable HOG_TCLLIB_PATH is NOT defined. This variable is essential to run Hog with Tcllib and Libero. Please, refer to https://hog.readthedocs.io/en/latest/02-User-Manual/01-Hog-local/13-Libero.html."
878  set has_error 1
879  } else {
880  Msg Info "HOG_TCLLIB_PATH is set. Hog-CI can run with Libero."
881  }
882  }
883 
884  Msg Info "Checking additional environment variables..."
885  dict for {var msg} $additional_vars {
886  if {![info exists env($var)]} {
887  Msg Info "Environment variable $var is $msg"
888  } else {
889  Msg Info "Found environment variable $var."
890  }
891  }
892 
893  if {$has_error} {
894  Msg Error "One or more essential environment variables are missing. Hog-CI cannot run!"
895  exit 1
896  }
897 }
898 
899 ## @brief Check the settings for the remote IP path. It checks if the path is on EOS or Rclone and if the necessary tools are available.
900 # @param[in] repo_path The path to the repository
901 # @param[in] ip_path The path to the remote IP repository
902 #
903 # @return A list with the following elements:
904 # 1. on_eos: 1 if the path is on EOS, 0 otherwise
905 # 2. on_rclone: 1 if the path is on Rclone, 0 otherwise
906 # 3. config_path: The path to the rclone config file if on Rclone
907 proc CheckRemoteIpPath {repo_path ip_path} {
908  global env
909  set on_eos 0
910  set on_rclone 0
911  set config_path ""
912  set old_path [pwd]
913  cd $repo_path
914 
915  if {[regexp {^[^/]+:} $ip_path]} {
916  # Rclone path (e.g., dropbox:Project/IPs or eos:user/d/dcieri/...)
917  set on_rclone 1
918  # Check if rclone is available
919  lassign [ExecuteRet rclone --version] rclone_ret rclone_ver
920  if {$rclone_ret != 0} {
921  Msg Warning "Rclone path specified but rclone not found or failed: $rclone_ver"
922  cd $old_path
923  return 0
924  } else {
925  Msg Info "IP remote directory path, on Rclone, is set to: $ip_path"
926  # Check if RCLONE_CONFIG environment variable is set, if not set it to the default path
927  if {[info exists env(HOG_RCLONE_CONFIG)]} {
928  Msg Info "Using rclone config from environment variable HOG_RCLONE_CONFIG: $env(HOG_RCLONE_CONFIG)"
929  set config_path $env(HOG_RCLONE_CONFIG)
930  } else {
931  set config_path "/dev/null"
932  Msg Info "Environment variable HOG_RCLONE_CONFIG not set, using rclone environmental variables..."
933  }
934 
935  set remote_name "[lindex [split $ip_path ":"] 0]:"
936  lassign [ExecuteRet rclone listremotes --config $config_path] rclone_list_ret remotes
937  if {$rclone_list_ret != 0} {
938  Msg Warning "Could not list rclone remotes: $remotes"
939  cd $old_path
940  return 0
941  } else {
942  if {![IsInList $remote_name $remotes]} {
943  Msg Warning "Rclone remote $remote_name not found among available remotes: $remotes"
944  cd $old_path
945  return 0
946  }
947  }
948  }
949  } elseif {[string first "/eos/" $ip_path] == 0} {
950  # IP Path is on EOS
951  # Check if kinit is done
952  if {!([info exists ::env(ENABLE_EOS)] && $::env(ENABLE_EOS) == 1)} {
953  Msg Warning "IP remote directory path is on EOS but kinit was not successfull or not done. I will not copy IPs from/to EOS."
954  cd $old_path
955  return 0
956  }
957  # Check if eos is mounted
958  if {[file isdirectory $ip_path]} {
959  Msg Info "Eos is mounted in the current machine. Treating it as a normal directory..."
960  } else {
961  set on_eos 1
962  lassign [eos "ls $ip_path"] ret result
963  if {$ret != 0} {
964  Msg Warning "Could not run ls for for EOS path: $ip_path (error: $result). \
965  Either the drectory does not exist or there are (temporary) problem with EOS."
966  cd $old_path
967  return 0
968  } else {
969  Msg Info "IP remote directory path, on EOS, is set to: $ip_path"
970  }
971  }
972  } else {
973  file mkdir $ip_path
974  }
975 
976  cd $old_path
977  return [list 1 $on_eos $on_rclone $config_path]
978 }
979 
980 proc CheckProjVer {repo_path project {sim 0} {ext_path ""}} {
981  global env
982 
983  if {$sim == 1} {
984  Msg Info "Will check also the version of the simulation files..."
985  }
986 
987  set ci_run 0
988  if {[info exists env(HOG_PUSH_TOKEN)] && [info exist env(CI_PROJECT_ID)] && [info exist env(CI_API_V4_URL)]} {
989  set token $env(HOG_PUSH_TOKEN)
990  set api_url $env(CI_API_V4_URL)
991  set project_id $env(CI_PROJECT_ID)
992  set ci_run 1
993  set curl_cmd [GetCurl $api_url]
994  if {[info exist env(CI_JOB_NAME)] && $env(CI_JOB_NAME) == "check_branch_state"} {
995  # Do not download artifacts from previous pipelines in check_branch_state job...
996  set ci_run 0
997  }
998  } else {
999  set curl_cmd [GetCurl]
1000  }
1001 
1002  cd $repo_path
1003  set project_dir $repo_path/Top/$project
1004  set ver [GetProjectVersion $project_dir $repo_path $ext_path $sim]
1005  if {$ver == 0} {
1006  Msg Info "$project was modified, continuing with the CI..."
1007  if {$ci_run == 1 && $curl_cmd != 0 && ![IsQuartus] && ![IsISE]} {
1008  Msg Info "Checking if the project has been already built in a previous CI run..."
1009  lassign [GetRepoVersions $project_dir $repo_path] sha
1010  if {$sha == [GetSHA $repo_path]} {
1011  Msg Info "Project was modified in the current commit, Hog will proceed with the build workflow."
1012  return 0
1013  }
1014  Msg Info "Checking if project $project has been built in a previous CI run with sha $sha..."
1015  set result [catch {package require json} JsonFound]
1016  if {"$result" != "0"} {
1017  Msg CriticalWarning "Cannot find JSON package equal or higher than 1.0.\n $JsonFound\n Exiting"
1018  return 0
1019  }
1020  lassign [ExecuteRet {*}$curl_cmd --header "PRIVATE-TOKEN: $token" "$api_url/projects/$project_id/pipelines"] ret content
1021  set pipeline_dict [json::json2dict $content]
1022  if {[llength $pipeline_dict] > 0} {
1023  foreach pip $pipeline_dict {
1024  set pip_sha [DictGet $pip sha]
1025  set source [DictGet $pip source]
1026  if {$source == "merge_request_event" && [string first $sha $pip_sha] != -1} {
1027  Msg Info "Found pipeline with sha $pip_sha for project $project"
1028  set pipeline_id [DictGet $pip id]
1029  # tclint-disable-next-line line-length
1030  lassign [ExecuteRet {*}$curl_cmd --header "PRIVATE-TOKEN: $token" "$api_url/projects/${project_id}/pipelines/${pipeline_id}/jobs?pagination=keyset&per_page=100"] ret2 content2
1031  set jobs_dict [json::json2dict $content2]
1032  if {[llength $jobs_dict] > 0} {
1033  foreach job $jobs_dict {
1034  set job_name [DictGet $job name]
1035  set job_id [DictGet $job id]
1036  set artifacts [DictGet $job artifacts_file]
1037  set status [DictGet $job status]
1038  set current_job_name $env(CI_JOB_NAME)
1039  if {$current_job_name == $job_name && $status == "success"} {
1040  # tclint-disable-next-line line-length
1041  lassign [ExecuteRet {*}$curl_cmd --location --output artifacts.zip --header "PRIVATE-TOKEN: $token" --url "$api_url/projects/$project_id/jobs/$job_id/artifacts"] ret3 content3
1042  if {$ret3 != 0} {
1043  Msg CriticalWarning "Cannot download artifacts for job $job_name with id $job_id"
1044  return 0
1045  } else {
1046  lassign [ExecuteRet unzip -o $repo_path/artifacts.zip] ret_zip
1047  if {$ret_zip != 0} {
1048 
1049  } else {
1050  Msg Info "Artifacts for job $job_name with id $job_id downloaded and unzipped."
1051  file mkdir $repo_path/Projects/$project
1052  set fp [open "$repo_path/Projects/$project/skip.me" w+]
1053  close $fp
1054  return 1
1055  }
1056  }
1057  }
1058  }
1059  }
1060  }
1061  }
1062  }
1063  }
1064  } elseif {$ver != -1} {
1065  Msg Info "$project was not modified since version: $ver."
1066  file mkdir $repo_path/Projects/$project
1067  set fp [open "$repo_path/Projects/$project/skip.me" w+]
1068  close $fp
1069  return 1
1070  } else {
1071  Msg Error "Impossible to check the project version. Most likely the repository is not clean. Please, commit your changes before running this command."
1072  return 0
1073  }
1074  return 0
1075 }
1076 
1077 # @brief Check the syntax of the source files in the
1078 #
1079 # @param[in] project_name the name of the project
1080 # @param[in] repo_path The main path of the git repository
1081 # @param[in] project_file The project file (for Libero)
1082 proc CheckSyntax {project_name repo_path {project_file ""}} {
1083  if {[IsVivado]} {
1084  update_compile_order
1085  set syntax [check_syntax -return_string]
1086  if {[string first "CRITICAL" $syntax] != -1} {
1087  check_syntax
1088  exit 1
1089  }
1090  } elseif {[IsQuartus]} {
1091  lassign [GetHogFiles -list_files "*.src" "$repo_path/Top/$project_name/list/" $repo_path] src_files dummy
1092  dict for {lib files} $src_files {
1093  foreach f $files {
1094  set file_extension [file extension $f]
1095  if {$file_extension == ".vhd" || $file_extension == ".vhdl" || $file_extension == ".v" || $file_extension == ".sv"} {
1096  if {[catch {execute_module -tool map -args "--analyze_file=$f"} result]} {
1097  Msg Error "\nResult: $result\n"
1098  Msg Error "Check syntax failed.\n"
1099  } else {
1100  if {$result == ""} {
1101  Msg Info "Check syntax was successful for $f.\n"
1102  } else {
1103  Msg Warning "Found syntax error in file $f:\n $result\n"
1104  }
1105  }
1106  }
1107  }
1108  }
1109  } elseif {[IsLibero]} {
1110  lassign [GetProjectFiles $project_file] prjLibraries prjProperties prjSimLibraries prjConstraints prjSrcSets prjSimSets prjConSets
1111  dict for {lib sources} $prjLibraries {
1112  if {[file extension $lib] == ".src"} {
1113  foreach f $sources {
1114  Msg Info "Checking Syntax of $f"
1115  check_hdl -file $f
1116  }
1117  }
1118  }
1119  } else {
1120  Msg Info "The Checking Syntax is not supported by this IDE. Skipping..."
1121  }
1122 }
1123 
1124 # @brief Close the open project (does nothing for Xilinx and Libero)
1125 proc CloseProject {} {
1126  if {[IsXilinx]} {
1127 
1128  } elseif {[IsQuartus]} {
1129  project_close
1130  } elseif {[IsLibero]} {
1131 
1132  } elseif {[IsDiamond]} {
1133  prj_project save
1134  prj_project close
1135  }
1136 }
1137 
1138 ## @brief Compare two semantic versions
1139 #
1140 # @param[in] ver1 a list of 3 numbers M m p
1141 # @param[in] ver2 a list of 3 numbers M m p
1142 #
1143 # In case the ver1 or ver2 are in the format vX.Y.Z rather than a list, they will be converted.
1144 # If one of the tags is an empty string it will be considered as 0.0.0
1145 #
1146 # @return Returns 1 ver1 is greater than ver2, 0 if they are equal, and -1 if ver2 is greater than ver1
1147 proc CompareVersions {ver1 ver2} {
1148  if {$ver1 eq ""} {
1149  set ver1 v0.0.0
1150  }
1151 
1152  if {$ver2 eq ""} {
1153  set ver2 v0.0.0
1154  }
1155 
1156  if {[regexp {v(\d+)\.(\d+)\.(\d+)} $ver1 - x y z]} {
1157  set ver1 [list $x $y $z]
1158  }
1159  if {[regexp {v(\d+)\.(\d+)\.(\d+)} $ver2 - x y z]} {
1160  set ver2 [list $x $y $z]
1161  }
1162 
1163  # Add 1 in front to avoid crazy Tcl behaviour with leading 0 being octal...
1164  set v1 [join $ver1 ""]
1165  set v1 "1$v1"
1166  set v2 [join $ver2 ""]
1167  set v2 "1$v2"
1168 
1169  if {[string is integer $v1] && [string is integer $v2]} {
1170  set ver1 [expr {[scan [lindex $ver1 0] %d] * 1000000 + [scan [lindex $ver1 1] %d] * 1000 + [scan [lindex $ver1 2] %d]}]
1171  set ver2 [expr {[scan [lindex $ver2 0] %d] * 1000000 + [scan [lindex $ver2 1] %d] * 1000 + [scan [lindex $ver2 2] %d]}]
1172 
1173  if {$ver1 > $ver2} {
1174  set ret 1
1175  } elseif {$ver1 == $ver2} {
1176  set ret 0
1177  } else {
1178  set ret -1
1179  }
1180  } else {
1181  Msg Warning "Version is not numeric: $ver1, $ver2"
1182  set ret 0
1183  }
1184  return [expr {$ret}]
1185 }
1186 
1187 # @brief Function searching for extra IP/BD files added at creation time using user scripts, and writing the list in
1188 # Project/proj/.hog/extra.files, with the correspondent md5sum
1189 #
1190 # @param[in] libraries The Hog libraries
1191 proc CheckExtraFiles {libraries constraints simlibraries} {
1192  ### CHECK NOW FOR IP OUTSIDE OF LIST FILE (Vivado only!)
1193  if {[IsVivado]} {
1194  lassign [GetProjectFiles] prjLibraries prjProperties prjSimLibraries prjConstraints
1195  set prj_dir [get_property DIRECTORY [current_project]]
1196  file mkdir "$prj_dir/.hog"
1197  set extra_file_name "$prj_dir/.hog/extra.files"
1198  set new_extra_file [open $extra_file_name "w"]
1199 
1200  dict for {prjLib prjFiles} $prjLibraries {
1201  foreach prjFile $prjFiles {
1202  if {[file extension $prjFile] == ".xcix"} {
1203  Msg Warning "IP $prjFile is packed in a .xcix core container. \
1204  This files are not suitable for version control systems. We recommend to use .xci files instead."
1205  continue
1206  }
1207  if {[file extension $prjFile] == ".xci" && [get_property CORE_CONTAINER [get_files $prjFile]] != ""} {
1208  Msg Info "$prjFile is a virtual IP file in a core container. Ignoring it..."
1209  continue
1210  }
1211 
1212  if {[IsInList $prjFile [DictGet $libraries $prjLib]] == 0} {
1213  if {[file extension $prjFile] == ".bd"} {
1214  # Generating BD products to save md5sum of already modified BD
1215  Msg Info "Generating targets of $prjFile..."
1216  generate_target all [get_files $prjFile]
1217  }
1218  puts $new_extra_file "$prjFile [Md5Sum $prjFile]"
1219  Msg Info "$prjFile (lib: $prjLib) has been generated by an external script. Adding to $extra_file_name..."
1220  }
1221  }
1222  }
1223  close $new_extra_file
1224  set extra_sim_file "$prj_dir/.hog/extrasim.files"
1225  set new_extra_file [open $extra_sim_file "w"]
1226 
1227  dict for {prjSimLib prjSimFiles} $prjSimLibraries {
1228  foreach prjSimFile $prjSimFiles {
1229  if {[IsInList $prjSimFile [DictGet $simlibraries $prjSimLib]] == 0} {
1230  puts $new_extra_file "$prjSimFile [Md5Sum $prjSimFile]"
1231  Msg Info "$prjSimFile (lib: $prjSimLib) has been generated by an external script. Adding to $extra_sim_file..."
1232  }
1233  }
1234  }
1235  close $new_extra_file
1236  set extra_con_file "$prj_dir/.hog/extracon.files"
1237  set new_extra_file [open $extra_con_file "w"]
1238 
1239  dict for {prjConLib prjConFiles} $prjConstraints {
1240  foreach prjConFile $prjConFiles {
1241  if {[IsInList $prjConFile [DictGet $constraints $prjConLib]] == 0} {
1242  puts $new_extra_file "$prjConFile [Md5Sum $prjConFile]"
1243  Msg Info "$prjConFile has been generated by an external script. Adding to $extra_con_file..."
1244  }
1245  }
1246  }
1247  close $new_extra_file
1248  }
1249 }
1250 
1251 # @brief Check if the running Hog version is the latest stable release
1252 #
1253 # @param[in] repo_path The main path of the git repository
1254 proc CheckLatestHogRelease {{repo_path .}} {
1255  if {[info exists ::env(CHECK_FOR_HOG_UPDATES)] && $::env(CHECK_FOR_HOG_UPDATES) eq "0"} {
1256  return
1257  }
1258 
1259 
1260  if {[catch {package require inifile 0.2.3} ERROR] == 0} {
1261  set repo_conf $repo_path/Top/repo.conf
1262  if {[file exists $repo_conf]} {
1263  set PROPERTIES [ReadConf $repo_conf]
1264  if {[dict exists $PROPERTIES main]} {
1265  set mainDict [dict get $PROPERTIES main]
1266  if {[dict exists $mainDict CHECK_FOR_HOG_UPDATES]} {
1267  if {[dict get $mainDict CHECK_FOR_HOG_UPDATES] == 0} {
1268  return
1269  }
1270  }
1271  }
1272  }
1273  }
1274 
1275  set old_path [pwd]
1276  cd $repo_path/Hog
1277  set current_ver [Git {describe --always}]
1278  Msg Debug "Current version: $current_ver"
1279  set current_sha [Git "log $current_ver -1 --format=format:%H"]
1280  Msg Debug "Current SHA: $current_sha"
1281 
1282  #We should find a proper way of checking for timeout using wait, this'll do for now
1283  if {[OS] == "windows"} {
1284  Msg Info "On windows we cannot set a timeout on 'git fetch', hopefully nothing will go wrong..."
1285  Git fetch
1286  } else {
1287  Msg Info "Checking for latest Hog release, can take up to 5 seconds..."
1288  ExecuteRet timeout 5s git fetch
1289  }
1290  set master_ver [Git "describe origin/master"]
1291  Msg Debug "Master version: $master_ver"
1292  set master_sha [Git "log $master_ver -1 --format=format:%H"]
1293  Msg Debug "Master SHA: $master_sha"
1294  lassign [GitRet "merge-base $current_sha $master_sha"] mb_ret merge_base
1295  if {$mb_ret != 0} {
1296  Msg Warning "Could not run git merge-base (shallow clone?). Skipping Hog update check."
1297  cd $old_path
1298  return
1299  }
1300  Msg Debug "merge base: $merge_base"
1301 
1302 
1303  if {$merge_base != $master_sha} {
1304  # If master_sha is NOT an ancestor of current_sha
1305  Msg Info "Version $master_ver has been released (https://gitlab.com/hog-cern/Hog/-/releases/$master_ver)"
1306  Msg Status "You should consider updating Hog submodule with the following instructions:"
1307  Msg Status ""
1308  Msg Status "cd Hog && git checkout master && git pull"
1309  Msg Status ""
1310  Msg Status "Also update the ref: in your .gitlab-ci.yml to $master_ver"
1311  Msg Status ""
1312  } else {
1313  # If it is
1314  Msg Info "Latest official version is $master_ver, nothing to do."
1315  }
1316 
1317  cd $old_path
1318 }
1319 
1320 
1321 ## @brief Checks that "ref" in .gitlab-ci.yml actually matches the hog.yml file in the
1322 #
1323 # @param[in] repo_path path to the repository root
1324 # @param[in] allow_failure if true throws CriticalWarnings instead of Errors
1325 #
1326 proc CheckYmlRef {repo_path allow_failure} {
1327  if {$allow_failure} {
1328  set MSG_TYPE CriticalWarning
1329  } else {
1330  set MSG_TYPE Error
1331  }
1332 
1333  if {[catch {package require yaml 0.3.3} YAMLPACKAGE]} {
1334  Msg CriticalWarning "Cannot find package YAML, skipping consistency check of \"ref\" in gilab-ci.yaml file.\n Error message: $YAMLPACKAGE
1335  You can fix this by installing package \"tcllib\""
1336  return
1337  }
1338 
1339  set thisPath [pwd]
1340 
1341  # Go to repository path
1342  cd "$repo_path"
1343  if {[file exists .gitlab-ci.yml]} {
1344  #get .gitlab-ci ref
1345  set YML_REF ""
1346  set YML_NAME ""
1347  if {[file exists .gitlab-ci.yml]} {
1348  set fp [open ".gitlab-ci.yml" r]
1349  set file_data [read $fp]
1350  close $fp
1351  } else {
1352  Msg $MSG_TYPE "Cannot open file .gitlab-ci.yml"
1353  cd $thisPath
1354  return
1355  }
1356  set file_data "\n$file_data\n\n"
1357 
1358  if {[catch {::yaml::yaml2dict -stream $file_data} yamlDict]} {
1359  Msg $MSG_TYPE "Parsing $repo_path/.gitlab-ci.yml failed. To fix this, check that yaml syntax is respected, remember not to use tabs."
1360  cd $thisPath
1361  return
1362  } else {
1363  dict for {dictKey dictValue} $yamlDict {
1364  #looking for Hog include in .gitlab-ci.yml
1365  if {
1366  "$dictKey" == "include" && (
1367  [lsearch [split $dictValue " {}"] "/hog.yml"] != "-1" ||
1368  [lsearch [split $dictValue " {}"] "/hog-dynamic.yml"] != "-1"
1369  )
1370  } {
1371  set YML_REF [lindex [split $dictValue " {}"] [expr {[lsearch -dictionary [split $dictValue " {}"] "ref"] + 1}]]
1372  set YML_NAME [lindex [split $dictValue " {}"] [expr {[lsearch -dictionary [split $dictValue " {}"] "file"] + 1}]]
1373  }
1374  }
1375  }
1376  if {$YML_REF == ""} {
1377  Msg Warning "Hog version not specified in the .gitlab-ci.yml. Assuming that master branch is used."
1378  cd Hog
1379  set YML_REF_F [Git {name-rev --tags --name-only origin/master}]
1380  cd ..
1381  } else {
1382  set YML_REF_F [regsub -all "'" $YML_REF ""]
1383  }
1384 
1385  if {$YML_NAME == ""} {
1386  Msg $MSG_TYPE "Hog included yml file not specified, assuming hog.yml"
1387  set YML_NAME_F hog.yml
1388  } else {
1389  set YML_NAME_F [regsub -all "^/" $YML_NAME ""]
1390  }
1391 
1392  lappend YML_FILES $YML_NAME_F
1393 
1394  #getting Hog repository tag and commit
1395  cd "Hog"
1396 
1397  #check if the yml file includes other files
1398  if {[catch {::yaml::yaml2dict -file $YML_NAME_F} yamlDict]} {
1399  Msg $MSG_TYPE "Parsing $YML_NAME_F failed."
1400  cd $thisPath
1401  return
1402  } else {
1403  dict for {dictKey dictValue} $yamlDict {
1404  #looking for included files
1405  if {"$dictKey" == "include"} {
1406  foreach v $dictValue {
1407  lappend YML_FILES [lindex [split $v " "] [expr {[lsearch -dictionary [split $v " "] "local"] + 1}]]
1408  }
1409  }
1410  }
1411  }
1412 
1413  Msg Info "Found the following yml files: $YML_FILES"
1414 
1415  set HOGYML_SHA [GetSHA $YML_FILES]
1416  lassign [GitRet "log --format=%h -1 --abbrev=7 $YML_REF_F" $YML_FILES] ret EXPECTEDYML_SHA
1417  if {$ret != 0} {
1418  lassign [GitRet "log --format=%h -1 --abbrev=7 origin/$YML_REF_F" $YML_FILES] ret EXPECTEDYML_SHA
1419  if {$ret != 0} {
1420  Msg $MSG_TYPE "Error in project .gitlab-ci.yml. ref: $YML_REF not found"
1421  set EXPECTEDYML_SHA ""
1422  }
1423  }
1424  if {!($EXPECTEDYML_SHA eq "")} {
1425  if {$HOGYML_SHA == $EXPECTEDYML_SHA} {
1426  Msg Info "Hog included file $YML_FILES matches with $YML_REF in .gitlab-ci.yml."
1427  } else {
1428  Msg $MSG_TYPE "HOG $YML_FILES SHA mismatch.
1429  From Hog submodule: $HOGYML_SHA
1430  From ref in .gitlab-ci.yml: $EXPECTEDYML_SHA
1431  You can fix this in 2 ways: by changing the ref in your repository or by changing the Hog submodule commit"
1432  }
1433  } else {
1434  Msg $MSG_TYPE "One or more of the following files could not be found $YML_FILES in Hog at $YML_REF"
1435  }
1436  } else {
1437  Msg Info ".gitlab-ci.yml not found in $repo_path. Skipping this step"
1438  }
1439 
1440  cd "$thisPath"
1441 }
1442 
1443 ## @brief Compare the contents of two dictionaries
1444 #
1445 # @param[in] proj_libs The dictionary of libraries in the project
1446 # @param[in] list_libs The dictionary of libraries in list files
1447 # @param[in] proj_sets The dictionary of filesets in the project
1448 # @param[in] list_sets The dictionary of filesets in list files
1449 # @param[in] proj_props The dictionary of file properties in the project
1450 # @param[in] list_props The dictionary of file pproperties in list files
1451 # @param[in] severity The severity of the message in case a file is not found (Default: CriticalWarning)
1452 # @param[in] outFile The output log file, to write the messages (Default "")
1453 # @param[in] extraFiles The dictionary of extra files generated a creation time (Default "")
1454 #
1455 # @return n_diffs The number of differences
1456 # @return extra_files Remaining list of extra files
1457 
1458 proc CompareLibDicts {proj_libs list_libs proj_sets list_sets proj_props list_props {severity "CriticalWarning"} {outFile ""} {extraFiles ""}} {
1459  set extra_files $extraFiles
1460  set n_diffs 0
1461  set out_prjlibs $proj_libs
1462  set out_prjprops $proj_props
1463  # Loop over filesets in project
1464  dict for {prjSet prjLibraries} $proj_sets {
1465  # Check if sets is also in list files
1466  if {[IsInList $prjSet $list_sets]} {
1467  set listLibraries [DictGet $list_sets $prjSet]
1468  # Loop over libraries in fileset
1469  foreach prjLib $prjLibraries {
1470  set prjFiles [DictGet $proj_libs $prjLib]
1471  # Check if library exists in list files
1472  if {[IsInList $prjLib $listLibraries]} {
1473  # Loop over files in library
1474  set listFiles [DictGet $list_libs $prjLib]
1475  foreach prjFile $prjFiles {
1476  set idx [lsearch -exact $listFiles $prjFile]
1477  set listFiles [lreplace $listFiles $idx $idx]
1478  if {$idx < 0} {
1479  # File is in project but not in list libraries, check if it was generated at creation time...
1480  if {[dict exists $extra_files $prjFile]} {
1481  # File was generated at creation time, checking the md5sum
1482  # Removing the file from the prjFiles list
1483  set idx2 [lsearch -exact $prjFiles $prjFile]
1484  set prjFiles [lreplace $prjFiles $idx2 $idx2]
1485  set new_md5sum [Md5Sum $prjFile]
1486  set old_md5sum [DictGet $extra_files $prjFile]
1487  if {$new_md5sum != $old_md5sum} {
1488  # tclint-disable-next-line line-length
1489  MsgAndLog "$prjFile in project has been modified from creation time. \Please update the script you used to create the file and regenerate the project, or save the file outside the Projects/ directory and add it to a project list file" $severity $outFile
1490  incr n_diffs
1491  }
1492  set extra_files [dict remove $extra_files $prjFile]
1493  } else {
1494  # File is neither in list files nor in extra_files
1495  MsgAndLog "$prjFile was found in project but not in list files or .hog/extra.files" $severity $outFile
1496  incr n_diffs
1497  }
1498  } else {
1499  # File is both in list files and project, checking properties...
1500  set prjProps [DictGet $proj_props $prjFile]
1501  set listProps [DictGet $list_props $prjFile]
1502  # Check if it is a potential sourced file
1503  if {[IsInList "nosynth" $prjProps] && [IsInList "noimpl" $prjProps] && [IsInList "nosim" $prjProps]} {
1504  # Check if it is sourced
1505  set idx_source [lsearch -exact $listProps "source"]
1506  if {$idx_source >= 0} {
1507  # It is sourced, let's replace the individual properties with source
1508  set idx [lsearch -exact $prjProps "noimpl"]
1509  set prjProps [lreplace $prjProps $idx $idx]
1510  set idx [lsearch -exact $prjProps "nosynth"]
1511  set prjProps [lreplace $prjProps $idx $idx]
1512  set idx [lsearch -exact $prjProps "nosim"]
1513  set prjProps [lreplace $prjProps $idx $idx]
1514  lappend prjProps "source"
1515  }
1516  }
1517 
1518  foreach prjProp $prjProps {
1519  set idx [lsearch -exact $listProps $prjProp]
1520  set listProps [lreplace $listProps $idx $idx]
1521  if {$idx < 0} {
1522  MsgAndLog "Property $prjProp of $prjFile was set in project but not in list files" $severity $outFile
1523  incr n_diffs
1524  }
1525  }
1526 
1527  foreach listProp $listProps {
1528  if {[string first $listProp "topsim="] == -1 && [string first $listProp "enable"] == -1} {
1529  MsgAndLog "Property $listProp of $prjFile was found in list files but not set in project." $severity $outFile
1530  incr n_diffs
1531  }
1532  }
1533 
1534  # Update project prjProps
1535  dict set out_prjprops $prjFile $prjProps
1536  }
1537  }
1538  # Loop over remaining files in list libraries
1539  foreach listFile $listFiles {
1540  MsgAndLog "$listFile was found in list files but not in project." $severity $outFile
1541  incr n_diffs
1542  }
1543  } else {
1544  # Check extra files again...
1545  foreach prjFile $prjFiles {
1546  if {[dict exists $extra_files $prjFile]} {
1547  # File was generated at creation time, checking the md5sum
1548  # Removing the file from the prjFiles list
1549  set idx2 [lsearch -exact $prjFiles $prjFile]
1550  set prjFiles [lreplace $prjFiles $idx2 $idx2]
1551  set new_md5sum [Md5Sum $prjFile]
1552  set old_md5sum [DictGet $extra_files $prjFile]
1553  if {$new_md5sum != $old_md5sum} {
1554  # tclint-disable-next-line line-length
1555  MsgAndLog "$prjFile in project has been modified from creation time. Please update the script you used to create the file and regenerate the project, or save the file outside the Projects/ directory and add it to a project list file" $severity $outFile
1556  incr n_diffs
1557  }
1558  set extra_files [dict remove $extra_files $prjFile]
1559  } else {
1560  # File is neither in list files nor in extra_files
1561  MsgAndLog "$prjFile was found in project but not in list files or .hog/extra.files" $severity $outFile
1562  incr n_diffs
1563  }
1564  }
1565  }
1566  # Update prjLibraries
1567  dict set out_prjlibs $prjLib $prjFiles
1568  }
1569  } else {
1570  MsgAndLog "Fileset $prjSet found in project but not in list files" $severity $outFile
1571  incr n_diffs
1572  }
1573  }
1574 
1575  return [list $n_diffs $extra_files $out_prjlibs $out_prjprops]
1576 }
1577 
1578 ## @brief Compare two VHDL files ignoring spaces and comments
1579 #
1580 # @param[in] file1 the first file
1581 # @param[in] file2 the second file
1582 #
1583 # @ return A string with the diff of the files
1584 #
1585 proc CompareVHDL {file1 file2} {
1586  set a [open $file1 r]
1587  set b [open $file2 r]
1588 
1589  while {[gets $a line] != -1} {
1590  set line [regsub {^[\t\s]*(.*)?\s*} $line "\\1"]
1591  if {![regexp {^$} $line] & ![regexp {^--} $line]} {
1592  #Exclude empty lines and comments
1593  lappend f1 $line
1594  }
1595  }
1596 
1597  while {[gets $b line] != -1} {
1598  set line [regsub {^[\t\s]*(.*)?\s*} $line "\\1"]
1599  if {![regexp {^$} $line] & ![regexp {^--} $line]} {
1600  #Exclude empty lines and comments
1601  lappend f2 $line
1602  }
1603  }
1604 
1605  close $a
1606  close $b
1607  set diff {}
1608  foreach x $f1 y $f2 {
1609  if {$x != $y} {
1610  lappend diff "> $x\n< $y\n\n"
1611  }
1612  }
1613 
1614  return $diff
1615 }
1616 
1617 ##
1618 ## Copy a file or folder into a new path, not throwing an error if the final path is not empty
1619 ##
1620 ## @param i_dirs The directory or file to copy
1621 ## @param o_dir The final destination
1622 ##
1623 proc Copy {i_dirs o_dir} {
1624  foreach i_dir $i_dirs {
1625  if {[file isdirectory $i_dir] && [file isdirectory $o_dir]} {
1626  if {([file tail $i_dir] == [file tail $o_dir]) || ([file exists $o_dir/[file tail $i_dir]] && [file isdirectory $o_dir/[file tail $i_dir]])} {
1627  file delete -force $o_dir/[file tail $i_dir]
1628  }
1629  }
1630 
1631  file copy -force $i_dir $o_dir
1632  }
1633 }
1634 
1635 ## @brief Read a XML list file and copy files to destination
1636 #
1637 # Additional information is provided with text separated from the file name with one or more spaces
1638 #
1639 # @param[in] proj_dir project path, path containing the ./list directory containing at least a list file with .ipb extention
1640 # @param[in] path the path the XML files are referred to in the list file
1641 # @param[in] dst the path the XML files must be copied to
1642 # @param[in] xml_version the M.m.p version to be used to replace the __VERSION__ placeholder in any of the xml files
1643 # @param[in] xml_sha the Git-SHA to be used to replace the __GIT_SHA__ placeholder in any of the xml files
1644 # @param[in] use_ipbus_sw if set to 1, use the IPbus sw to generate or check the vhdl files
1645 # @param[in] generate if set to 1, tells the function to generate the VHDL decode address files rather than check them
1646 proc CopyIPbusXMLs {proj_dir path dst {xml_version "0.0.0"} {xml_sha "00000000"} {use_ipbus_sw 0} {generate 0}} {
1647  if {$use_ipbus_sw == 1} {
1648  lassign [ExecuteRet python3 -c "from __future__ import print_function; from sys import path;print(':'.join(path\[1:\]))"] ret msg
1649  if {$ret == 0} {
1650  set ::env(PYTHONPATH) $msg
1651  lassign [ExecuteRet gen_ipbus_addr_decode -h] ret msg
1652  if {$ret != 0} {
1653  set can_generate 0
1654  } else {
1655  set can_generate 1
1656  }
1657  } else {
1658  Msg CriticalWarning "Problem while trying to run python: $msg"
1659  set can_generate 0
1660  }
1661  set dst [file normalize $dst]
1662  file mkdir $dst
1663  if {$can_generate == 0} {
1664  if {$generate == 1} {
1665  Msg Error "Cannot generate IPbus address files, IPbus executable gen_ipbus_addr_decode not found or not working: $msg"
1666  return -1
1667  } else {
1668  Msg Warning "IPbus executable gen_ipbus_addr_decode not found or not working, will not verify IPbus address tables."
1669  }
1670  }
1671  } else {
1672  set can_generate 0
1673  }
1674 
1675  set ipb_files [glob -nocomplain $proj_dir/list/*.ipb]
1676  set n_ipb_files [llength $ipb_files]
1677  if {$n_ipb_files == 0} {
1678  Msg CriticalWarning "No files with .ipb extension found in $proj_dir/list."
1679  return
1680  }
1681  set libraries [dict create]
1682  set vhdl_dict [dict create]
1683 
1684  foreach ipb_file $ipb_files {
1685  lassign [ReadListFile {*}"$ipb_file $path"] l p fs
1686  set libraries [MergeDict $l $libraries]
1687  set vhdl_dict [MergeDict $p $vhdl_dict]
1688  }
1689 
1690  set xmlfiles [dict get $libraries "xml.ipb"]
1691 
1692  set xml_list_error 0
1693  foreach xmlfile $xmlfiles {
1694  if {[file isdirectory $xmlfile]} {
1695  Msg CriticalWarning "Directory $xmlfile listed in xml list file $list_file. Directories are not supported!"
1696  set xml_list_error 1
1697  }
1698 
1699  if {[file exists $xmlfile]} {
1700  if {[dict exists $vhdl_dict $xmlfile]} {
1701  set vhdl_file [file normalize [dict get $vhdl_dict $xmlfile]]
1702  } else {
1703  set vhdl_file ""
1704  }
1705  lappend vhdls $vhdl_file
1706  set xmlfile [file normalize $xmlfile]
1707  Msg Info "Copying $xmlfile to $dst and replacing place holders..."
1708  set in [open $xmlfile r]
1709 
1710  if {[regexp {/xml/+(.*)$} $xmlfile XXX out_with_dir]} {
1711  set out_file $dst/$out_with_dir
1712  lappend xmls $out_with_dir
1713  Msg Debug "xml file $xmlfile is contained in a directory called 'xml', so file will be copied to $out_file"
1714  set out_dir [file dir $out_file]
1715  if {![file exists $out_dir]} {
1716  file mkdir $out_dir
1717  }
1718  } else {
1719  set out_file $dst/[file tail $xmlfile]
1720  lappend xmls [file tail $xmlfile]
1721  }
1722 
1723  set out [open $out_file w]
1724  while {[gets $in line] != -1} {
1725  set new_line [regsub {(.*)__VERSION__(.*)} $line "\\1$xml_version\\2"]
1726  set new_line2 [regsub {(.*)__GIT_SHA__(.*)} $new_line "\\1$xml_sha\\2"]
1727  puts $out $new_line2
1728  }
1729  close $in
1730  close $out
1731  } else {
1732  Msg Warning "XML file $xmlfile not found"
1733  }
1734  }
1735  if {${xml_list_error}} {
1736  Msg Error "Invalid files added to $list_file!"
1737  }
1738 
1739  set cnt [llength $xmls]
1740  Msg Info "$cnt xml file/s copied"
1741 
1742 
1743  if {$can_generate == 1} {
1744  set old_dir [pwd]
1745  cd $dst
1746  file mkdir "address_decode"
1747  cd "address_decode"
1748  foreach x $xmls v $vhdls {
1749  if {$v ne ""} {
1750  set x [file normalize ../$x]
1751  if {[file exists $x]} {
1752  lassign [ExecuteRet gen_ipbus_addr_decode --no-timestamp $x 2>&1] status log
1753  if {$status == 0} {
1754  set generated_vhdl ./ipbus_decode_[file rootname [file tail $x]].vhd
1755  if {$generate == 1} {
1756  Msg Info "Copying generated VHDL file $generated_vhdl into $v (replacing if necessary)"
1757  file copy -force -- $generated_vhdl $v
1758  } else {
1759  if {[file exists $v]} {
1760  set diff [CompareVHDL $generated_vhdl $v]
1761  set n [llength $diff]
1762  if {$n > 0} {
1763  Msg CriticalWarning "$v does not correspond to its XML $x, [expr {$n / 3}] line/s differ:"
1764  Msg Status [join $diff "\n"]
1765  set diff_file [open ../diff_[file rootname [file tail $x]].txt w]
1766  puts $diff_file $diff
1767  close $diff_file
1768  } else {
1769  Msg Info "[file tail $x] and $v match."
1770  }
1771  } else {
1772  Msg Warning "VHDL address map file $v not found."
1773  }
1774  }
1775  } else {
1776  Msg Warning "Address map generation failed for [file tail $x]: $log"
1777  }
1778  } else {
1779  Msg Warning "Copied XML file $x not found."
1780  }
1781  } else {
1782  Msg Info "Skipped verification of [file tail $x] as no VHDL file was specified."
1783  }
1784  }
1785  cd ..
1786  file delete -force address_decode
1787  cd $old_dir
1788  }
1789 }
1790 
1791 ## @brief Map a Cheby generator alias from the .chb list file to the
1792 # corresponding cheby command-line flag.
1793 #
1794 # Each line in a .chb list file may set a `gen=` property whose value is a
1795 # comma-separated list of generators (e.g. `gen=hdl,consts`). The aliases used
1796 # in the list file are intentionally short and stable; this proc translates
1797 # them to the actual cheby executable flags (e.g. `--gen-hdl`).
1798 #
1799 # @param[in] gen The short generator alias (e.g. "hdl", "consts", "c", "doc")
1800 #
1801 # @return The cheby command-line flag for that generator,
1802 # or an empty string if the alias is unknown.
1803 proc ChebyGenFlag {gen} {
1804  switch -- $gen {
1805  "hdl" { return "--gen-hdl" }
1806  "consts" { return "--gen-consts" }
1807  "c" { return "--gen-c" }
1808  "c_check" { return "--gen-c-check-layout" }
1809  "doc" { return "--gen-doc" }
1810  "memmap" { return "--print-memmap" }
1811  "memmap_v" { return "--print-memmap-verbose" }
1812  "pretty" { return "--print-pretty" }
1813  "devicetree" { return "--gen-devicetree" }
1814  "edge" { return "--gen-edge" }
1815  "silecs" { return "--gen-silecs" }
1816  "wbgen" { return "--gen-wbgen-hdl" }
1817  "custom" { return "--gen-custom" }
1818  "install" { return "--gen-install-script" }
1819  "gena_memmap" { return "--gen-gena-memmap" }
1820  "gena_regctrl" { return "--gen-gena-regctrl" }
1821  default { return "" }
1822  }
1823 }
1824 
1825 ## @brief Parse a Cheby `.chb` list file into a list of per-line dictionaries.
1826 #
1827 # Each non-empty, non-comment line is expected to have the form:
1828 # <input.cheby> [<output1> <output2> ...] [key=value ...]
1829 # Tokens containing `=` are treated as properties (mapped to cheby flags),
1830 # while tokens without `=` are treated as expected output files.
1831 #
1832 # @param[in] chb_file Path to a .chb list file.
1833 #
1834 # @return A list of dictionaries, one per line. Each dictionary
1835 # contains keys: input, outputs, props, line, file.
1836 proc ParseChebyListFile {chb_file} {
1837  set fp [open $chb_file r]
1838  set data [read $fp]
1839  close $fp
1840  set lines [split $data "\n"]
1841  set result [list]
1842  set line_num 0
1843  foreach line $lines {
1844  incr line_num
1845  set trimmed [string trim $line]
1846  if {$trimmed eq "" || [string index $trimmed 0] eq "#"} {
1847  continue
1848  }
1849  set tokens [regexp -all -inline {\S+} $line]
1850  if {[llength $tokens] < 1} {
1851  continue
1852  }
1853  set input [lindex $tokens 0]
1854  set rest [lrange $tokens 1 end]
1855  set outputs [list]
1856  set props [dict create]
1857  foreach tok $rest {
1858  set eq_pos [string first "=" $tok]
1859  if {$eq_pos == -1} {
1860  lappend outputs $tok
1861  } else {
1862  set key [string range $tok 0 [expr {$eq_pos - 1}]]
1863  set val [string range $tok [expr {$eq_pos + 1}] end]
1864  dict set props $key $val
1865  }
1866  }
1867  lappend result [dict create input $input outputs $outputs props $props \
1868  line $line_num file $chb_file]
1869  }
1870  return $result
1871 }
1872 
1873 ## @brief Translate Cheby list-file properties into cheby command-line flags
1874 # and pair each declared output file with its generator.
1875 #
1876 # The properties dictionary may contain a special `gen=` entry whose value is
1877 # a comma-separated list of generator aliases. The number of comma-separated
1878 # generators must match the number of expected output files declared on the
1879 # same .chb line. When `gen=` is absent, this proc tries to infer a single
1880 # generator from the file extension of the (single) declared output file.
1881 #
1882 # All other recognised properties are mapped to cheby flags, e.g.:
1883 # hdl=vhdl -> --hdl vhdl
1884 # header=commit -> --header commit
1885 # c_style=arm -> --c-style arm
1886 # doc=html -> --doc html
1887 # Boolean-style properties (e.g. hdl_preload=1) are emitted as bare flags.
1888 # Properties whose key already starts with `--` are passed through verbatim.
1889 #
1890 # @param[in] props A dict of key=value properties parsed from the .chb line.
1891 # @param[in] outputs A list of expected output file paths declared on the
1892 # same .chb line.
1893 #
1894 # @return A 3-element list { ok gen_map opt_flags } where:
1895 # ok is 0 on success or non-zero on error.
1896 # gen_map on success: a list { gen out gen out ... }
1897 # pairing each generator with its output;
1898 # on error: a human-readable error message.
1899 # opt_flags on success: a flat list of cheby flag/value
1900 # elements to add to the command line.
1901 proc BuildChebyCmdArgs {props outputs} {
1902  set gens [list]
1903  if {[dict exists $props "gen"]} {
1904  set gen_csv [dict get $props "gen"]
1905  set gens [split $gen_csv ","]
1906  }
1907  set ngens [llength $gens]
1908  if {$ngens == 0} {
1909  if {[llength $outputs] == 1} {
1910  set ext [string tolower [file extension [lindex $outputs 0]]]
1911  switch -- $ext {
1912  ".vhd" -
1913  ".vhdl" -
1914  ".v" -
1915  ".sv" { set gens [list "hdl"] }
1916  ".h" -
1917  ".hpp" { set gens [list "c"] }
1918  ".html" -
1919  ".md" -
1920  ".rst" -
1921  ".tex" { set gens [list "doc"] }
1922  default {
1923  return [list 1 "Cannot infer generator from output extension '$ext'.\
1924  Please add a `gen=...` property to the line." [list]]
1925  }
1926  }
1927  set ngens 1
1928  } else {
1929  return [list 1 "Cannot map [llength $outputs] outputs without a `gen=...`\
1930  property listing the generators." [list]]
1931  }
1932  }
1933  if {[llength $outputs] != $ngens} {
1934  return [list 1 "Number of declared outputs ([llength $outputs]) does not match\
1935  number of generators ($ngens, gen=[join $gens ,])." [list]]
1936  }
1937  set gen_map [list]
1938  foreach g $gens o $outputs {
1939  lappend gen_map $g $o
1940  }
1941 
1942  set option_map [dict create \
1943  "hdl" "--hdl" \
1944  "header" "--header" \
1945  "c_style" "--c-style" \
1946  "consts_style" "--consts-style" \
1947  "doc" "--doc" \
1948  "address_space" "--address-space" \
1949  "out_prefix" "--out-prefix" \
1950  "ff_reset" "--ff-reset" \
1951  "word_endian" "--word-endian" \
1952  "wb_lib_name" "--wb-lib-name" \
1953  "axil_lib_name" "--axil-lib-name" \
1954  "rest_headers" "--rest-headers" \
1955  "custom" "--custom" \
1956  ]
1957  set bool_map [dict create \
1958  "hdl_preload" "--hdl-preload" \
1959  "doc_hide_comments" "--doc-hide-comments" \
1960  "doc_no_reg_drawing" "--doc-no-reg-drawing" \
1961  "doc_include_js_dep" "--doc-include-js-dep" \
1962  "gena_common_visual" "--gena-common-visual" \
1963  "gen_c_bit_struct" "--gen-c-bit-struct" \
1964  "gen_gena_dsp" "--gen-gena-dsp" \
1965  ]
1966 
1967  set opt_flags [list]
1968  dict for {k v} $props {
1969  if {$k eq "gen" || $k eq "profile"} {
1970  continue
1971  }
1972  if {[dict exists $option_map $k]} {
1973  lappend opt_flags [dict get $option_map $k] $v
1974  } elseif {[dict exists $bool_map $k]} {
1975  if {$v eq "1" || [string tolower $v] eq "true" || [string tolower $v] eq "yes"} {
1976  lappend opt_flags [dict get $bool_map $k]
1977  }
1978  } elseif {[string range $k 0 1] eq "--"} {
1979  lappend opt_flags $k $v
1980  } else {
1981  Msg Warning "Unknown cheby property '$k=$v', ignoring."
1982  }
1983  }
1984  return [list 0 $gen_map $opt_flags]
1985 }
1986 
1987 ## @brief Return @a abs as a path relative to @a base for cheby argv/header display.
1988 #
1989 # Cheby records sys.argv in generated file headers. Running cheby from the
1990 # YAML directory with relative paths produces headers comparable to manual
1991 # gen_regs.sh invocations (e.g. gasp_regs.yaml instead of an absolute path).
1992 #
1993 # @param[in] base Reference directory (typically the .yaml/.cheby parent dir).
1994 # @param[in] abs Absolute path to express relatively.
1995 #
1996 # @return A relative path, or @a abs unchanged when no relative form exists.
1997 proc ChebyRelPath {base abs} {
1998  set base [file normalize $base]
1999  set abs [file normalize $abs]
2000  if {$base eq [file dirname $abs]} {
2001  return [file tail $abs]
2002  }
2003  set rel [Relative $base $abs 1]
2004  if {$rel eq ""} {
2005  return $abs
2006  }
2007  return $rel
2008 }
2009 
2010 ## @brief Drop the leading auto-generated cheby comment header from a line list.
2011 #
2012 # Cheby headers (see cheby/gen_header.py) are metadata only and always sit at
2013 # the top of the file in a fixed shape: a banner line, the argv line, and an
2014 # optional "Generated on <date> by <user>" line (only with header=full). None
2015 # of these should cause check-mode mismatches when the register body matches.
2016 # Blank lines are assumed already removed by the caller.
2017 #
2018 # @param[in] lines Non-blank, trimmed lines read from a generated file.
2019 #
2020 # @return Lines with the cheby banner/argv/timestamp lines removed.
2021 proc StripChebyGeneratedHeader {lines} {
2022  set idx [lsearch -regexp $lines {Do not edit\.\s+Generated by cheby}]
2023  if {$idx < 0} {
2024  return $lines
2025  }
2026  # Always drop the banner and the following argv line.
2027  set last $idx
2028  incr last
2029  # Drop the optional timestamp line when present (header=full).
2030  # Match anywhere in the line: VHDL uses "-- Generated on ...", C/Markdown
2031  # may use other comment prefixes.
2032  set ts_line [lindex $lines [expr {$idx + 2}]]
2033  if {$ts_line ne "" && [string first "Generated on " $ts_line] >= 0} {
2034  incr last
2035  }
2036  return [lreplace $lines $idx $last]
2037 }
2038 
2039 ## @brief Compare two text files ignoring trailing whitespace and blank lines.
2040 #
2041 # Used by CopyChebyFiles to detect if a regenerated cheby output is
2042 # semantically different from what is currently committed on disk.
2043 #
2044 # @param[in] file1 Path to the first file.
2045 # @param[in] file2 Path to the second file.
2046 # @param[in] skip_cheby_header If 1, ignore cheby auto-generated comment headers.
2047 #
2048 # @return 1 if the files are equivalent, 0 otherwise.
2049 proc FilesAreSemanticallyEqual {file1 file2 {skip_cheby_header 0}} {
2050  if {![file exists $file1] || ![file exists $file2]} {
2051  return 0
2052  }
2053  set fa [open $file1 r]
2054  set fb [open $file2 r]
2055  set la [list]
2056  set lb [list]
2057  while {[gets $fa line] != -1} {
2058  set line [string trimright $line]
2059  if {[string trim $line] eq ""} { continue }
2060  lappend la $line
2061  }
2062  while {[gets $fb line] != -1} {
2063  set line [string trimright $line]
2064  if {[string trim $line] eq ""} { continue }
2065  lappend lb $line
2066  }
2067  close $fa
2068  close $fb
2069  if {$skip_cheby_header} {
2070  set la [StripChebyGeneratedHeader $la]
2071  set lb [StripChebyGeneratedHeader $lb]
2072  }
2073  if {[llength $la] != [llength $lb]} {
2074  return 0
2075  }
2076  foreach x $la y $lb {
2077  if {$x ne $y} { return 0 }
2078  }
2079  return 1
2080 }
2081 
2082 ## @brief Read .chb (Cheby) list files and either regenerate or check the
2083 # declared cheby outputs (HDL, C headers, documentation, etc.).
2084 #
2085 # This is the Cheby equivalent of CopyIPbusXMLs. For each .chb file in
2086 # `<proj_dir>/list/`, every non-comment line is parsed (see ParseChebyListFile)
2087 # and the cheby executable is invoked with the appropriate flags. In `check`
2088 # mode (the default), generated outputs are written to a temporary directory
2089 # and compared against the on-disk targets, reporting any mismatches; in
2090 # `generate` mode the on-disk targets are overwritten with the freshly
2091 # generated content.
2092 #
2093 # A copy of the resolved .cheby inputs and the (existing) generated outputs
2094 # is also placed under `<dst>` for traceability.
2095 #
2096 # @param[in] proj_dir Project directory (must contain a `list/` folder).
2097 # @param[in] path Base path against which paths inside the .chb
2098 # list files are resolved (typically the repo root).
2099 # @param[in] dst Destination directory where the resolved cheby
2100 # dependency set and selected outputs are copied.
2101 # @param[in] cheby_version Project-wide cheby version (recorded in logs).
2102 # @param[in] cheby_sha Project-wide cheby SHA (recorded in logs).
2103 # @param[in] generate If 1, overwrite on-disk outputs with newly
2104 # generated content; if 0, only check.
2105 # @param[in] profile If not "all", only process .chb lines whose
2106 # `profile=` property matches this value.
2107 # @param[in] tool Cheby executable to invoke (default: "cheby").
2108 # @param[in] strict If 1, any mismatch/missing output is reported as
2109 # an Error (otherwise as a CriticalWarning).
2110 # @param[in] verbose If 1, print expanded cheby command lines.
2111 #
2112 # @return The number of errors encountered (0 on success).
2113 proc CopyChebyFiles {proj_dir path dst {cheby_version "0.0.0"} {cheby_sha "00000000"} \
2114  {generate 0} {profile "all"} {tool "cheby"} {strict 0} {verbose 0}} {
2115  set chb_files [glob -nocomplain $proj_dir/list/*.chb]
2116  if {[llength $chb_files] == 0} {
2117  Msg CriticalWarning "No files with .chb extension found in $proj_dir/list."
2118  return 1
2119  }
2120 
2121  lassign [ExecuteRetUserEnv $tool --version] ret tool_msg
2122  if {$ret != 0} {
2123  if {$generate == 1} {
2124  Msg Error "Cannot run cheby: '$tool' not found or not working: $tool_msg"
2125  return 1
2126  } else {
2127  Msg Warning "Cheby executable '$tool' not found or not working ($tool_msg).\
2128  Will not verify cheby outputs."
2129  return 0
2130  }
2131  }
2132  Msg Info "Using cheby tool: $tool ([string trim $tool_msg])"
2133  if {$cheby_version ne "" && $cheby_sha ne ""} {
2134  Msg Info "Cheby list set version: $cheby_version, SHA: $cheby_sha"
2135  }
2136 
2137  set dst [file normalize $dst]
2138  file mkdir $dst
2139  set tmp_dir [file join $dst _check]
2140  file mkdir $tmp_dir
2141  set inputs_dir [file join $dst inputs]
2142  file mkdir $inputs_dir
2143 
2144  set n_lines 0
2145  set n_processed 0
2146  set n_changed 0
2147  set n_errors 0
2148  set severity [expr {$strict ? "Error" : "CriticalWarning"}]
2149 
2150  foreach chb_file $chb_files {
2151  Msg Info "Processing cheby list file: $chb_file"
2152  set entries [ParseChebyListFile $chb_file]
2153  foreach entry $entries {
2154  incr n_lines
2155  set input_rel [dict get $entry input]
2156  set outputs [dict get $entry outputs]
2157  set props [dict get $entry props]
2158  set line_num [dict get $entry line]
2159  set chb_tail [file tail $chb_file]
2160 
2161  set line_profile [DictGet $props "profile" "all"]
2162  if {$profile ne "all" && $line_profile ne "all" && $line_profile ne $profile} {
2163  if {$verbose} {
2164  Msg Info " Skipping $chb_tail:$line_num (profile='$line_profile')"
2165  }
2166  continue
2167  }
2168 
2169  set abs_input [file normalize "$path/$input_rel"]
2170  if {![file exists $abs_input]} {
2171  Msg $severity "Cheby input not found ($chb_tail:$line_num): $abs_input"
2172  incr n_errors
2173  continue
2174  }
2175 
2176  lassign [BuildChebyCmdArgs $props $outputs] ok gen_map opt_flags
2177  if {$ok != 0} {
2178  Msg $severity "$chb_tail:$line_num: $gen_map"
2179  incr n_errors
2180  continue
2181  }
2182 
2183  # Run cheby from the input directory with relative argv paths so generated
2184  # headers match manual invocations (cheby records sys.argv verbatim).
2185  set cheby_cwd [file dirname $abs_input]
2186  set cmd [list $tool -i [file tail $abs_input]]
2187  foreach f $opt_flags { lappend cmd $f }
2188 
2189  set out_targets [list]
2190  set bad_gen 0
2191  foreach {gen out_rel} $gen_map {
2192  set gen_flag [ChebyGenFlag $gen]
2193  if {$gen_flag eq ""} {
2194  Msg $severity "$chb_tail:$line_num: unknown generator '$gen'"
2195  incr n_errors
2196  set bad_gen 1
2197  break
2198  }
2199  set abs_target [file normalize "$path/$out_rel"]
2200  if {$generate == 1} {
2201  set out_path $abs_target
2202  } else {
2203  set out_path [file join $tmp_dir \
2204  [file rootname [file tail $abs_target]]_${n_lines}_${gen}[file extension $abs_target]]
2205  }
2206  lappend cmd $gen_flag [ChebyRelPath $cheby_cwd $out_path]
2207  lappend out_targets [list $out_rel $abs_target $out_path $gen]
2208  }
2209  if {$bad_gen} { continue }
2210 
2211  foreach t $out_targets {
2212  file mkdir [file dirname [lindex $t 1]]
2213  file mkdir [file dirname [lindex $t 2]]
2214  }
2215 
2216  if {$verbose} {
2217  Msg Info " Running (cwd=$cheby_cwd): [join $cmd { }]"
2218  }
2219 
2220  set saved_pwd [pwd]
2221  cd $cheby_cwd
2222  lassign [ExecuteRetUserEnv {*}$cmd] cret cmsg
2223  cd $saved_pwd
2224  if {$cret != 0} {
2225  Msg $severity "Cheby failed for $input_rel ($chb_tail:$line_num): $cmsg"
2226  incr n_errors
2227  continue
2228  }
2229  incr n_processed
2230 
2231  if {$generate == 1} {
2232  foreach t $out_targets {
2233  Msg Info " Generated: [lindex $t 0]"
2234  incr n_changed
2235  }
2236  } else {
2237  foreach t $out_targets {
2238  set out_rel [lindex $t 0]
2239  set abs_target [lindex $t 1]
2240  set out_path [lindex $t 2]
2241  if {![file exists $abs_target]} {
2242  Msg $severity "Expected cheby output missing: $out_rel ($chb_tail:$line_num)"
2243  incr n_errors
2244  continue
2245  }
2246  if {[FilesAreSemanticallyEqual $out_path $abs_target 1] == 0} {
2247  Msg $severity "Cheby output mismatch: $out_rel does not match what cheby\
2248  would generate from $input_rel ($chb_tail:$line_num).\
2249  Run `Hog/Do cheby <project> -generate` to refresh."
2250  catch { file copy -force $out_path "$dst/diff_[file tail $abs_target]" }
2251  incr n_changed
2252  incr n_errors
2253  } else {
2254  Msg Info " OK: $out_rel matches generator output."
2255  }
2256  }
2257  }
2258 
2259  catch { file copy -force $abs_input [file join $inputs_dir [file tail $abs_input]] }
2260  foreach t $out_targets {
2261  set abs_target [lindex $t 1]
2262  if {[file exists $abs_target]} {
2263  catch { file copy -force $abs_target [file join $dst [file tail $abs_target]] }
2264  }
2265  }
2266  }
2267  }
2268 
2269  catch { file delete -force $tmp_dir }
2270 
2271  set summary "Cheby summary: parsed $n_lines line(s), ran $n_processed cheby invocation(s),\
2272  $n_changed change(s), $n_errors error(s)."
2273  if {$n_errors > 0} {
2274  Msg CriticalWarning $summary
2275  } else {
2276  Msg Info $summary
2277  }
2278  return $n_errors
2279 }
2280 
2281 ## @brief Returns the description from the hog.conf file.
2282 # The description is the comment in the second line stripped of the hashes
2283 # If the description contains the word test, Test or TEST, then "test" is simply returned.
2284 # This is used to avoid printing them in ListProjects unless -all is specified
2285 #
2286 # @param[in] conf_file the path to the hog.conf file
2287 #
2288 proc DescriptionFromConf {conf_file} {
2289  set f [open $conf_file "r"]
2290  set lines [split [read $f] "\n"]
2291  close $f
2292  set second_line [lindex $lines 1]
2293 
2294 
2295  if {![regexp {\#+ *(.+)} $second_line - description]} {
2296  set description ""
2297  }
2298 
2299  if {[regexp -all {test|Test|TEST} $description]} {
2300  set description "test"
2301  }
2302 
2303  return $description
2304 }
2305 
2306 ## @brief Returns the value in a Tcl dictionary corresponding to the chosen key
2307 #
2308 # @param[in] dictName the name of the dictionary
2309 # @param[in] keyName the name of the key
2310 # @param[in] default the default value to be returned if the key is not found (default "")
2311 #
2312 # @return The value in the dictionary corresponding to the provided key
2313 proc DictGet {dictName keyName {default ""}} {
2314  if {[dict exists $dictName $keyName]} {
2315  return [dict get $dictName $keyName]
2316  } else {
2317  return $default
2318  }
2319 }
2320 
2321 ## Sorts a dictionary
2322 #
2323 # @param[in] dict the dictionary
2324 # @param[in] args the arguments to pass to lsort, e.g. -ascii, -dictionary, -decreasing
2325 # @returns a new dictionary with the keys sorted according to the arguments
2326 proc DictSort {dict args} {
2327  set res {}
2328  foreach key [lsort {*}$args [dict keys $dict]] {
2329  dict set res $key [dict get $dict $key]
2330  }
2331  set res
2332 }
2333 
2334 ## @brief Checks the Doxygen version installed in this machine
2335 #
2336 # @param[in] target_version the version required by the current project
2337 #
2338 # @return Returns 1, if the system Doxygen version is greater or equal to the target
2339 proc DoxygenVersion {target_version} {
2340  set ver [split $target_version "."]
2341  set v [Execute doxygen --version]
2342  Msg Info "Found Doxygen version: $v"
2343  set current_ver [split $v ". "]
2344  set target [expr {[lindex $ver 0] * 100000 + [lindex $ver 1] * 100 + [lindex $ver 2]}]
2345  set current [expr {[lindex $current_ver 0] * 100000 + [lindex $current_ver 1] * 100 + [lindex $current_ver 2]}]
2346 
2347  return [expr {$target <= $current}]
2348 }
2349 
2350 ## @brief Handle eos commands
2351 #
2352 # It can be used with lassign like this: lassign [eos <eos command> ] ret result
2353 #
2354 # @param[in] command: the EOS command to be run, e.g. ls, cp, mv, rm
2355 # @param[in] attempt: (default 0) how many times the command should be attempted in case of failure
2356 #
2357 # @returns a list of 2 elements: the return value (0 if no error occurred) and the output of the EOS command
2358 proc eos {command {attempt 1}} {
2359  global env
2360  if {![info exists env(EOS_MGM_URL)]} {
2361  Msg Warning "Environment variable EOS_MGM_URL not set, setting it to default value root://eosuser.cern.ch"
2362  set ::env(EOS_MGM_URL) "root://eosuser.cern.ch"
2363  }
2364  if {$attempt < 1} {
2365  Msg Warning "The value of attempt should be 1 or more, not $attempt, setting it to 1 as default"
2366  set attempt 1
2367  }
2368  for {set i 0} {$i < $attempt} {incr i} {
2369  set ret [catch {exec -ignorestderr eos {*}$command} result]
2370  if {$ret == 0} {
2371  break
2372  } else {
2373  if {$attempt > 1} {
2374  set wait [expr {1 + int(rand() * 29)}]
2375  Msg Warning "Command $command failed ($i/$attempt): $result, trying again in $wait seconds..."
2376  after [expr {$wait * 1000}]
2377  }
2378  }
2379  }
2380  return [list $ret $result]
2381 }
2382 
2383 ## @brief Quote a string for a POSIX shell single-quoted literal.
2384 proc ShellSingleQuote {s} {
2385  return "'[string map {' '\\''} $s]'"
2386 }
2387 
2388 ## @brief Run an external command using the user's shell environment.
2389 #
2390 # Inside Vivado, Tcl's exec can route Python scripts through Vivado's bundled
2391 # Python (missing deps such as PyYAML). Re-run via bash with Vivado Python env
2392 # cleared, and for .py tools call /usr/bin/python3 explicitly.
2393 #
2394 # Optional env HOG_PYTHON overrides the python command (full path or name).
2395 # Important: the bash -c script must be passed as ONE Tcl list element, otherwise
2396 # Tcl word-splits it and bash only runs the first token (e.g. bare `env`).
2397 proc ExecuteRetUserEnv {args} {
2398  global env
2399  if {![IsVivado]} {
2400  return [ExecuteRet {*}$args]
2401  }
2402 
2403  set run_args $args
2404  set tool [lindex $args 0]
2405  if {[regexp {\.py$} $tool]} {
2406  if {[info exists env(HOG_PYTHON)] && $env(HOG_PYTHON) ne ""} {
2407  set py $env(HOG_PYTHON)
2408  } else {
2409  set py /usr/bin/python3
2410  }
2411  set run_args [linsert $args 0 $py]
2412  }
2413 
2414  set quoted [list]
2415  foreach a $run_args {
2416  lappend quoted [ShellSingleQuote $a]
2417  }
2418  set inner [join $quoted { }]
2419 
2420  if {[OS] eq "windows"} {
2421  return [ExecuteRet {*}[list cmd /c $inner]]
2422  }
2423 
2424  # Vivado sets PYTHON/PYTHONPATH/PYTHONHOME to its bundled 3.8.3. Clear them
2425  # and put system bins first so cheby sees system packages (e.g. PyYAML).
2426  set cmd "env -u PYTHONHOME -u PYTHONPATH -u PYTHON \
2427 PATH=/usr/local/bin:/usr/bin:/bin:\$PATH $inner"
2428  return [ExecuteRet {*}[list /bin/bash -c $cmd]]
2429 }
2430 
2431 ## @brief Handle shell commands
2432 #
2433 # It can be used with lassign like this: lassign [Execute <command> ] ret result
2434 #
2435 # @param[in] args: the shell command
2436 #
2437 # @returns the output of the command
2438 proc Execute {args} {
2439  global env
2440  lassign [ExecuteRet {*}$args] ret result
2441  if {$ret != 0} {
2442  Msg Error "Command [join $args] returned error code: $ret"
2443  }
2444 
2445  return $result
2446 }
2447 
2448 
2449 ## @brief Handle shell commands
2450 #
2451 # It can be used with lassign like this: lassign [ExecuteRet <command> ] ret result
2452 #
2453 # @param[in] args: the shell command
2454 #
2455 # @returns a list of 2 elements: the return value (0 if no error occurred) and the output of the command
2456 proc ExecuteRet {args} {
2457  global env
2458  if {[llength $args] == 0} {
2459  Msg CriticalWarning "No argument given"
2460  set ret -1
2461  set result ""
2462  } else {
2463  set ret [catch {exec -ignorestderr {*}$args} result]
2464  }
2465 
2466  return [list $ret $result]
2467 }
2468 
2469 ## @brief Extract the [files] section from a sim list file
2470 #
2471 # @param[in] the content of the simulation list file to extract the [files] section from
2472 # @returns a list of files in the [files] section, or all lines if no [files] section is found
2473 proc ExtractFilesSection {file_data} {
2474  set in_files_section 0
2475  set result {}
2476 
2477  foreach line $file_data {
2478  if {[regexp {^ *\[ *files *\]} $line]} {
2479  set in_files_section 1
2480  continue
2481  }
2482  if {$in_files_section} {
2483  if {[regexp {^ *\[.*\]} $line]} {
2484  break
2485  }
2486  lappend result $line
2487  }
2488  }
2489 
2490  # If [files] was not found, return all file_data
2491  if {!$in_files_section} {
2492  return $file_data
2493  } else {
2494  return $result
2495  }
2496 }
2497 
2498 
2499 ## @brief Tags the repository with a new version calculated on the basis of the previous tags
2500 #
2501 # @param[in] tag a tag in the Hog format: v$M.$m.$p or b$(mr)v$M.$m.$p-$n
2502 #
2503 # @return a list containing: Major minor patch v.
2504 #
2505 proc ExtractVersionFromTag {tag} {
2506  if {[regexp {^(?:b(\d+))?v0*(\d+)\.0*(\d+).0*(\d+)(?:-\d+)?$} $tag -> mr M m p]} {
2507  if {$mr eq ""} {
2508  set mr 0
2509  }
2510  } else {
2511  Msg Warning "Repository tag $tag is not in a Hog-compatible format."
2512  set mr -1
2513  set M -1
2514  set m -1
2515  set p -1
2516  }
2517  return [list $M $m $p $mr]
2518 }
2519 
2520 
2521 ## @brief Checks if file was committed into the repository
2522 #
2523 #
2524 # @param[in] File: file name
2525 #
2526 # @returns 1 if file was committed and 0 if file was not committed
2527 proc FileCommitted {File} {
2528  set Ret 1
2529  set currentDir [pwd]
2530  cd [file dirname [file normalize $File]]
2531  set GitLog [Git ls-files [file tail $File]]
2532  if {$GitLog == ""} {
2533  Msg CriticalWarning "File [file normalize $File] is not in the git repository. Please add it with:\n git add [file normalize $File]\n"
2534  set Ret 0
2535  }
2536  cd $currentDir
2537  return $Ret
2538 }
2539 
2540 # @brief Returns the common child of two git commits
2541 #
2542 # @param[in] SHA1 The first commit
2543 # @param[in] SHA2 The second commit
2544 proc FindCommonGitChild {SHA1 SHA2} {
2545  # Get the list of all commits in the repository
2546  set commits [Git {log --oneline --merges}]
2547  set ancestor 0
2548  # Iterate over each commit
2549  foreach line [split $commits "\n"] {
2550  set commit [lindex [split $line] 0]
2551 
2552  # Check if both SHA1 and SHA2 are ancestors of the commit
2553  if {[IsCommitAncestor $SHA1 $commit] && [IsCommitAncestor $SHA2 $commit]} {
2554  set ancestor $commit
2555  break
2556  }
2557  }
2558  return $ancestor
2559 }
2560 
2561 
2562 # @brief Returns a list of files in a directory matching a pattern
2563 #
2564 # @param[in] basedir The directory to start looking in
2565 # @param[in pattern A pattern, as defined by the glob command, that the files must match
2566 # Credit: https://stackexchange.com/users/14219/jackson
2567 proc findFiles {basedir pattern} {
2568  # Fix the directory name, this ensures the directory name is in the
2569  # native format for the platform and contains a final directory seperator
2570  set basedir [string trimright [file join [file normalize $basedir] { }]]
2571  set fileList {}
2572 
2573  # Look in the current directory for matching files, -type {f r}
2574  # means ony readable normal files are looked at, -nocomplain stops
2575  # an error being thrown if the returned list is empty
2576  foreach fileName [glob -nocomplain -type {f r} -path $basedir $pattern] {
2577  lappend fileList $fileName
2578  }
2579 
2580  # Now look for any sub direcories in the current directory
2581  foreach dirName [glob -nocomplain -type {d r} -path $basedir *] {
2582  # Recusively call the routine on the sub directory and append any
2583  # new files to the results
2584  set subDirList [findFiles $dirName $pattern]
2585  if {[llength $subDirList] > 0} {
2586  foreach subDirFile $subDirList {
2587  lappend fileList $subDirFile
2588  }
2589  }
2590  }
2591  return $fileList
2592 }
2593 
2594 ## @brief determine file type from extension
2595 # Used only for Quartus
2596 #
2597 ## @return FILE_TYPE the file Type
2598 proc FindFileType {file_name} {
2599  set extension [file extension $file_name]
2600  switch $extension {
2601  .stp {
2602  set file_extension "USE_SIGNALTAP_FILE"
2603  }
2604  .vhd {
2605  set file_extension "VHDL_FILE"
2606  }
2607  .vhdl {
2608  set file_extension "VHDL_FILE"
2609  }
2610  .v {
2611  set file_extension "VERILOG_FILE"
2612  }
2613  .sv {
2614  set file_extension "SYSTEMVERILOG_FILE"
2615  }
2616  .sdc {
2617  set file_extension "SDC_FILE"
2618  }
2619  .pdc {
2620  set file_extension "PDC_FILE"
2621  }
2622  .ndc {
2623  set file_extension "NDC_FILE"
2624  }
2625  .fdc {
2626  set file_extension "FDC_FILE"
2627  }
2628  .qsf {
2629  set file_extension "SOURCE_FILE"
2630  }
2631  .ip {
2632  set file_extension "IP_FILE"
2633  }
2634  .qsys {
2635  set file_extension "QSYS_FILE"
2636  }
2637  .qip {
2638  set file_extension "QIP_FILE"
2639  }
2640  .sip {
2641  set file_extension "SIP_FILE"
2642  }
2643  .bsf {
2644  set file_extension "BSF_FILE"
2645  }
2646  .bdf {
2647  set file_extension "BDF_FILE"
2648  }
2649  .tcl {
2650  set file_extension "COMMAND_MACRO_FILE"
2651  }
2652  .vdm {
2653  set file_extension "VQM_FILE"
2654  }
2655  default {
2656  set file_extension "ERROR"
2657  Msg Error "Unknown file extension $extension"
2658  }
2659  }
2660  return $file_extension
2661 }
2662 
2663 
2664 # @brief Returns the newest version in a list of versions
2665 #
2666 # @param[in] versions The list of versions
2667 proc FindNewestVersion {versions} {
2668  set new_ver 00000000
2669  foreach ver $versions {
2670  # tclint-disable-next-line redundant-expr
2671  if {[expr 0x$ver > 0x$new_ver]} {
2672  set new_ver $ver
2673  }
2674  }
2675  return $new_ver
2676 }
2677 
2678 # Find repo root by walking up from a start dir until we see Top/ and Projects/.
2679 # For absolute paths we do not normalize, so the path form is preserved and [file exists]
2680 # sees the same view as the script was loaded from.
2681 proc FindRepoRoot {start_dir} {
2682  if {[file pathtype $start_dir] eq "relative"} {
2683  set dir [file normalize [file join [pwd] $start_dir]]
2684  } else {
2685  set dir $start_dir
2686  }
2687  while {1} {
2688  if {[file exists [file join $dir Top]] && [file exists [file join $dir Projects]]} {
2689  return $dir
2690  }
2691  set parent [file dirname $dir]
2692  if {$parent eq $dir} {
2693  return ""
2694  }
2695  set dir $parent
2696  }
2697 }
2698 
2699 ## @brief Set VHDL version to 2008 for *.vhd files
2700 #
2701 # @param[in] file_name the name of the HDL file
2702 #
2703 # @return "-hdl_version VHDL_2008" if the file is a *.vhd files else ""
2704 proc FindVhdlVersion {file_name} {
2705  set extension [file extension $file_name]
2706  switch $extension {
2707  .vhd {
2708  set vhdl_version "-hdl_version VHDL_2008"
2709  }
2710  .vhdl {
2711  set vhdl_version "-hdl_version VHDL_2008"
2712  }
2713  default {
2714  set vhdl_version ""
2715  }
2716  }
2717 
2718  return $vhdl_version
2719 }
2720 
2721 ## @brief Format a generic to a 32 bit verilog style hex number, e.g.
2722 # take in ea8394c and return 32'h0ea8394c
2723 #
2724 # @param[in] unformatted generic
2725 proc FormatGeneric {generic} {
2726  if {[string is integer "0x$generic"]} {
2727  return [format "32'h%08X" "0x$generic"]
2728  } else {
2729  # for non integers (e.g. blanks) just return 0
2730  return [format "32'h%08X" 0]
2731  }
2732 }
2733 
2734 # @brief Generate the bitstream
2735 #
2736 # @param[in] project_name The name of the project
2737 # @param[in] run_folder The path where to run the implementation
2738 # @param[in] repo_path The main path of the git repository
2739 # @param[in] njobs The number of CPU jobs to run in parallel
2740 proc GenerateBitstream {{run_folder ""} {repo_path .} {njobs 1}} {
2741  Msg Info "Starting write bitstream flow..."
2742  if {[IsQuartus]} {
2743  set revision [get_current_revision]
2744  if {[catch {execute_module -tool asm} result]} {
2745  Msg Error "Result: $result\n"
2746  Msg Error "Generate bitstream failed. See the report file.\n"
2747  } else {
2748  Msg Info "Generate bitstream was successful for revision $revision.\n"
2749  }
2750  } elseif {[IsLibero]} {
2751  Msg Info "Run GENERATEPROGRAMMINGDATA ..."
2752  if {[catch {run_tool -name {GENERATEPROGRAMMINGDATA}}]} {
2753  Msg Error "GENERATEPROGRAMMINGDATA FAILED!"
2754  } else {
2755  Msg Info "GENERATEPROGRAMMINGDATA PASSED."
2756  }
2757  Msg Info "Sourcing Hog/Tcl/integrated/post-bitstream.tcl"
2758  source $repo_path/Hog/Tcl/integrated/post-bitstream.tcl
2759  } elseif {[IsDiamond]} {
2760  prj_run Export -impl Implementation0 -task Bitgen
2761  }
2762 }
2763 
2764 ## @brief Function used to generate a qsys system from a .qsys file.
2765 # The procedure adds the generated IPs to the project.
2766 #
2767 # @param[in] qsysFile the Intel Platform Designed file (.qsys), containing the system to be generated
2768 # @param[in] commandOpts the command options to be used during system generation as they are in qsys-generate options
2769 #
2770 proc GenerateQsysSystem {qsysFile commandOpts} {
2771  global env
2772  if {[file exists $qsysFile] != 0} {
2773  set qsysPath [file dirname $qsysFile]
2774  set qsysName [file rootname [file tail $qsysFile]]
2775  set qsysIPDir "$qsysPath/$qsysName"
2776  set qsysLogFile "$qsysPath/$qsysName.qsys-generate.log"
2777 
2778  set qsys_rootdir ""
2779  if {![info exists ::env(QSYS_ROOTDIR)]} {
2780  if {[info exists ::env(QUARTUS_ROOTDIR)]} {
2781  set qsys_rootdir "$::env(QUARTUS_ROOTDIR)/sopc_builder/bin"
2782  Msg Warning "The QSYS_ROOTDIR environment variable is not set! I will use $qsys_rootdir"
2783  } else {
2784  Msg CriticalWarning "The QUARTUS_ROOTDIR environment variable is not set! Assuming all quartus executables are contained in your PATH!"
2785  }
2786  } else {
2787  set qsys_rootdir $::env(QSYS_ROOTDIR)
2788  }
2789 
2790  set cmd "$qsys_rootdir/qsys-generate"
2791  set cmd_options "$qsysFile --output-directory=$qsysIPDir $commandOpts"
2792  if {![catch {"exec $cmd -version"}] || [lindex $::errorCode 0] eq "NONE"} {
2793  Msg Info "Executing: $cmd $cmd_options"
2794  Msg Info "Saving logfile in: $qsysLogFile"
2795  if {[catch {eval exec -ignorestderr "$cmd $cmd_options >>& $qsysLogFile"} ret opt]} {
2796  set makeRet [lindex [dict get $opt -errorcode] end]
2797  Msg CriticalWarning "$cmd returned with $makeRet"
2798  }
2799  } else {
2800  Msg Error " Could not execute command $cmd"
2801  exit 1
2802  }
2803  #Add generated IPs to project
2804  set qsysIPFileList [concat \
2805  [glob -nocomplain -directory $qsysIPDir -types f *.ip *.qip] \
2806  [glob -nocomplain -directory "$qsysIPDir/synthesis" -types f *.ip *.qip *.vhd *.vhdl]]
2807  foreach qsysIPFile $qsysIPFileList {
2808  if {[file exists $qsysIPFile] != 0} {
2809  set qsysIPFileType [FindFileType $qsysIPFile]
2810  set_global_assignment -name $qsysIPFileType $qsysIPFile
2811  # Write checksum to file
2812  set IpMd5Sum [Md5Sum $qsysIPFile]
2813  # open file for writing
2814  set fileDir [file normalize "./hogTmp"]
2815  set fileName "$fileDir/.hogQsys.md5"
2816  if {![file exists $fileDir]} {
2817  file mkdir $fileDir
2818  }
2819  set hogQsysFile [open $fileName "a"]
2820  set fileEntry "$qsysIPFile\t$IpMd5Sum"
2821  puts $hogQsysFile $fileEntry
2822  close $hogQsysFile
2823  }
2824  }
2825  } else {
2826  Msg ERROR "Error while generating ip variations from qsys: $qsysFile not found!"
2827  }
2828 }
2829 
2830 
2831 ## Format generics from conf file to string that simulators accepts
2832 #
2833 # @param[in] dict containing generics from conf file
2834 # @param[in] target: software target(vivado, questa)
2835 # defines the output format of the string
2836 proc GenericToSimulatorString {prop_dict target} {
2837  set prj_generics ""
2838  dict for {theKey theValue} $prop_dict {
2839  set theValue [string trim $theValue]
2840  set valueHexFull ""
2841  set valueNumBits ""
2842  set valueHexFlag ""
2843  set valueHex ""
2844  set valueIntFull ""
2845  set ValueInt ""
2846  set valueStrFull ""
2847  set ValueStr ""
2848  regexp {([0-9]*)('h)([0-9a-fA-F]*)} $theValue valueHexFull valueNumBits valueHexFlag valueHex
2849  regexp {^([0-9]*)$} $theValue valueIntFull ValueInt
2850  regexp {(?!^\d+$)^.+$} $theValue valueStrFull ValueStr
2851  if {[string tolower $target] == "vivado" || [string tolower $target] == "xsim"} {
2852  if {[string tolower $theValue] == "true" || [string tolower $theValue] == "false"} {
2853  set prj_generics "$prj_generics $theKey=[string tolower $theValue]"
2854  } elseif {$valueNumBits != "" && $valueHexFlag != "" && $valueHex != ""} {
2855  set prj_generics "$prj_generics $theKey=$valueHexFull"
2856  } elseif {$valueIntFull != "" && $ValueInt != ""} {
2857  set prj_generics "$prj_generics $theKey=$ValueInt"
2858  } elseif {$valueStrFull != "" && $ValueStr != ""} {
2859  set prj_generics "$prj_generics $theKey=\"$ValueStr\""
2860  } else {
2861  set prj_generics "$prj_generics $theKey=\"$theValue\""
2862  }
2863  } elseif {[lsearch -exact [GetSimulators] [string tolower $target]] >= 0} {
2864  if {$valueNumBits != "" && $valueHexFlag != "" && $valueHex != ""} {
2865  set numBits 0
2866  scan $valueNumBits %d numBits
2867  set numHex 0
2868  scan $valueHex %x numHex
2869  binary scan [binary format "I" $numHex] "B*" binval
2870  set numBits [expr {$numBits - 1}]
2871  set numBin [string range $binval end-$numBits end]
2872  set prj_generics "$prj_generics $theKey=\"$numBin\""
2873  } elseif {$valueIntFull != "" && $ValueInt != ""} {
2874  set prj_generics "$prj_generics $theKey=$ValueInt"
2875  } elseif {$valueStrFull != "" && $ValueStr != ""} {
2876  set prj_generics "$prj_generics {$theKey=\"$ValueStr\"}"
2877  } else {
2878  set prj_generics "$prj_generics {$theKey=\"$theValue\"}"
2879  }
2880  } else {
2881  Msg Warning "Target : $target not implemented"
2882  }
2883  }
2884  return $prj_generics
2885 }
2886 
2887 ## Get the configuration files to create a Hog project
2888 #
2889 # @param[in] proj_dir: The project directory containing the conf file or the the tcl file
2890 #
2891 # @return[in] the paths of hog.conf, sim.conf, pre-creation.tcl, post-creation.tcl,
2892 # pre-rtl.tcl and post-rtl.tcl,
2893 # followed by path patterns for all project pre/post hooks
2894 proc GetConfFiles {proj_dir} {
2895  Msg Debug "GetConfFiles called with proj_dir=$proj_dir"
2896  if {![file isdirectory $proj_dir]} {
2897  Msg Error "$proj_dir is supposed to be the top project directory"
2898  return -1
2899  }
2900  set conf_file [file normalize $proj_dir/hog.conf]
2901  set sim_file [file normalize $proj_dir/sim.conf]
2902  set pre_tcl [file normalize $proj_dir/pre-creation.tcl]
2903  set post_tcl [file normalize $proj_dir/post-creation.tcl]
2904  set pre_rtl [file normalize $proj_dir/pre-rtl.tcl]
2905  set post_rtl [file normalize $proj_dir/post-rtl.tcl]
2906 
2907  # Include all project hooks in version tracking, including deleted hooks.
2908  return [list $conf_file $sim_file $pre_tcl $post_tcl $pre_rtl $post_rtl \
2909  [file normalize $proj_dir/pre-*.tcl] \
2910  [file normalize $proj_dir/post-*.tcl]]
2911 }
2912 
2913 
2914 # Searches directory for tcl scripts to add as custom commands to launch.tcl
2915 # Returns string of tcl scripts formatted as usage or switch statement
2916 #
2917 # @param[in] directory The directory where to look for custom tcl scripts (Default .)
2918 # @param[in] ret_commands if 1 returns commands as switch statement string instead of usage (Default 0)
2919 proc GetCustomCommands {parameters {directory .}} {
2920  set commands_dict [dict create]
2921  set commands_files [glob -nocomplain $directory/*.tcl]
2922 
2923  if {[llength $commands_files] == 0} {
2924  return ""
2925  }
2926 
2927  foreach file $commands_files {
2928  #Msg Info "do compile libe? $do_compile_lib"
2929  set custom_cmd [LoadCustomCommandFile $file $parameters]
2930 
2931  if {$custom_cmd eq ""} {
2932  continue
2933  }
2934 
2935  #Msg Info "Validating custom command $custom_cmd"
2936  set custom_cmd_name [dict get $custom_cmd NAME]
2937 
2938  Msg Debug "Loaded custom command '$custom_cmd_name' from $file"
2939 
2940  #Ensure command is not already defined
2941  if {[dict exists $commands_dict $custom_cmd_name]} {
2942  Msg Error "Custom command '$custom_cmd_name' in $file already defined as: \[dict get $commands_dict $custom_cmd_name\]. Skipping."
2943  continue
2944  }
2945 
2946 
2947  set custom_cmd_name [string toupper $custom_cmd_name]
2948  dict set commands_dict $custom_cmd_name $custom_cmd
2949  }
2950 
2951  return $commands_dict
2952 }
2953 
2954 proc SanitizeCustomCommand {cmdDict file parameters} {
2955  # Normalize all user-provided keys to uppercase so NAME/DESCRIPTION/etc are case-insensitive.
2956 
2957 
2958  set normalized {}
2959  foreach k [dict keys $cmdDict] {
2960  set K [string toupper $k]
2961  dict set normalized $K [dict get $cmdDict $k]
2962  }
2963 
2964  set cmdDict $normalized
2965  if {![dict exists $cmdDict NAME]} {
2966  Msg Error "Custom command in $file missing required key NAME. Skipping."
2967  return ""
2968  }
2969  if {![dict exists $cmdDict SCRIPT]} {
2970  Msg Error "Custom command '$[dict get $cmdDict NAME]' in $file missing SCRIPT. Skipping."
2971  return ""
2972  }
2973 
2974  # Allowed keys (uppercased). IDE is optional and will be validated if present.
2975  set allowed {NAME DESCRIPTION OPTIONS CUSTOM_OPTIONS SCRIPT IDE NO_EXIT}
2976  foreach k [dict keys $cmdDict] {
2977  if {[lsearch -exact $allowed $k] < 0} {
2978  Msg Warning "Custom command '[dict get $cmdDict NAME]' in $file: unknown key '$k'. Allowed: $allowed. Skipping."
2979  }
2980  }
2981 
2982  # NAME
2983  set name [string trim [dict get $cmdDict NAME]]
2984  if {$name eq ""} {
2985  Msg Error "Custom command in $file has empty NAME. Skipping."
2986  return ""
2987  }
2988 
2989  if {![regexp {^[a-zA-Z][a-zA-Z0-9_]+$} $name]} {
2990  Msg Error "Custom command NAME '$name' (file $file) contains invalid characters."
2991  }
2992 
2993  # DESCRIPTION
2994  if {![dict exists $cmdDict DESCRIPTION]} {
2995  dict set cmdDict DESCRIPTION "No description provided."
2996  }
2997 
2998 
2999  set hog_parameters {}
3000  foreach p $parameters {
3001  lappend hog_parameters [lindex $p 0]
3002  }
3003 
3004  # OPTIONS
3005  set hog_options {}
3006  if {[dict exists $cmdDict OPTIONS]} {
3007  set raw_opts [dict get $cmdDict OPTIONS]
3008  if {![llength $raw_opts]} {
3009  set raw_opts {}
3010  }
3011 
3012  foreach item $raw_opts {
3013  set found 0
3014  foreach p $parameters {
3015  set hog_parameter [lindex $p 0]
3016  if {$item eq $hog_parameter} {
3017  lappend hog_options $p
3018  set found 1
3019  break
3020  }
3021  }
3022  if {!$found} {
3023  Msg Warning "Custom command '$name' in $file: option '$item' not found in Hog parameters. Skipping."
3024  }
3025  }
3026  dict set cmdDict OPTIONS $hog_options
3027  } else {
3028  dict set cmdDict OPTIONS {}
3029  }
3030 
3031 
3032  # CUSTOM_OPTIONS
3033  set opt_defs {}
3034  if {[dict exists $cmdDict CUSTOM_OPTIONS]} {
3035  set raw_opts [dict get $cmdDict CUSTOM_OPTIONS]
3036  if {![llength $raw_opts]} {
3037  set raw_opts {}
3038  }
3039  foreach item $raw_opts {
3040  if {[llength $item] != 2 && [llength $item] != 3} {
3041  Msg Error "Bad custom option: \[$item\]. Custom command '$name' in $file: \
3042  each CUSTOM_OPTIONS entry must be {option \"help\"} for flags \
3043  and {option \"default_value\" \"help\"} for options with arguments. Skipping command."
3044  return ""
3045  }
3046 
3047  if {[llength $item] == 2} {
3048  lassign $item opt help
3049  set def ""
3050  } else {
3051  lassign $item opt def help
3052  }
3053 
3054  if {[IsInList $opt $hog_parameters] == 1} {
3055  Msg Warning "Custom command '$name' in $file: option '$opt' already defined in Hog parameters. Skipping."
3056  continue
3057  }
3058 
3059 
3060  #optional .arg in option regex
3061  if {![regexp {^[a-zA-Z][a-zA-Z0-9_]*(\.arg)?$} $opt]} {
3062  Msg Error "Custom command '$name' in $file: invalid option name '$opt'."
3063  return ""
3064  }
3065 
3066  if {$help eq ""} {
3067  Msg Warning "Custom command '$name' option '$opt' has empty help text."
3068  }
3069  }
3070  } else {
3071  dict set cmdDict CUSTOM_OPTIONS {}
3072  }
3073 
3074  # NO EXIT
3075  if {[dict exists $cmdDict NO_EXIT]} {
3076  set no_exit [dict get $cmdDict NO_EXIT]
3077  set no_exit [string tolower [string trim $no_exit]]
3078 
3079  if {$no_exit eq "1" || $no_exit eq "true"} {
3080  set no_exit 1
3081  } else {
3082  set no_exit 0
3083  }
3084 
3085  dict set cmdDict NO_EXIT $no_exit
3086  } else {
3087  dict set cmdDict NO_EXIT 0
3088  }
3089 
3090  return $cmdDict
3091 }
3092 
3093 proc LoadCustomCommandFile {file parameters} {
3094  set saved_pwd [pwd]
3095  set dir [file dirname $file]
3096  cd $dir
3097  unset -nocomplain ::hog_command
3098  set rc [catch {source $file} err]
3099  cd $saved_pwd
3100  if {$rc} {
3101  Msg Error "Error sourcing custom command file $file: $err"
3102  return ""
3103  }
3104  if {![info exists ::hog_command]} {
3105  Msg Warning "File $file did not define ::hog_command. Skipping."
3106  return ""
3107  }
3108  set cmdDict $::hog_command
3109  # Ensure it's a dict
3110  if {[catch {dict size $cmdDict}]} {
3111  Msg Error "In $file ::hog_command is not a valid dict. Skipping."
3112  return ""
3113  }
3114  return [SanitizeCustomCommand $cmdDict $file $parameters]
3115 }
3116 
3117 
3118 ## Get the Date and time of a commit (or current time if Git < 2.9.3)
3119 #
3120 # @param[in] commit The commit
3121 proc GetDateAndTime {commit} {
3122  set clock_seconds [clock seconds]
3123 
3124  if {[GitVersion 2.9.3]} {
3125  set date [Git "log -1 --format=%cd --date=format:%d%m%Y $commit"]
3126  set timee [Git "log -1 --format=%cd --date=format:00%H%M%S $commit"]
3127  } else {
3128  Msg Warning "Found Git version older than 2.9.3. Using current date and time instead of commit time."
3129  set date [clock format $clock_seconds -format {%d%m%Y}]
3130  set timee [clock format $clock_seconds -format {00%H%M%S}]
3131  }
3132  return [list $date $timee]
3133 }
3134 
3135 ## @brief Gets a list of files contained in the current fileset that match a file name (passed as parameter)
3136 #
3137 # The file name is matched against the input parameter.
3138 #
3139 # @param[in] file name (or part of it)
3140 # @param[in] fileset name
3141 #
3142 # @return a list of files matching the parameter in the chosen fileset
3143 #
3144 proc GetFile {file fileset} {
3145  if {[IsXilinx]} {
3146  # Vivado
3147  set Files [get_files -all $file -of_object [get_filesets $fileset]]
3148  set f [lindex $Files 0]
3149 
3150  return $f
3151  } elseif {[IsQuartus]} {
3152  # Quartus
3153  return ""
3154  } else {
3155  # Tcl Shell
3156  puts "***DEBUG Hog:GetFile $file"
3157  return "DEBUG_file"
3158  }
3159 }
3160 
3161 ## @brief Extract the generics from a file
3162 #
3163 # @param[in] filename The file from which to extract the generics
3164 # @param[in] entity The entity in the file from which to extract the generics (default "")
3165 proc GetFileGenerics {filename {entity ""}} {
3166  set file_type [FindFileType $filename]
3167  if {[string equal $file_type "VERILOG_FILE"] || [string equal $file_type "SYSTEMVERILOG_FILE"]} {
3168  return [GetVerilogGenerics $filename]
3169  } elseif {[string equal $file_type "VHDL_FILE"]} {
3170  return [GetVhdlGenerics $filename $entity]
3171  } else {
3172  Msg CriticalWarning "Could not determine extension of top level file."
3173  }
3174 }
3175 
3176 ## @brief Returns the list of Hog-managed generic base names (without prefix)
3177 proc HogGenericBaseNames {} {
3178  return [list \
3179  GLOBAL_DATE GLOBAL_TIME GLOBAL_VER GLOBAL_SHA \
3180  TOP_SHA TOP_VER HOG_SHA HOG_VER \
3181  CON_VER CON_SHA XML_VER XML_SHA FLAVOUR]
3182 }
3183 
3184 ## @brief Extracts and validates the Hog generic prefix from an already-parsed
3185 # hog.conf properties dictionary
3186 #
3187 # @param[in] properties The dictionary returned by ReadConf
3188 # @return Prefix string, or empty if not set/invalid
3189 proc GetHogGenericPrefixFromDict {properties} {
3190  set prefix [string trim [DictGet [DictGet $properties hog] HOG_GENERIC_PREFIX ""]]
3191 
3192  if {$prefix ne "" && ![regexp {^[A-Za-z_][A-Za-z0-9_]*$} $prefix]} {
3193  Msg Warning "HOG_GENERIC_PREFIX '$prefix' contains invalid characters. Ignoring prefix."
3194  return ""
3195  }
3196 
3197  return $prefix
3198 }
3199 
3200 ## @brief Returns the optional Hog generic prefix from hog.conf
3201 #
3202 # @param[in] proj_dir Project path relative to Top/ (e.g. group/project)
3203 # @param[in] repo_path Optional repository root path (default: current directory)
3204 # @return Prefix string, or empty if not set
3205 proc GetHogGenericPrefix {proj_dir {repo_path ""}} {
3206  if {$repo_path ne ""} {
3207  set conf_file [file normalize "$repo_path/Top/$proj_dir/hog.conf"]
3208  } else {
3209  set conf_file [file normalize "Top/$proj_dir/hog.conf"]
3210  }
3211 
3212  if {![file exists $conf_file]} {
3213  return ""
3214  }
3215 
3216  set properties [ReadConf $conf_file]
3217  return [GetHogGenericPrefixFromDict $properties]
3218 }
3219 
3220 ## @brief Applies the Hog generic prefix to a base generic name
3221 #
3222 # @param[in] base_name Generic name without prefix
3223 # @param[in] prefix Prefix from hog.conf
3224 # @return Prefixed generic name
3225 proc HogGenericName {base_name {prefix ""}} {
3226  if {$prefix eq ""} {
3227  return $base_name
3228  }
3229  return "${prefix}${base_name}"
3230 }
3231 
3232 ## @brief Checks if a generic is managed by Hog (optionally with prefix)
3233 #
3234 # @param[in] name Generic name as set in the project
3235 # @param[in] prefix Optional Hog generic prefix from hog.conf
3236 # @return 1 if Hog-managed, 0 otherwise
3237 proc IsHogManagedGeneric {name {prefix ""}} {
3238  set upper_name [string toupper $name]
3239  set base_name $upper_name
3240 
3241  if {$prefix ne ""} {
3242  set prefix_upper [string toupper $prefix]
3243  if {[string match "${prefix_upper}*" $upper_name]} {
3244  set base_name [string range $upper_name [string length $prefix_upper] end]
3245  }
3246  }
3247 
3248  if {$base_name in [HogGenericBaseNames]} {
3249  return 1
3250  }
3251 
3252  if {[regexp {_VER$|_SHA$} $base_name]} {
3253  return 1
3254  }
3255 
3256  return 0
3257 }
3258 
3259 ## @brief Gets custom generics from hog
3260 #
3261 # @param[in] proj_dir: the top folder of the project
3262 # @return dict with generics
3263 #
3264 proc GetGenericsFromConf {proj_dir} {
3265  set generics_dict [dict create]
3266  set top_dir "Top/$proj_dir"
3267  set conf_file "$top_dir/hog.conf"
3268  set conf_index 0
3269  Msg Debug "GetGenericsFromConf called with proj_dir=$proj_dir, top_dir=$top_dir"
3270 
3271  if {[file exists $conf_file]} {
3272  set properties [ReadConf [lindex [GetConfFiles $top_dir] $conf_index]]
3273  if {[dict exists $properties generics]} {
3274  set generics_dict [dict get $properties generics]
3275  }
3276  } else {
3277  Msg Warning "File $conf_file not found."
3278  }
3279  return $generics_dict
3280 }
3281 
3282 ## @brief Gets custom Verilog `define macros from hog.conf
3283 #
3284 # @param[in] proj_dir: the top folder of the project
3285 # @return dict with defines
3286 #
3287 proc GetDefinesFromConf {proj_dir} {
3288  set defines_dict [dict create]
3289  set top_dir "Top/$proj_dir"
3290  set conf_file "$top_dir/hog.conf"
3291  set conf_index 0
3292  Msg Debug "GetDefinesFromConf called with proj_dir=$proj_dir, top_dir=$top_dir"
3293 
3294  if {[file exists $conf_file]} {
3295  set properties [ReadConf [lindex [GetConfFiles $top_dir] $conf_index]]
3296  if {[dict exists $properties defines]} {
3297  set defines_dict [dict get $properties defines]
3298  }
3299  } else {
3300  Msg Warning "File $conf_file not found."
3301  }
3302  return $defines_dict
3303 }
3304 
3305 ## @brief Gets the simulation sets from the project
3306 #
3307 # @param[in] project_name: the name of the project
3308 # @param[in] repo_path: the path to the repository
3309 # @param[in] simsets: a list of simulation sets to retrieve (default: all)
3310 # @param[in] ghdl: if 1, only GHDL simulation sets are returned (default: 0),
3311 # otherwise only non-GHDL simulation sets are returned
3312 # @param[in] no_conf: if 1, the simulation sets are returned without reading the sim.conf file (default: 0)
3313 # @return a dictionary with the simulation sets, where the keys are the simulation set names
3314 # and the values are dictionaries with the properties of each simulation set
3315 proc GetSimSets {project_name repo_path {simsets ""} {ghdl 0} {no_conf 0}} {
3316  set simsets_dict [dict create]
3317  set list_dir "$repo_path/Top/$project_name/list"
3318  set list_files []
3319  if {$simsets != ""} {
3320  foreach s $simsets {
3321  set list_file "$list_dir/$s.sim"
3322  if {[file exists $list_file]} {
3323  lappend list_files $list_file
3324  } elseif {$s != "sim_1"} {
3325  Msg CriticalWarning "Simulation set list file $list_file not found."
3326  return ""
3327  }
3328  }
3329  } else {
3330  set list_files [glob -nocomplain -directory $list_dir "*.sim"]
3331  }
3332 
3333  # Get simulation properties from conf file
3334  set proj_dir [file normalize $repo_path/Top/$project_name]
3335  set sim_file [file normalize $proj_dir/sim.conf]
3336 
3337  foreach list_file $list_files {
3338  set file_name [file tail $list_file]
3339  set simset_name [file rootname $file_name]
3340  set fp [open $list_file r]
3341  set file_data [read $fp]
3342  close $fp
3343  set data [split $file_data "\n"]
3344 
3345  set firstline [lindex $data 0]
3346  # Find simulator
3347  if {[regexp {^ *\# *Simulator} $firstline]} {
3348  set simulator_prop [regexp -all -inline {\S+} $firstline]
3349  set simulator [string tolower [lindex $simulator_prop end]]
3350  } else {
3351  Msg Warning "Simulator not set in $simset_name.sim. \
3352  The first line of $simset_name.sim should be #Simulator <SIMULATOR_NAME>,\
3353  where <SIMULATOR_NAME> can be xsim, questa, modelsim, ghdl, riviera, activehdl,\
3354  ies, or vcs, e.g. #Simulator questa.\
3355  Setting simulator by default to xsim."
3356  set simulator "xsim"
3357  }
3358  if {$simulator eq "skip_simulation"} {
3359  Msg Info "Skipping simulation for $simset_name"
3360  continue
3361  }
3362  if {($ghdl == 1 && $simulator != "ghdl") || ($ghdl == 0 && $simulator == "ghdl")} {
3363  continue
3364  }
3365 
3366  set SIM_PROPERTIES ""
3367  if {[file exists $sim_file] && $no_conf == 0} {
3368  set SIM_PROPERTIES [ReadConf $sim_file]
3369  }
3370 
3371  set global_sim_props [dict create]
3372  dict set global_sim_props "properties" [DictGet $SIM_PROPERTIES "sim"]
3373  dict set global_sim_props "generics" [DictGet $SIM_PROPERTIES "generics"]
3374  dict set global_sim_props "hog" [DictGet $SIM_PROPERTIES "hog"]
3375 
3376 
3377  set sim_dict [dict create]
3378  dict set sim_dict "simulator" $simulator
3379  if {[dict exists $SIM_PROPERTIES $simset_name]} {
3380  dict set sim_dict "properties" [DictGet $SIM_PROPERTIES $simset_name]
3381  dict set sim_dict "generics" [DictGet $SIM_PROPERTIES "$simset_name:generics"]
3382  dict set sim_dict "hog" [DictGet $SIM_PROPERTIES "$simset_name:hog"]
3383  } elseif {$no_conf == 0} {
3384  # Retrieve properties from .sim file
3385  set conf_dict [ReadConf $list_file]
3386  set sim_dict [MergeDict $sim_dict $conf_dict 0]
3387  }
3388  set sim_dict [MergeDict $sim_dict $global_sim_props 0]
3389  dict set simsets_dict $simset_name $sim_dict
3390  }
3391  return $simsets_dict
3392 }
3393 
3394 ## @brief Gets all custom <simset>:generics from sim.conf
3395 #
3396 # @param[in] proj_dir: the top folder of the project
3397 # @return nested dict with all <simset>:generics
3398 #
3399 proc GetSimsetGenericsFromConf {proj_dir} {
3400  set simsets_generics_dict [dict create]
3401  set top_dir "Top/$proj_dir"
3402  set conf_file "$top_dir/sim.conf"
3403  set conf_index 1
3404 
3405  if {[file exists $conf_file]} {
3406  set properties [ReadConf [lindex [GetConfFiles $top_dir] $conf_index]]
3407  # Filter the dictionary for keys ending with ":generics"
3408  set simsets_generics_dict [dict filter $properties key *:generics]
3409  } else {
3410  Msg Warning "File $conf_file not found."
3411  }
3412  return $simsets_generics_dict
3413 }
3414 
3415 
3416 ## Returns the group name from the project directory
3417 #
3418 # @param[in] proj_dir project directory
3419 # @param[in] repo_dir repository directory
3420 #
3421 # @return the group name without initial and final slashes
3422 #
3423 proc GetGroupName {proj_dir repo_dir} {
3424  if {[regexp {^(.*)/(Top|Projects)/+(.*?)/*$} $proj_dir dummy possible_repo_dir proj_or_top dir]} {
3425  # The Top or Project folder is in the root of a the git repository
3426  if {[file normalize $repo_dir] eq [file normalize $possible_repo_dir]} {
3427  set group [file dir $dir]
3428  if {$group == "."} {
3429  set group ""
3430  }
3431  } else {
3432  # The Top or Project folder is NOT in the root of a git repository
3433  Msg Warning "Project directory $proj_dir seems to be in $possible_repo_dir which is not a the main Git repository $repo_dir."
3434  }
3435  } else {
3436  Msg Warning "Could not parse project directory $proj_dir"
3437  set group ""
3438  }
3439  return $group
3440 }
3441 
3442 ## Get custom Hog describe for the project under investigation
3443 #
3444 # @param[in] proj_dir the top directory of the project (e.g. repo_path/Top/group/project)
3445 # @param[in] repo_path the main path of the repository
3446 #
3447 # @return the Hog describe of the project, with a "-dirty" suffix if the project files are not clean
3448 #
3449 proc GetHogDescribe {proj_dir {repo_path .}} {
3450  lassign [GetRepoVersions $proj_dir $repo_path] global_commit global_version
3451  if {$global_commit == 0} {
3452  # in case the repo is dirty, we use the last committed sha and add a -dirty suffix
3453  set new_sha "[string toupper [GetSHA]]"
3454  set suffix "-dirty"
3455  } else {
3456  set new_sha [string toupper $global_commit]
3457  set suffix ""
3458  }
3459  set describe "v[HexVersionToString $global_version]-$new_sha$suffix"
3460  return $describe
3461 }
3462 
3463 ## @brief Extract files, libraries and properties from the project's list files
3464 #
3465 # @param[in] args The arguments are <list_path> <repository path>[options]
3466 # * list_path path to the list file directory
3467 # Options:
3468 # * -list_files <List files> the file wildcard, if not specified all Hog list files will be looked for
3469 # * -sha_mode forwarded to ReadListFile, see there for info
3470 # * -ext_path <external path> path for external libraries forwarded to ReadListFile
3471 #
3472 # @return a list of 3 dictionaries: libraries and properties
3473 # - libraries has library name as keys and a list of filenames as values
3474 # - properties has file names as keys and a list of properties as values
3475 # - filesets has the fileset name as keys and the correspondent list of libraries as values (significant only for simulations)
3476 proc GetHogFiles {args} {
3477  if {[IsQuartus]} {
3478  load_package report
3479  if {[catch {package require cmdline} ERROR]} {
3480  puts "$ERROR\n If you are running this script on tclsh, you can fix this by installing 'tcllib'"
3481  return 0
3482  }
3483  }
3484 
3485 
3486  set parameters {
3487  {list_files.arg "" "The file wildcard, if not specified all Hog list files will be looked for."}
3488  {sha_mode "Forwarded to ReadListFile, see there for info."}
3489  {ext_path.arg "" "Path for the external libraries forwarded to ReadListFile."}
3490  {print_log "Forwarded to ReadListFile, see there for info."}
3491  }
3492  set usage "USAGE: GetHogFiles \[options\] <list path> <repository path>"
3493  if {[catch {array set options [cmdline::getoptions args $parameters $usage]}] || [llength $args] != 2} {
3494  Msg CriticalWarning [cmdline::usage $parameters $usage]
3495  return
3496  }
3497  set list_path [lindex $args 0]
3498  set repo_path [lindex $args 1]
3499 
3500  set list_files $options(list_files)
3501  set sha_mode $options(sha_mode)
3502  set ext_path $options(ext_path)
3503  set print_log $options(print_log)
3504 
3505  if {$sha_mode == 1} {
3506  set sha_mode_opt "-sha_mode"
3507  } else {
3508  set sha_mode_opt ""
3509  }
3510 
3511  if {$print_log == 1} {
3512  set print_log_opt "-print_log"
3513  } else {
3514  set print_log_opt ""
3515  }
3516 
3517 
3518  if {$list_files == ""} {
3519  set list_files {.src,.con,.sim,.ext}
3520  }
3521  set libraries [dict create]
3522  set properties [dict create]
3523  set list_files [glob -nocomplain -directory $list_path "*{$list_files}"]
3524  set filesets [dict create]
3525 
3526  foreach f $list_files {
3527  set ext [file extension $f]
3528  if {$ext == ".ext"} {
3529  lassign [ReadListFile {*}"$sha_mode_opt $print_log_opt $f $ext_path"] l p fs
3530  } else {
3531  lassign [ReadListFile {*}"$sha_mode_opt $print_log_opt $f $repo_path"] l p fs
3532  }
3533  set libraries [MergeDict $l $libraries]
3534  set properties [MergeDict $p $properties]
3535  Msg Debug "list file $f, filesets: $fs"
3536  set filesets [MergeDict $fs $filesets]
3537  Msg Debug "Merged filesets $filesets"
3538  }
3539 
3540  # Auto-discover HLS components from the project's hog.conf (no .src needed).
3541  # The list_path argument is conventionally <proj_dir>/list/, so hog.conf sits
3542  # one level up. For each [hls:<comp>] section with HLS_CONFIG=<path>, add the
3543  # cfg + everything it references to a synthesized "<comp>" library, and -- if
3544  # print_log is on -- show the file tree exactly like a .src would
3545  set proj_conf [file normalize [file join [file dirname $list_path] hog.conf]]
3546  if {[file exists $proj_conf]} {
3547  set hls_configs [GetHlsConfigsFromProjConf $proj_conf $repo_path]
3548  set already_tracked [dict create]
3549  dict for {libname libfiles} $libraries {
3550  foreach lf $libfiles {dict set already_tracked [file normalize $lf] 1}
3551  }
3552  dict for {comp_name cfg_abs} $hls_configs {
3553  if {[dict exists $already_tracked $cfg_abs]} {
3554  Msg Debug "HLS component '$comp_name': cfg $cfg_abs already tracked via a .src, skipping conf-based GetHogFiles discovery."
3555  continue
3556  }
3557  set lib_name "${comp_name}.src"
3558  dict lappend libraries $lib_name $cfg_abs
3559  dict set already_tracked $cfg_abs 1
3560  set hls_extras [ExpandHlsConfigFiles $cfg_abs]
3561  Msg Info "HLS component '$comp_name' (from hog.conf): tracking [expr {1 + [llength $hls_extras]}] file(s) via $cfg_abs"
3562  if {$print_log == 1} {
3563  Msg Status "\nhog.conf \[hls:$comp_name\] (auto-discovered)"
3564  set rel_cfg [Relative $repo_path $cfg_abs 1]
3565  if {$rel_cfg eq ""} {set rel_cfg $cfg_abs}
3566  if {[llength $hls_extras] == 0} {
3567  Msg Status "└── $rel_cfg"
3568  } else {
3569  Msg Status "├── $rel_cfg"
3570  Msg Status " Inside [file tail $cfg_abs] (HLS auto-expand):"
3571  }
3572  }
3573  set n_extras [llength $hls_extras]
3574  set i 0
3575  foreach hls_extra $hls_extras {
3576  incr i
3577  if {[dict exists $already_tracked $hls_extra]} {continue}
3578  dict lappend libraries $lib_name $hls_extra
3579  dict set already_tracked $hls_extra 1
3580  if {$print_log == 1} {
3581  if {$i == $n_extras} {set pad "└──"} else {set pad "├──"}
3582  set rel_extra [Relative [file dirname $cfg_abs] $hls_extra 1]
3583  if {$rel_extra eq ""} {set rel_extra $hls_extra}
3584  Msg Status " $pad $rel_extra"
3585  }
3586  }
3587  }
3588  }
3589 
3590  return [list $libraries $properties $filesets]
3591 }
3592 
3593 # @brief Get the IDE of a Hog project and returns the correct argument for the IDE cli command
3594 #
3595 # @param[in] proj_conf The project hog.conf file
3596 # @param[in] custom_ver If set, use this version instead of the one in the hog.conf
3597 proc GetIDECommand {proj_conf {custom_ver ""}} {
3598  if {$custom_ver ne ""} {
3599  set ide_name_and_ver [string tolower "$custom_ver"]
3600  } elseif {[file exists $proj_conf]} {
3601  set ide_name_and_ver [string tolower [GetIDEFromConf $proj_conf]]
3602  } else {
3603  Msg Error "Configuration file $proj_conf not found."
3604  }
3605 
3606  set ide_name [lindex [regexp -all -inline {\S+} $ide_name_and_ver] 0]
3607 
3608  if {$ide_name eq "vivado" || $ide_name eq "vivado_vitis_classic" || $ide_name eq "vivado_vitis_unified" || $ide_name eq "vitis_unified"} {
3609  set command "vivado"
3610  # A space after the before_tcl_script is important
3611  set before_tcl_script " -nojournal -nolog -mode batch -notrace -source "
3612  set after_tcl_script " -tclargs "
3613  set end_marker ""
3614  } elseif {$ide_name eq "planahead"} {
3615  set command "planAhead"
3616  # A space ater the before_tcl_script is important
3617  set before_tcl_script " -nojournal -nolog -mode batch -notrace -source "
3618  set after_tcl_script " -tclargs "
3619  set end_marker ""
3620  } elseif {$ide_name eq "quartus"} {
3621  set command "quartus_sh"
3622  # A space after the before_tcl_script is important
3623  set before_tcl_script " -t "
3624  set after_tcl_script " "
3625  set end_marker ""
3626  } elseif {$ide_name eq "libero"} {
3627  #I think we need quotes for libero, not sure...
3628 
3629  set command "libero"
3630  set before_tcl_script "SCRIPT:"
3631  set after_tcl_script " SCRIPT_ARGS:\""
3632  set end_marker "\""
3633  } elseif {$ide_name eq "diamond"} {
3634  set command "diamondc"
3635  set before_tcl_script " "
3636  set after_tcl_script " "
3637  set end_marker ""
3638  } elseif {$ide_name eq "vitis_classic"} {
3639  set command "xsct"
3640  # A space after the before_tcl_script is important
3641  set before_tcl_script ""
3642  set after_tcl_script " "
3643  set end_marker ""
3644  } elseif {$ide_name eq "ghdl"} {
3645  set command "ghdl"
3646  set before_tcl_script " "
3647  set after_tcl_script " "
3648  set end_marker ""
3649  } else {
3650  Msg Error "IDE: $ide_name not known."
3651  }
3652 
3653  return [list $command $before_tcl_script $after_tcl_script $end_marker]
3654 }
3655 
3656 ## Get the IDE (Vivado,Quartus,PlanAhead,Libero) version from the conf file she-bang
3657 #
3658 # @param[in] conf_file The hog.conf file
3659 proc GetIDEFromConf {conf_file} {
3660  set f [open $conf_file "r"]
3661  set line [gets $f]
3662  close $f
3663  if {[regexp -all {^\# *(\w*) *(vitis_(?:classic|unified))? *(\d+\.\d+(?:\.\d+)?(?:\.\d+)?)?(_.*)? *$} $line dummy ide vitisflag version patch]} {
3664  if {[info exists vitisflag] && $vitisflag != ""} {
3665  set ide "${ide}_${vitisflag}"
3666  }
3667 
3668  if {[info exists version] && $version != ""} {
3669  set ver $version
3670  } else {
3671  set ver 0.0.0
3672  }
3673  # what shall we do with $patch? ignored for the time being
3674  set ret [list $ide $ver]
3675  } else {
3676  Msg CriticalWarning "The first line of hog.conf should be \#<IDE name> <version>, \
3677  where <IDE name>. is quartus, vivado, planahead, libero, diamond or ghdl, \
3678  and <version> the tool version, e.g. \#vivado 2020.2. Will assume vivado."
3679  set ret [list "vivado" "0.0.0"]
3680  }
3681 
3682  return $ret
3683 }
3684 
3685 # @brief Returns the name of the running IDE
3686 proc GetIDEName {} {
3687  if {[IsISE]} {
3688  return "ISE/PlanAhead"
3689  } elseif {[IsVivado]} {
3690  return "Vivado"
3691  } elseif {[IsQuartus]} {
3692  return "Quartus"
3693  } elseif {[IsLibero]} {
3694  return "Libero"
3695  } elseif {[IsDiamond]} {
3696  return "Diamond"
3697  } else {
3698  return ""
3699  }
3700 }
3701 
3702 ## Returns the version of the IDE (Vivado,Quartus,PlanAhead,Libero) in use
3703 #
3704 # @return the version in string format, e.g. 2020.2
3705 #
3706 proc GetIDEVersion {} {
3707  if {[IsXilinx]} {
3708  # Vivado or planAhead
3709  regexp {\d+\.\d+(\.\d+)?} [version -short] ver
3710  # This regex will cut away anything after the numbers, useful for patched version 2020.1_AR75210
3711  } elseif {[IsQuartus]} {
3712  # Quartus
3713  global quartus
3714  regexp {[\.0-9]+} $quartus(version) ver
3715  } elseif {[IsLibero]} {
3716  # Libero
3717  set ver [get_libero_version]
3718  } elseif {[IsDiamond]} {
3719  # Diamond
3720  regexp {\d+\.\d+(\.\d+)?} [sys_install version] ver
3721  } elseif {[IsVitisClassic]} {
3722  # Vitis Classic
3723  regexp {\d+\.\d+(\.\d+)?} [version] ver
3724  } elseif {[IsVitisUnified]} {
3725  # Vitis Unified
3726  set vitis_output [exec vitis --version 2>@1]
3727  regexp {[Vv]itis\s+v?(\d+\.\d+(?:\.\d+)?)} $vitis_output -> ver
3728  } else {
3729  set ver "0.0.0"
3730  }
3731  return $ver
3732 }
3733 
3734 
3735 ## @brief Returns the real file linked by a soft link
3736 #
3737 # If the provided file is not a soft link, it will give a Warning and return an empty string.
3738 # If the link is broken, will give a warning but still return the linked file
3739 #
3740 # @param[in] link_file The soft link file
3741 proc GetLinkedFile {link_file} {
3742  if {[file type $link_file] eq "link"} {
3743  if {[OS] == "windows"} {
3744  #on windows we need to use readlink because Tcl is broken
3745  lassign [ExecuteRet realpath $link_file] ret msg
3746  lassign [ExecuteRet cygpath -m $msg] ret2 msg2
3747  if {$ret == 0 && $ret2 == 0} {
3748  set real_file $msg2
3749  Msg Debug "Found link file $link_file on Windows, the linked file is: $real_file"
3750  } else {
3751  Msg CriticalWarning "[file normalize $link_file] is a soft link. \
3752  Soft link are not supported on Windows and readlink.exe or cygpath.exe did not work: readlink=$ret: $msg, cygpath=$ret2: $msg2."
3753  set real_file $link_file
3754  }
3755  } else {
3756  #on linux Tcl just works
3757  set linked_file [file link $link_file]
3758  set real_file [file normalize [file dirname $link_file]/$linked_file]
3759  }
3760 
3761  if {![file exists $real_file]} {
3762  Msg Warning "$link_file is a broken link, because the linked file: $real_file does not exist."
3763  }
3764  } else {
3765  Msg Warning "$link file is not a soft link"
3766  set real_file $link_file
3767  }
3768  return $real_file
3769 }
3770 
3771 ## @brief Gets MAX number of Threads property from property.conf file in Top/$proj_name directory.
3772 #
3773 # If property is not set returns default = 1
3774 #
3775 # @param[in] proj_dir: the top folder of the project
3776 #
3777 # @return 1 if property is not set else the value of MaxThreads
3778 #
3779 proc GetMaxThreads {proj_dir} {
3780  set maxThreads 1
3781  if {[file exists $proj_dir/hog.conf]} {
3782  set properties [ReadConf [lindex [GetConfFiles $proj_dir] 0]]
3783  if {[dict exists $properties parameters]} {
3784  set propDict [dict get $properties parameters]
3785  if {[dict exists $propDict MAX_THREADS]} {
3786  set maxThreads [dict get $propDict MAX_THREADS]
3787  }
3788  }
3789  } else {
3790  Msg Warning "File $proj_dir/hog.conf not found. Max threads will be set to default value 1"
3791  }
3792  return $maxThreads
3793 }
3794 
3795 
3796 ## @brief Get a list of all modified the files matching then pattern
3797 #
3798 # @param[in] repo_path the path of the git repository
3799 # @param[in] pattern the pattern with wildcards that files should match
3800 #
3801 # @return a list of all modified files matching the pattern
3802 #
3803 proc GetModifiedFiles {{repo_path "."} {pattern "."}} {
3804  set old_path [pwd]
3805  cd $repo_path
3806  set ret [Git "ls-files --modified $pattern"]
3807  cd $old_path
3808  return $ret
3809 }
3810 
3811 # @brief Gets the command argv list and returns a list of
3812 # options and arguments
3813 # @param[in] argv The command input arguments
3814 # @param[in] parameters The command input parameters
3815 proc GetOptions {argv parameters} {
3816  # Get Options from argv
3817  set arg_list [list]
3818  set param_list [list]
3819  set option_list [list]
3820 
3821  foreach p $parameters {
3822  lappend param_list [lindex $p 0]
3823  }
3824 
3825  set index 0
3826  while {$index < [llength $argv]} {
3827  set arg [lindex $argv $index]
3828  if {[string first - $arg] == 0} {
3829  set option [string trimleft $arg "-"]
3830  incr index
3831  lappend option_list $arg
3832  if {[lsearch -regex $param_list "$option\[.arg]?"] >= 0} {
3833  if {[lsearch -regex $param_list "$option\[.arg]"] >= 0} {
3834  lappend option_list [lindex $argv $index]
3835  incr index
3836  }
3837  }
3838  } else {
3839  lappend arg_list $arg
3840  incr index
3841  }
3842  }
3843  Msg Debug "Argv: $argv"
3844  Msg Debug "Options: $option_list"
3845  Msg Debug "Arguments: $arg_list"
3846  return [list $option_list $arg_list]
3847 }
3848 
3849 # return [list $libraries $properties $simlibraries $constraints $srcsets $simsets $consets]
3850 ## @ brief Returns a list of 7 dictionaries: libraries, properties, constraints, and filesets for sources and simulations
3851 #
3852 # The returned dictionaries are libraries, properties, simlibraries, constraints, srcsets, simsets, consets
3853 # - libraries and simlibraries have the library name as keys and a list of filenames as values
3854 # - properties has as file names as keys and a list of properties as values
3855 # - constraints is a dictionary with a single key (sources.con) and a list of constraint files as value
3856 # - srcsets is a dictionary with a fileset name as a key (e.g. sources_1) and a list of libraries as value
3857 # - simsets is a dictionary with a simset name as a key (e.g. sim_1) and a list of libraries as value
3858 # - consets is a dictionary with a constraints file sets name as a key (e.g. constr_1) and a list of constraint "libraries" (sources.con)
3859 #
3860 # Files, libraries and properties are extracted from the current project
3861 #
3862 # @param[in] project_file The project file (for Libero and Diamond)
3863 # @return A list of 7 dictionaries: libraries, properties, constraints, and filesets for sources and simulations
3864 proc GetProjectFiles {{project_file ""}} {
3865  set libraries [dict create]
3866  set simlibraries [dict create]
3867  set constraints [dict create]
3868  set properties [dict create]
3869  set consets [dict create]
3870  set srcsets [dict create]
3871  set simsets [dict create]
3872 
3873  if {[IsVivado]} {
3874  set all_filesets [get_filesets]
3875  set simulator [get_property target_simulator [current_project]]
3876  set top [get_property "top" [current_fileset]]
3877  set topfile [GetTopFile]
3878  dict lappend properties $topfile "top=$top"
3879 
3880  foreach fs $all_filesets {
3881  if {$fs == "utils_1"} {
3882  # Skipping utility fileset
3883  continue
3884  }
3885 
3886  set all_files [get_files -quiet -of_objects [get_filesets $fs]]
3887  set fs_type [get_property FILESET_TYPE [get_filesets $fs]]
3888 
3889  if {$fs_type == "BlockSrcs"} {
3890  # Vivado creates for each ip a blockset... Let's redirect to sources_1
3891  set dict_fs "sources_1"
3892  } else {
3893  set dict_fs $fs
3894  }
3895  foreach f $all_files {
3896  # Ignore files that are part of the vivado/planahead project but would not be reflected
3897  # in list files (e.g. generated products from ip cores)
3898  set ignore 0
3899  # Generated files point to a parent composite file;
3900  # planahead does not have an IS_GENERATED property
3901  if {[IsInList "IS_GENERATED" [list_property [GetFile $f $fs]]]} {
3902  if {[lindex [get_property IS_GENERATED [GetFile $f $fs]] 0] != 0} {
3903  set ignore 1
3904  }
3905  }
3906 
3907  if {[get_property FILE_TYPE [GetFile $f $fs]] == "Configuration Files"} {
3908  set ignore 1
3909  }
3910 
3911 
3912  if {[IsInList "CORE_CONTAINER" [list_property [GetFile $f $fs]]]} {
3913  if {[get_property CORE_CONTAINER [GetFile $f $fs]] != ""} {
3914  if {[file extension $f] == ".xcix"} {
3915  set f [get_property CORE_CONTAINER [GetFile $f $fs]]
3916  } else {
3917  set ignore 1
3918  }
3919  }
3920  }
3921 
3922  if {[IsInList "SCOPED_TO_REF" [list_property [GetFile $f $fs]]]} {
3923  if {[get_property SCOPED_TO_REF [GetFile $f $fs]] != ""} {
3924  dict lappend properties $f "scoped_to_ref=[get_property SCOPED_TO_REF [GetFile $f $fs]]"
3925  }
3926  }
3927 
3928  if {[IsInList "SCOPED_TO_CELLS" [list_property [GetFile $f $fs]]]} {
3929  if {[get_property SCOPED_TO_CELLS [GetFile $f $fs]] != ""} {
3930  dict lappend properties $f "scoped_to_cells=[regsub " " [get_property SCOPED_TO_CELLS [GetFile $f $fs]] ","]"
3931  }
3932  }
3933 
3934  if {[IsInList "PARENT_COMPOSITE_FILE" [list_property [GetFile $f $fs]]]} {
3935  set ignore 1
3936  }
3937 
3938  # Ignore nocattrs.dat for Versal
3939  if {[file tail $f] == "nocattrs.dat"} {
3940  set ignore 1
3941  }
3942 
3943  if {!$ignore} {
3944  if {[file extension $f] != ".coe"} {
3945  set f [file normalize $f]
3946  }
3947  lappend files $f
3948  set type [get_property FILE_TYPE [GetFile $f $fs]]
3949  # Added a -quiet because some files (.v, .sv) don't have a library
3950  set lib [get_property -quiet LIBRARY [GetFile $f $fs]]
3951 
3952  # Type can be complex like VHDL 2008, in that case we want the second part to be a property
3953  Msg Debug "File $f Extension [file extension $f] Type [lindex $type 0]"
3954 
3955  if {[string equal [lindex $type 0] "VHDL"] && [llength $type] == 1} {
3956  set prop "93"
3957  } elseif {[string equal [lindex $type 0] "VHDL"] && [string equal [lindex $type 1] "2019"]} {
3958  # VHDL 2019 must be reported as an explicit property, unlike VHDL 2008
3959  # (the default, kept propertyless below) so it matches the "2019" tag
3960  # used in list files.
3961  set type "VHDL"
3962  set prop "2019"
3963  } elseif {[string equal [lindex $type 0] "Block"] && [string equal [lindex $type 1] "Designs"]} {
3964  set type "IP"
3965  set prop ""
3966  } elseif {[string equal $type "SystemVerilog"] && [file extension $f] != ".sv" && [file extension $f] != ".svp"} {
3967  set prop "SystemVerilog"
3968  } elseif {[string equal [lindex $type 0] "XDC"] && [file extension $f] != ".xdc"} {
3969  set prop "XDC"
3970  } elseif {[string equal $type "Verilog Header"] && [file extension $f] != ".vh" && [file extension $f] != ".svh"} {
3971  set prop "verilog_header"
3972  } elseif {[string equal $type "Verilog Template"] && [file extension $f] == ".v" && [file extension $f] != ".sv"} {
3973  set prop "verilog_template"
3974  } else {
3975  set type [lindex $type 0]
3976  set prop ""
3977  }
3978  #If type is "VHDL 2008" we will keep only VHDL
3979  if {![string equal $prop ""]} {
3980  dict lappend properties $f $prop
3981  }
3982  # check where the file is used and add it to prop
3983  if {[string equal $fs_type "SimulationSrcs"]} {
3984  # Simulation sources
3985  if {[string equal $type "VHDL"]} {
3986  set library "${lib}.sim"
3987  } else {
3988  set library "others.sim"
3989  }
3990 
3991  if {[IsInList $library [DictGet $simsets $dict_fs]] == 0} {
3992  dict lappend simsets $dict_fs $library
3993  }
3994 
3995  dict lappend simlibraries $library $f
3996  } elseif {[string equal $type "VHDL"]} {
3997  # VHDL files (both 2008 and 93)
3998  if {[IsInList "${lib}.src" [DictGet $srcsets $dict_fs]] == 0} {
3999  dict lappend srcsets $dict_fs "${lib}.src"
4000  }
4001  dict lappend libraries "${lib}.src" $f
4002  } elseif {[string first "IP" $type] != -1} {
4003  # IPs
4004  if {[IsInList "ips.src" [DictGet $srcsets $dict_fs]] == 0} {
4005  dict lappend srcsets $dict_fs "ips.src"
4006  }
4007  dict lappend libraries "ips.src" $f
4008  Msg Debug "Appending $f to ips.src"
4009  } elseif {[string equal $fs_type "Constrs"]} {
4010  # Constraints
4011  if {[IsInList "sources.con" [DictGet $consets $dict_fs]] == 0} {
4012  dict lappend consets $dict_fs "sources.con"
4013  }
4014  dict lappend constraints "sources.con" $f
4015  } else {
4016  # Verilog and other files
4017  if {[IsInList "others.src" [DictGet $srcsets $dict_fs]] == 0} {
4018  dict lappend srcsets $dict_fs "others.src"
4019  }
4020  dict lappend libraries "others.src" $f
4021  Msg Debug "Appending $f to others.src"
4022  }
4023 
4024  if {[lindex [get_property -quiet used_in_synthesis [GetFile $f $fs]] 0] == 0} {
4025  dict lappend properties $f "nosynth"
4026  }
4027  if {[lindex [get_property -quiet used_in_implementation [GetFile $f $fs]] 0] == 0} {
4028  dict lappend properties $f "noimpl"
4029  }
4030  if {[lindex [get_property -quiet used_in_simulation [GetFile $f $fs]] 0] == 0} {
4031  dict lappend properties $f "nosim"
4032  }
4033  if {[lindex [get_property -quiet IS_MANAGED [GetFile $f $fs]] 0] == 0 && [file extension $f] != ".xcix"} {
4034  dict lappend properties $f "locked"
4035  }
4036  }
4037  }
4038  }
4039 
4040  dict lappend properties "Simulator" [get_property target_simulator [current_project]]
4041  } elseif {[IsLibero] || [IsSynplify]} {
4042  # Open the project file
4043  set file [open $project_file r]
4044  set in_file_manager 0
4045  set top ""
4046  while {[gets $file line] >= 0} {
4047  # Detect the ActiveRoot (Top) module
4048  if {[regexp {^KEY ActiveRoot \"([^\"]+)\"} $line -> value]} {
4049  set top [string range $value 0 [expr {[string first "::" $value] - 1}]]
4050  }
4051 
4052  # Detect the start of the FileManager section
4053  if {[regexp {^LIST FileManager} $line]} {
4054  set in_file_manager 1
4055  continue
4056  }
4057 
4058  # Detect the end of the FileManager section
4059  if {$in_file_manager && [regexp {^ENDLIST} $line]} {
4060  break
4061  }
4062 
4063  # Extract file paths from the VALUE entries
4064  if {$in_file_manager && [regexp {^VALUE \"([^\"]+)} $line -> value]} {
4065  # lappend source_files [remove_after_comma $filepath]
4066  # set file_path ""
4067  lassign [split $value ,] file_path file_type
4068  # Extract file properties
4069  set parent_file ""
4070  set library "others"
4071  while {[gets $file line] >= 0} {
4072  if {$line == "ENDFILE"} {
4073  break
4074  }
4075  regexp {^LIBRARY=\"([^\"]+)} $line -> library
4076  regexp {^PARENT=\"([^\"]+)} $line -> parent_file
4077  }
4078  Msg Debug "Found file ${file_path} in project.."
4079  if {$parent_file == ""} {
4080  if {$file_type == "hdl"} {
4081  # VHDL files (both 2008 and 93)
4082  if {[IsInList "${library}.src" [DictGet $srcsets "sources_1"]] == 0} {
4083  dict lappend srcsets "sources_1" "${library}.src"
4084  }
4085  dict lappend libraries "${library}.src" $file_path
4086  # Check if file is top_module in project
4087  Msg Debug "File $file_path module [GetModuleName $file_path]"
4088 
4089  if {[GetModuleName $file_path] == [string tolower $top] && $top != ""} {
4090  Msg Debug "Found top module $top in $file_path"
4091  dict lappend properties $file_path "top=$top"
4092  }
4093  } elseif {$file_type == "tb_hdl"} {
4094  if {[IsInList "${library}.sim" [DictGet $simsets "sim_1"]] == 0} {
4095  dict lappend simsets "sim_1" "${library}.sim"
4096  }
4097  dict lappend simlibraries "${library}.sim" $file_path
4098  } elseif {$file_type == "io_pdc" || $file_type == "sdc"} {
4099  if {[IsInList "sources.con" [DictGet $consets "constrs_1"]] == 0} {
4100  dict lappend consets "constrs_1" "sources.con"
4101  }
4102  dict lappend constraints "sources.con" $file_path
4103  }
4104  }
4105  }
4106  }
4107  } elseif {[IsDiamond]} {
4108  # Open the Diamond XML project file content
4109  set fileData [read [open $project_file]]
4110 
4111  set project_path [file dirname $project_file]
4112 
4113  # Remove XML declaration
4114  regsub {<\?xml.*\?>} $fileData "" fileData
4115 
4116  # Extract the Implementation block
4117  regexp {<Implementation.*?>(.*)</Implementation>} $fileData -> implementationContent
4118 
4119  # Extract each Source block one by one
4120  set sources {}
4121  set sourceRegex {<Source name="([^"]*?)" type="([^"]*?)" type_short="([^"]*?)".*?>(.*?)</Source>}
4122 
4123  set optionsRegex {<Options(.*?)\/>}
4124  regexp $optionsRegex $implementationContent -> prj_options
4125  foreach option $prj_options {
4126  if {[regexp {^top=\"([^\"]+)\"} $option match result]} {
4127  set top $result
4128  }
4129  }
4130 
4131  while {[regexp $sourceRegex $implementationContent match name type type_short optionsContent]} {
4132  Msg Debug "Found file ${name} in project..."
4133  set file_path [file normalize $project_path/$name]
4134  # Extract the Options attributes
4135  set optionsRegex {<Options(.*?)\/>}
4136  regexp $optionsRegex $optionsContent -> options
4137  set library "others"
4138  set isSV 0
4139  foreach option $options {
4140  if {[string first "System Verilog" $option]} {
4141  set isSV 1
4142  }
4143  if {[regexp {^lib=\"([^\"]+)\"} $option match1 result]} {
4144  set library $result
4145  }
4146  }
4147  set ext ".src"
4148  if {[regexp {syn_sim="([^"]*?)"} $match match_sim simonly]} {
4149  set ext ".sim"
4150  }
4151 
4152  # Append VHDL files
4153  if {$type_short == "VHDL" || $type_short == "Verilog" || $type_short == "IPX"} {
4154  if {$ext == ".src"} {
4155  if {[IsInList "${library}${ext}" [DictGet $srcsets "sources_1"]] == 0} {
4156  dict lappend srcsets "sources_1" "${library}${ext}"
4157  }
4158  dict lappend libraries "${library}${ext}" $file_path
4159  } elseif {$ext == ".sim"} {
4160  if {[IsInList "${library}.sim" [DictGet $simsets "sim_1"]] == 0} {
4161  dict lappend simsets "sim_1" "${library}.sim"
4162  }
4163  dict lappend simlibraries "${library}.sim" $file_path
4164  }
4165  # Check if file is top_module in project
4166  Msg Debug "File $file_path module [GetModuleName $file_path]"
4167 
4168  if {[GetModuleName $file_path] == $top && $top != ""} {
4169  Msg Debug "Found top module $top in $file_path"
4170  dict lappend properties $file_path "top=$top"
4171  }
4172  } elseif {$type_short == "SDC"} {
4173  if {[IsInList "sources.con" [DictGet $consets "constrs_1"]] == 0} {
4174  dict lappend consets "constrs_1" "sources.con"
4175  }
4176  dict lappend constraints "sources.con" $file_path
4177  }
4178 
4179  # Remove the processed Source block from the implementation content
4180  regsub -- $match $implementationContent "" implementationContent
4181  }
4182  }
4183  return [list $libraries $properties $simlibraries $constraints $srcsets $simsets $consets]
4184 }
4185 
4186 #"
4187 ## Get the Project flavour
4188 #
4189 # @param[in] proj_name The project name
4190 proc GetProjectFlavour {proj_name} {
4191  # Calculating flavour if any
4192  set flavour [string map {. ""} [file extension $proj_name]]
4193  if {$flavour != ""} {
4194  if {[string is integer $flavour]} {
4195  Msg Info "Project $proj_name has flavour = $flavour, the generic variable FLAVOUR will be set to $flavour"
4196  } else {
4197  Msg Warning "Project name has a unexpected non numeric extension, flavour will be set to -1"
4198  set flavour -1
4199  }
4200  } else {
4201  set flavour -1
4202  }
4203  return $flavour
4204 }
4205 
4206 ## Get the project version
4207 #
4208 # @param[in] proj_dir: The top folder of the project of which all the version must be calculated
4209 # @param[in] repo_path: The top folder of the repository
4210 # @param[in] ext_path: path for external libraries
4211 # @param[in] sim: if enabled, check the version also for the simulation files
4212 #
4213 # @return returns the project version
4214 proc GetProjectVersion {proj_dir repo_path {ext_path ""} {sim 0}} {
4215  if {![file exists $proj_dir]} {
4216  Msg CriticalWarning "$proj_dir not found"
4217  return -1
4218  }
4219  set old_dir [pwd]
4220  cd $proj_dir
4221 
4222  #The latest version the repository
4223  lassign [GitRet {describe --tags --abbrev=0 --match "v*"}] ret result
4224  if {$ret != 0} {
4225  Msg CriticalWarning "No Hog versioning tags (v*) in repo"
4226  return -1
4227  }
4228 
4229  set v_last [ExtractVersionFromTag $result]
4230  lassign [GetRepoVersions $proj_dir $repo_path $ext_path $sim] sha ver
4231  if {$sha == 0} {
4232  Msg Warning "Repository is not clean"
4233  cd $old_dir
4234  return -1
4235  }
4236 
4237  #The project version
4238  set v_proj [ExtractVersionFromTag v[HexVersionToString $ver]]
4239  set comp [CompareVersions $v_proj $v_last]
4240  Msg Debug "Project version $v_proj, latest tag $v_last"
4241  if {$comp == 1} {
4242  Msg Debug "The specified project was modified since official version."
4243  set ret 0
4244  } else {
4245  set ret v[HexVersionToString $ver]
4246  }
4247 
4248  if {$comp == 0} {
4249  Msg Info "The specified project was modified in the latest official version $ret"
4250  } elseif {$comp == -1} {
4251  Msg Info "The specified project was modified in a past official version $ret"
4252  }
4253 
4254  cd $old_dir
4255  return $ret
4256 }
4257 
4258 ## Get the versions for all libraries, submodules, etc. for a given project
4259 #
4260 # @param[in] proj_dir: The project directory containing the conf file or the the tcl file
4261 # @param[in] repo_path: top path of the repository
4262 # @param[in] ext_path: path for external libraries
4263 # @param[in] sim: if enabled, check the version also for the simulation files
4264 #
4265 # @return a list containing all the versions: global, top (hog.conf, pre and post tcl scripts, etc.), constraints,
4266 # libraries, submodules, external, ipbus xml, user ip repos, cheby (hash and ver)
4267 proc GetRepoVersions {proj_dir repo_path {ext_path ""} {sim 0}} {
4268  global NOT_CLEAN_WARNED
4269  if {[catch {package require cmdline} ERROR]} {
4270  puts "$ERROR\n If you are running this script on tclsh, you can fix this by installing 'tcllib'"
4271  return 1
4272  }
4273 
4274  set old_path [pwd]
4275  set conf_files [GetConfFiles $proj_dir]
4276 
4277  # This will be the list of all the SHAs of this project, the most recent will be picked up as GLOBAL SHA
4278  set SHAs ""
4279  set versions ""
4280 
4281  # Hog submodule
4282  cd $repo_path
4283 
4284  # Append the SHA in which Hog submodule was changed, not the submodule SHA
4285  lappend SHAs [GetSHA {Hog}]
4286  lappend versions [GetVerFromSHA $SHAs $repo_path]
4287 
4288  cd "$repo_path/Hog"
4289  if {[Git {status --untracked-files=no --porcelain}] eq ""} {
4290  Msg Debug "Hog submodule [pwd] clean."
4291  lassign [GetVer ./] hog_ver hog_hash
4292  } else {
4293  Msg CriticalWarning "Hog submodule [pwd] not clean, commit hash will be set to 0."
4294  set hog_hash "0000000"
4295  set hog_ver "00000000"
4296  }
4297 
4298  cd $repo_path
4299  # Collect all project-relevant files; the clean check will be deferred until all files are known
4300  # set project_files $conf_files
4301  foreach conf_file $conf_files {
4302  if {[string match "$repo_path/*" $conf_file]} {
4303  set conf_file [string replace $conf_file 0 [string length $repo_path]]
4304  }
4305  lappend project_files $conf_file
4306  }
4307 
4308  lappend project_files Hog
4309 
4310  # Top project directory
4311  lassign [GetVer [join $conf_files]] top_ver top_hash
4312  lappend SHAs $top_hash
4313  lappend versions $top_ver
4314 
4315  # Read list files
4316  set libs ""
4317  set vers ""
4318  set hashes ""
4319  # Specify sha_mode 1 for GetHogFiles to get all the files, including the list-files themselves
4320  lassign [GetHogFiles -list_files "*.src" -sha_mode "$proj_dir/list/" $repo_path] src_files dummy
4321  dict for {f files} $src_files {
4322  # library names have a .src extension in values returned by GetHogFiles
4323  set name [file rootname [file tail $f]]
4324  if {[file ext $f] == ".oth"} {
4325  set name "OTHERS"
4326  }
4327  lassign [GetVer $files] ver hash
4328  # Msg Info "Found source list file $f, version: $ver commit SHA: $hash"
4329  lappend libs $name
4330  lappend versions $ver
4331  lappend vers $ver
4332  lappend hashes $hash
4333  lappend SHAs $hash
4334  set relative_files ""
4335  foreach fil $files {
4336  if {[string match "$repo_path/*" $fil]} {
4337  set fil [string replace $fil 0 [string length $repo_path]]
4338  }
4339  lappend relative_files $fil
4340  }
4341 
4342  lappend project_files $f {*}$relative_files
4343  }
4344 
4345  # Read constraint list files
4346  set cons_hashes ""
4347  # Specify sha_mode 1 for GetHogFiles to get all the files, including the list-files themselves
4348  lassign [GetHogFiles -list_files "*.con" -sha_mode "$proj_dir/list/" $repo_path] cons_files dummy
4349  dict for {f files} $cons_files {
4350  #library names have a .con extension in values returned by GetHogFiles
4351  set name [file rootname [file tail $f]]
4352  lassign [GetVer $files] ver hash
4353  #Msg Info "Found constraint list file $f, version: $ver commit SHA: $hash"
4354  if {$hash eq ""} {
4355  Msg CriticalWarning "Constraints file $f not found in Git."
4356  }
4357  lappend cons_hashes $hash
4358  lappend SHAs $hash
4359  lappend versions $ver
4360  set relative_files ""
4361  foreach fil $files {
4362  if {[string match "$repo_path/*" $fil]} {
4363  set fil [string replace $fil 0 [string length $repo_path]]
4364  }
4365  lappend relative_files $fil
4366  }
4367  lappend project_files $f {*}$relative_files
4368  }
4369 
4370  # Read simulation list files
4371  if {$sim == 1} {
4372  set sim_hashes ""
4373  # Specify sha_mode 1 for GetHogFiles to get all the files, including the list-files themselves
4374  lassign [GetHogFiles -list_files "*.sim" -sha_mode "$proj_dir/list/" $repo_path] sim_files dummy
4375  dict for {f files} $sim_files {
4376  #library names have a .sim extension in values returned by GetHogFiles
4377  set name [file rootname [file tail $f]]
4378  lassign [GetVer $files] ver hash
4379  #Msg Info "Found simulation list file $f, version: $ver commit SHA: $hash"
4380  lappend sim_hashes $hash
4381  lappend SHAs $hash
4382  lappend versions $ver
4383  set relative_files ""
4384  foreach fil $files {
4385  if {[string match "$repo_path/*" $fil]} {
4386  set fil [string replace $fil 0 [string length $repo_path]]
4387  }
4388  lappend relative_files $fil
4389  }
4390  lappend project_files $f {*}$relative_files
4391  }
4392  }
4393 
4394 
4395  #Of all the constraints we get the most recent
4396  if {[IsInList {} $cons_hashes]} {
4397  #" Fake comment for Visual Code Studio
4398  Msg CriticalWarning "No hashes found for constraints files (not in git)"
4399  set cons_hash ""
4400  } else {
4401  set cons_hash [string tolower [Git "log --format=%h -1 $cons_hashes"]]
4402  }
4403  set cons_ver [GetVerFromSHA $cons_hash $repo_path]
4404  #Msg Info "Among all the constraint list files, if more than one, the most recent version was chosen: $cons_ver commit SHA: $cons_hash"
4405 
4406  # Read external library files
4407  set ext_hashes ""
4408  set ext_files [glob -nocomplain "$proj_dir/list/*.ext"]
4409  set ext_names ""
4410 
4411  foreach f $ext_files {
4412  set name [file rootname [file tail $f]]
4413  set hash [GetSHA $f]
4414  #Msg Info "Found source file $f, commit SHA: $hash"
4415  lappend ext_names $name
4416  lappend ext_hashes $hash
4417  lappend SHAs $hash
4418  set ext_ver [GetVerFromSHA $hash $repo_path]
4419  lappend versions $ext_ver
4420  lappend project_files $f
4421 
4422  set fp [open $f r]
4423  set file_data [read $fp]
4424  close $fp
4425  set data [split $file_data "\n"]
4426  #Msg Info "Checking checksums of external library files in $f"
4427  foreach line $data {
4428  if {![regexp {^ *$} $line] & ![regexp {^ *\#} $line]} {
4429  #Exclude empty lines and comments
4430  set file_and_prop [regexp -all -inline {\S+} $line]
4431  set hdlfile [lindex $file_and_prop 0]
4432  set hdlfile $ext_path/$hdlfile
4433  if {[file exists $hdlfile]} {
4434  set hash [lindex $file_and_prop 1]
4435  set current_hash [Md5Sum $hdlfile]
4436  if {[string first $hash $current_hash] == -1} {
4437  Msg CriticalWarning "File $hdlfile has a wrong hash. Current checksum: $current_hash, expected: $hash"
4438  }
4439  }
4440  }
4441  }
4442  }
4443 
4444  # Ipbus XML
4445  if {[llength [glob -nocomplain $proj_dir/list/*.ipb]] > 0} {
4446  #Msg Info "Found IPbus XML list file, evaluating version and SHA of listed files..."
4447  lassign [GetHogFiles -list_files "*.ipb" -sha_mode "$proj_dir/list/" $repo_path] xml_files dummy
4448  set xml_source_files [dict get $xml_files "xml.ipb"]
4449  lassign [GetVer $xml_source_files] xml_ver xml_hash
4450  lappend SHAs $xml_hash
4451  lappend versions $xml_ver
4452  set relative_files ""
4453  foreach fil $xml_source_files {
4454  if {[string match "$repo_path/*" $fil]} {
4455  set fil [string replace $fil 0 [string length $repo_path]]
4456  }
4457  lappend relative_files $fil
4458  }
4459  lappend project_files {*}[glob $proj_dir/list/*.ipb] {*}$relative_files
4460  #Msg Info "Found IPbus XML SHA: $xml_hash and version: $xml_ver."
4461  } else {
4462  Msg Debug "This project does not use IPbus XMLs"
4463  set xml_ver ""
4464  set xml_hash ""
4465  }
4466 
4467  # Cheby register-map sources
4468  if {[llength [glob -nocomplain $proj_dir/list/*.chb]] > 0} {
4469  lassign [GetHogFiles -list_files "*.chb" -sha_mode "$proj_dir/list/" $repo_path] cheby_files dummy
4470  if {[dict exists $cheby_files "cheby.chb"]} {
4471  set cheby_source_files [dict get $cheby_files "cheby.chb"]
4472  lassign [GetVer $cheby_source_files] cheby_ver cheby_hash
4473  lappend SHAs $cheby_hash
4474  lappend versions $cheby_ver
4475  lappend project_files {*}[glob $proj_dir/list/*.chb] {*}$cheby_source_files
4476  } else {
4477  set cheby_ver ""
4478  set cheby_hash ""
4479  }
4480  } else {
4481  Msg Info "This project does not use Cheby register maps"
4482  set cheby_ver ""
4483  set cheby_hash ""
4484  }
4485 
4486  set user_ip_repos ""
4487  set user_ip_repo_hashes ""
4488  set user_ip_repo_vers ""
4489  # User IP Repository (Vivado only, hog.conf only)
4490  if {[file exists [lindex $conf_files 0]]} {
4491  set PROPERTIES [ReadConf [lindex $conf_files 0]]
4492  if {[dict exists $PROPERTIES main]} {
4493  set main [dict get $PROPERTIES main]
4494  dict for {p v} $main {
4495  if {[string tolower $p] == "ip_repo_paths"} {
4496  foreach repo $v {
4497  if {[file isdirectory "$repo_path/$repo"]} {
4498  set repo_file_list [glob -nocomplain "$repo_path/$repo/*"]
4499  if {[llength $repo_file_list] == 0} {
4500  Msg Warning "IP_REPO_PATHS property set to $repo in hog.conf but directory is empty."
4501  } else {
4502  lappend user_ip_repos "$repo_path/$repo"
4503  }
4504  }
4505  }
4506  }
4507  }
4508  }
4509 
4510  # For each defined IP repository get hash and version if directory exists and not empty
4511  foreach repo $user_ip_repos {
4512  if {[file isdirectory $repo]} {
4513  set repo_file_list [glob -nocomplain "$repo/*"]
4514  if {[llength $repo_file_list] != 0} {
4515  lassign [GetVer $repo] ver sha
4516  lappend user_ip_repo_hashes $sha
4517  lappend user_ip_repo_vers $ver
4518  lappend versions $ver
4519  lappend project_files $repo
4520  } else {
4521  Msg Warning "IP_REPO_PATHS property set to $repo in hog.conf but directory is empty."
4522  }
4523  } else {
4524  Msg Warning "IP_REPO_PATHS property set to $repo in hog.conf but directory does not exist."
4525  }
4526  }
4527  }
4528 
4529  cd $repo_path
4530  # Check cleanliness only for the files that belong to this project
4531  set dirty ""
4532  # if {[OS] == "windows"} {
4533  # set chunk_size 10
4534  # for {set i 0} {$i < [llength $project_files]} {incr i $chunk_size} {
4535  # set chunk [lrange $project_files $i [expr {$i + $chunk_size - 1}]]
4536  # append dirty [Git "status --untracked-files=no --porcelain" $chunk]
4537  # }
4538  # } else {
4539  append dirty [Git "status --untracked-files=no --porcelain" $project_files]
4540  # }
4541 
4542  if {$dirty eq ""} {
4543  Msg Debug "Project-relevant files are clean."
4544  set clean 1
4545  } else {
4546  if {![info exists NOT_CLEAN_WARNED]} {
4547  Msg CriticalWarning "Project-relevant files not clean, commit hash and version will be set to 0."
4548  set NOT_CLEAN_WARNED 1
4549  }
4550  set clean 0
4551  }
4552 
4553  #The global SHA and ver is the most recent among everything
4554  if {$clean == 1} {
4555  set found 0
4556  while {$found == 0} {
4557  set global_commit [Git "log --topo-order --format=%h -1 --abbrev=7 $SHAs"]
4558  foreach sha $SHAs {
4559  set found 1
4560  if {![IsCommitAncestor $sha $global_commit]} {
4561  set common_child [FindCommonGitChild $global_commit $sha]
4562  if {$common_child == 0} {
4563  Msg CriticalWarning "The commit $sha is not an ancestor of the global commit $global_commit, which is OK. \
4564  But $sha and $global_commit do not have any common child, which is NOT OK. \
4565  This is probably do to a REBASE that is forbidden in Hog methodology as it changes git history. \
4566  Hog cannot guarantee the accuracy of the SHAs. \
4567  A way to fix this is to make a commit that touches all the projects in the repositories (e.g. change the Hog version), \
4568  but please do not rebase in the official branches in the future."
4569  } else {
4570  Msg Info "The commit $sha is not an ancestor of the global commit $global_commit, adding the first common child $common_child instead..."
4571  lappend SHAs $common_child
4572  }
4573  set found 0
4574 
4575  break
4576  }
4577  }
4578  }
4579  set global_version [FindNewestVersion $versions]
4580  } else {
4581  set global_commit "0000000"
4582  set global_version "00000000"
4583  }
4584 
4585  cd $old_path
4586 
4587  set top_hash [format %+07s $top_hash]
4588  set cons_hash [format %+07s $cons_hash]
4589  return [list $global_commit $global_version \
4590  $hog_hash $hog_ver $top_hash $top_ver \
4591  $libs $hashes $vers $cons_ver $cons_hash \
4592  $ext_names $ext_hashes $xml_hash $xml_ver \
4593  $user_ip_repos $user_ip_repo_hashes $user_ip_repo_vers \
4594  $cheby_hash $cheby_ver]
4595 }
4596 
4597 ## @brief Get git SHA of a subset of list file
4598 #
4599 # @param[in] path the file/path or list of files/path the git SHA should be evaluated from. If is not set, use the current path
4600 #
4601 # @return the value of the desired SHA
4602 #
4603 proc GetSHA {{path ""}} {
4604  set old_path [pwd]
4605  if {$path == ""} {
4606  lassign [GitRet {log --format=%h --abbrev=7 -1}] status result
4607  if {$status == 0} {
4608  return [string tolower $result]
4609  } else {
4610  Msg Error "Something went wrong while finding the latest SHA. Does the repository have a commit?"
4611  exit 1
4612  }
4613  }
4614 
4615  # Get repository top level
4616  set repo_path [lindex [Git {rev-parse --show-toplevel}] 0]
4617  cd $repo_path
4618  set paths {}
4619  # Retrieve the list of submodules in the repository
4620  foreach f $path {
4621  set file_in_module 0
4622  if {[file exists .gitmodules]} {
4623  lassign [GitRet "config --file .gitmodules --get-regexp path"] status result
4624  if {$status == 0} {
4625  set submodules [split $result "\n"]
4626  } else {
4627  set submodules ""
4628  Msg Warning "Something went wrong while trying to find submodules: $result"
4629  }
4630 
4631  foreach mod $submodules {
4632  set module [lindex $mod 1]
4633  if {[string first "$repo_path/$module" $f] == 0} {
4634  # File is in a submodule. Append
4635  set file_in_module 1
4636  lappend paths "$module"
4637  break
4638  }
4639  }
4640  }
4641  if {$file_in_module == 0} {
4642  #File is not in a submodule
4643  lappend paths $f
4644  }
4645  }
4646 
4647  lassign [GitRet {log --format=%h --abbrev=7 -1} $paths] status result
4648  if {$status == 0} {
4649  return [string tolower $result]
4650  } else {
4651  Msg Error "Something went wrong while finding the latest SHA. Does the repository have a commit?"
4652  exit 1
4653  }
4654  cd $old_path
4655  return [string tolower $result]
4656 }
4657 
4658 ## @brief Returns the list of Simulators supported by Vivado
4659 proc GetSimulators {} {
4660  set SIMULATORS [list "modelsim" "questa" "riviera" "activehdl" "ies" "vcs"]
4661  return $SIMULATORS
4662 }
4663 
4664 ## @brief Return the path to the active top file
4665 proc GetTopFile {} {
4666  if {[IsVivado]} {
4667  set compile_order_prop [get_property source_mgmt_mode [current_project]]
4668  if {$compile_order_prop ne "All"} {
4669  Msg CriticalWarning "Compile order is not set to automatic, setting it now..."
4670  set_property source_mgmt_mode All [current_project]
4671  update_compile_order -fileset sources_1
4672  }
4673  return [lindex [get_files -quiet -compile_order sources -used_in synthesis -filter {FILE_TYPE =~ "VHDL*" || FILE_TYPE =~ "*Verilog*" }] end]
4674  } elseif {[IsISE]} {
4675  debug::design_graph_mgr -create [current_fileset]
4676  debug::design_graph -add_fileset [current_fileset]
4677  debug::design_graph -update_all
4678  return [lindex [debug::design_graph -get_compile_order] end]
4679  } else {
4680  Msg Error "GetTopFile not yet implemented for this IDE"
4681  }
4682 }
4683 
4684 ## @brief Return the name of the active top module
4685 proc GetTopModule {} {
4686  if {[IsXilinx]} {
4687  return [get_property top [current_fileset]]
4688  } else {
4689  Msg Error "GetTopModule not yet implemented for this IDE"
4690  }
4691 }
4692 
4693 ## @brief Get git version and commit hash of a subset of files
4694 #
4695 # @param[in] path list file or path containing the subset of files whose latest commit hash will be returned
4696 #
4697 # @return a list: the git SHA, the version in hex format
4698 #
4699 proc GetVer {path {force_develop 0}} {
4700  set SHA [GetSHA $path]
4701  #oldest tag containing SHA
4702  if {$SHA eq ""} {
4703  Msg CriticalWarning "Empty SHA found for ${path}. Commit to Git to resolve this warning."
4704  }
4705  set old_path [pwd]
4706  set p [lindex $path 0]
4707  if {[file isdirectory $p]} {
4708  cd $p
4709  } else {
4710  cd [file dirname $p]
4711  }
4712  set repo_path [Git {rev-parse --show-toplevel}]
4713  cd $old_path
4714 
4715  return [list [GetVerFromSHA $SHA $repo_path $force_develop] $SHA]
4716 }
4717 
4718 ## @brief Get git version and commit hash of a specific commit give the SHA
4719 #
4720 # @param[in] SHA the git SHA of the commit
4721 # @param[in] repo_path the path of the repository, this is used to open the Top/repo.conf file
4722 # @param[in] force_develop Force a tag for the develop branch (increase m)
4723 #
4724 # @return a list: the git SHA, the version in hex format
4725 #
4726 proc GetVerFromSHA {SHA repo_path {force_develop 0}} {
4727  global NO_HOG_VER_TAG_WARNED
4728  if {$SHA eq ""} {
4729  Msg CriticalWarning "Empty SHA found"
4730  set ver "v0.0.0"
4731  } else {
4732  lassign [GitRet "tag --sort=creatordate --contain $SHA -l v*.*.* -l b*v*.*.*"] status result
4733 
4734  if {$status == 0} {
4735  if {[regexp {^ *$} $result]} {
4736  # We do not want the most recent tag, we want the biggest value
4737  lassign [GitRet "log --oneline --pretty=\"%d\""] status2 tag_list
4738  #Msg Status "List of all tags including $SHA: $tag_list."
4739  #cleanup the list and get only the tags
4740  set pattern {tag: v\d+\.\d+\.\d+}
4741  set real_tag_list {}
4742  foreach x $tag_list {
4743  set x_untrimmed [regexp -all -inline $pattern $x]
4744  regsub "tag: " $x_untrimmed "" x_trimmed
4745  set tt [lindex $x_trimmed 0]
4746  if {![string equal $tt ""]} {
4747  lappend real_tag_list $tt
4748  #puts "<$tt>"
4749  }
4750  }
4751  Msg Debug "Cleaned up list: $real_tag_list."
4752  # Sort the tags in version order
4753  set sorted_tags [lsort -decreasing -command CompareVersions $real_tag_list]
4754 
4755  Msg Debug "Sorted Tag list: $sorted_tags"
4756  # Select the newest tag in terms of number, not time
4757  set tag [lindex $sorted_tags 0]
4758 
4759  # Msg Debug "Chosen Tag $tag"
4760  set pattern {v\d+\.\d+\.\d+}
4761  if {![regexp $pattern $tag]} {
4762  if {![info exists NO_HOG_VER_TAG_WARNED]} {
4763  Msg CriticalWarning "No Hog version tags found in this repository."
4764  set NO_HOG_VER_TAG_WARNED 1
4765  }
4766  set ver v0.0.0
4767  } else {
4768  lassign [ExtractVersionFromTag $tag] M m p mr
4769  # Open repo.conf and check prefixes
4770  set repo_conf $repo_path/Top/repo.conf
4771 
4772  # Check if the develop/master scheme is used and where is the merge directed to
4773  # Default values
4774  set hotfix_prefix "hotfix/"
4775  set minor_prefix "minor_version/"
4776  set major_prefix "major_version/"
4777  set is_hotfix 0
4778  set enable_develop_branch $force_develop
4779 
4780  set branch_name [Git {rev-parse --abbrev-ref HEAD}]
4781 
4782  if {[file exists $repo_conf]} {
4783  set PROPERTIES [ReadConf $repo_conf]
4784  # [main] section
4785  if {[dict exists $PROPERTIES main]} {
4786  set mainDict [dict get $PROPERTIES main]
4787 
4788  # ENABLE_DEVELOP_ BRANCH property
4789  if {[dict exists $mainDict ENABLE_DEVELOP_BRANCH]} {
4790  set enable_develop_branch [dict get $mainDict ENABLE_DEVELOP_BRANCH]
4791  }
4792  # More properties in [main] here ...
4793  }
4794 
4795  # [prefixes] section
4796  if {[dict exists $PROPERTIES prefixes]} {
4797  set prefixDict [dict get $PROPERTIES prefixes]
4798 
4799  if {[dict exists $prefixDict HOTFIX]} {
4800  set hotfix_prefix [dict get $prefixDict HOTFIX]
4801  }
4802  if {[dict exists $prefixDict MINOR_VERSION]} {
4803  set minor_prefix [dict get $prefixDict MINOR_VERSION]
4804  }
4805  if {[dict exists $prefixDict MAJOR_VERSION]} {
4806  set major_prefix [dict get $prefixDict MAJOR_VERSION]
4807  }
4808  # More properties in [prefixes] here ...
4809  }
4810  }
4811 
4812  if {[string match "HEAD" $branch_name]} {
4813  Msg Debug "Detached HEAD detected - attempting to find branch name"
4814 
4815  # if the branch_name is HEAD (not a legal branch name btw)
4816  # then the branch has been checked out in a detached head state
4817  # this is a fallback condition to enable finding the branch name that the commit is linked too
4818  set log_refs [Git {show -s --pretty=%D HEAD}]
4819  set branch_list [split $log_refs ","]
4820  Msg Debug "list of possible branch refs $log_refs"
4821 
4822  # iterate over all possible refs and match against all prefix types
4823  # set branch name as matched prefix if and only if one match is found
4824 
4825  set match_count 0
4826  set match_prefixes [list $hotfix_prefix $minor_prefix $major_prefix]
4827  set prev_branch_name $branch_name
4828 
4829  foreach br $branch_list {
4830  foreach pr $match_prefixes {
4831  if {[string match "$pr*" [string trim $br]]} {
4832  set branch_name [string trim $br]
4833  incr match_count 1
4834  }
4835  }
4836  }
4837 
4838  if {!$match_count == 1} {
4839  set branch_name $prev_branch_name
4840  Msg Debug "Branch name not found. Using $branch_name"
4841  } else {
4842  Msg Debug "Branch name found: $branch_name"
4843  }
4844  }
4845 
4846  if {$enable_develop_branch == 1} {
4847  if {[string match "$hotfix_prefix*" $branch_name]} {
4848  set is_hotfix 1
4849  }
4850  }
4851 
4852  if {[string match "$major_prefix*" $branch_name]} {
4853  # If major prefix is used, we increase M regardless of anything else
4854  set version_level major
4855  } elseif {[string match "$minor_prefix*" $branch_name] || ($enable_develop_branch == 1 && $is_hotfix == 0)} {
4856  # This is tricky. We increase m if the minor prefix is used or if we are in develop mode and this IS NOT a hotfix
4857  set version_level minor
4858  } else {
4859  # This is even trickier... We increase p if no prefix is used AND we are not in develop mode or if we are in develop mode this IS a Hotfix
4860  set version_level patch
4861  }
4862 
4863  if {$M == -1} {
4864  Msg CriticalWarning "Tag $tag does not contain a Hog compatible version in this repository."
4865  exit
4866  #set ver v0.0.0
4867  } elseif {$mr == 0} {
4868  switch $version_level {
4869  minor {
4870  incr m
4871  set p 0
4872  }
4873  major {
4874  incr M
4875  set m 0
4876  set p 0
4877  }
4878  default {
4879  incr p
4880  }
4881  }
4882  } else {
4883  Msg Info "No tag contains $SHA, will use most recent tag $tag. As this is a candidate tag, the patch level will be kept at $p."
4884  }
4885  set ver v$M.$m.$p
4886  }
4887  } else {
4888  #The tag in $result contains the current SHA
4889  set vers [split $result "\n"]
4890  set ver [lindex $vers 0]
4891  foreach v $vers {
4892  if {[regexp {^v.*$} $v]} {
4893  set un_ver $ver
4894  set ver $v
4895  break
4896  }
4897  }
4898  }
4899  } else {
4900  Msg CriticalWarning "Error while trying to find tag for $SHA"
4901  set ver "v0.0.0"
4902  }
4903  }
4904  lassign [ExtractVersionFromTag $ver] M m c mr
4905 
4906  if {$mr > -1} {
4907  # Candidate tab
4908  set M [format %02X $M]
4909  set m [format %02X $m]
4910  set c [format %04X $c]
4911  } elseif {$M > -1} {
4912  # official tag
4913  set M [format %02X $M]
4914  set m [format %02X $m]
4915  set c [format %04X $c]
4916  } else {
4917  Msg Warning "Tag does not contain a properly formatted version: $ver"
4918  set M [format %02X 0]
4919  set m [format %02X 0]
4920  set c [format %04X 0]
4921  }
4922 
4923  return $M$m$c
4924 }
4925 
4926 ## @brief Handle git commands
4927 #
4928 #
4929 # @param[in] command: the git command to be run including refs (branch, tags, sha, etc.), except files.
4930 # @param[in] files: files given to git as argument. They will always be separated with -- to avoid weird accidents
4931 #
4932 # @returns the output of the git command
4933 proc Git {command {files ""}} {
4934  lassign [GitRet $command $files] ret result
4935  if {$ret != 0} {
4936  Msg Error "Code $ret returned by git running: $command -- $files"
4937  }
4938 
4939  return $result
4940 }
4941 
4942 
4943 # @brief Get the name of the module in a HDL file. If module is not found, it returns an empty string
4944 #
4945 # @param[in] filename The name of the hdl file
4946 
4947 proc GetModuleName {filename} {
4948  # Check if the file exists
4949  if {![file exists $filename]} {
4950  Msg CriticalWarning "Error: File $filename does not exist."
4951  return ""
4952  }
4953 
4954  # Open the file for reading
4955  set fileId [open $filename r]
4956 
4957  # Read the content of the file
4958  set file_content [read $fileId]
4959 
4960  # Close the file
4961  close $fileId
4962 
4963 
4964  if {[file extension $filename] == ".vhd" || [file extension $filename] == ".vhdl"} {
4965  # Convert the file content to lowercase for case-insensitive matching
4966  set file_content [string tolower $file_content]
4967  # Regular expression to match the entity name after the 'entity' keyword
4968  set pattern {(?m)^\s*entity\s+(\S+)\s+is}
4969  } elseif {[file extension $filename] == ".v" || [file extension $filename] == ".sv"} {
4970  # Regular expression to match the module name after the 'module' keyword
4971  set pattern {\n\s*module\s*(\w+)(\s*|\(|\n)}
4972  } else {
4973  Msg Debug "File is neither VHDL nor Verilog... Returning empty string..."
4974  return "'"
4975  }
4976 
4977  # Search for the module name using the regular expression
4978  if {[regexp $pattern $file_content match module_name]} {
4979  return $module_name
4980  } else {
4981  Msg Debug "No module was found in $filename. Returning an empty string..."
4982  return ""
4983  }
4984 }
4985 
4986 ## Get a dictionary of verilog generics with their types for a given file
4987 #
4988 # @param[in] file File to read Generics from
4989 proc GetVerilogGenerics {file} {
4990  set fp [open $file r]
4991  set data [read $fp]
4992  close $fp
4993  set lines []
4994 
4995  # read in the verilog file and remove comments
4996  foreach line [split $data "\n"] {
4997  regsub "^\\s*\/\/.*" $line "" line
4998  regsub "(.*)\/\/.*" $line {\1} line
4999  if {![string equal $line ""]} {
5000  append lines $line " "
5001  }
5002  }
5003 
5004  # remove block comments also /* */
5005  regsub -all {/\*.*\*/} $lines "" lines
5006 
5007  # create a list of characters to split for tokenizing
5008  set punctuation [list]
5009  foreach char [list "(" ")" ";" "," " " "!" "<=" ":=" "=" "\[" "\]"] {
5010  lappend punctuation $char "\000$char\000"
5011  }
5012 
5013  # split the file into tokens
5014  set tokens [split [string map $punctuation $lines] \000]
5015 
5016  set parameters [dict create]
5017 
5018  set PARAM_NAME 1
5019  set PARAM_VALUE 2
5020  set LEXING 3
5021  set PARAM_WIDTH 4
5022  set state $LEXING
5023 
5024  # loop over the generic lines
5025  foreach token $tokens {
5026  set token [string trim $token]
5027  if {![string equal "" $token]} {
5028  if {[string equal [string tolower $token] "parameter"]} {
5029  set state $PARAM_NAME
5030  } elseif {[string equal $token ")"] || [string equal $token ";"]} {
5031  set state $LEXING
5032  } elseif {$state == $PARAM_WIDTH} {
5033  if {[string equal $token "\]"]} {
5034  set state $PARAM_NAME
5035  }
5036  } elseif {$state == $PARAM_VALUE} {
5037  if {[string equal $token ","]} {
5038  set state $PARAM_NAME
5039  } elseif {[string equal $token ";"]} {
5040  set state $LEXING
5041  } else {
5042 
5043  }
5044  } elseif {$state == $PARAM_NAME} {
5045  if {[string equal $token "="]} {
5046  set state $PARAM_VALUE
5047  } elseif {[string equal $token "\["]} {
5048  set state $PARAM_WIDTH
5049  } elseif {[string equal $token ","]} {
5050  set state $PARAM_NAME
5051  } elseif {[string equal $token ";"]} {
5052  set state $LEXING
5053  } elseif {[string equal $token ")"]} {
5054  set state $LEXING
5055  } else {
5056  dict set parameters $token "integer"
5057  }
5058  }
5059  }
5060  }
5061 
5062  return $parameters
5063 }
5064 
5065 ## Get a dictionary of VHDL generics with their types for a given file
5066 #
5067 # @param[in] file File to read Generics from
5068 # @param[in] entity The entity from which extracting the generics
5069 proc GetVhdlGenerics {file {entity ""}} {
5070  set fp [open $file r]
5071  set data [read $fp]
5072  close $fp
5073  set lines []
5074 
5075  # read in the vhdl file and remove comments
5076  foreach line [split $data "\n"] {
5077  regsub "^\\s*--.*" $line "" line
5078  regsub "(.*)--.*" $line {\1} line
5079  if {![string equal $line ""]} {
5080  append lines $line " "
5081  }
5082  }
5083 
5084  # extract the generic block
5085  set generic_block ""
5086  set generics [dict create]
5087 
5088  if {1 == [string equal $entity ""]} {
5089  regexp {(?i).*entity\s+([^\s]+)\s+is} $lines _ entity
5090  }
5091 
5092  set generics_regexp "(?i).*entity\\s+$entity\\s+is\\s+generic\\s*\\((.*)\\)\\s*;\\s*port.*end.*$entity"
5093 
5094  if {[regexp $generics_regexp $lines _ generic_block]} {
5095  # loop over the generic lines
5096  foreach line [split $generic_block ";"] {
5097  # split the line into the generic + the type
5098  regexp {(.*):\s*([A-Za-z0-9_]+).*} $line _ generic type
5099 
5100  # one line can have multiple generics of the same type, so loop over them
5101  set splits [split $generic ","]
5102  foreach split $splits {
5103  dict set generics [string trim $split] [string trim $type]
5104  }
5105  }
5106  }
5107  return $generics
5108 }
5109 
5110 ## @brief Runs a GHDL command and returns its output and exit state
5111 proc GHDL {command logfile} {
5112  set ret [catch {exec -ignorestderr ghdl {*}$command >>& $logfile} result options]
5113  # puts "ret: $ret"
5114  # puts "result: $result\n"
5115  # puts "options: $options"
5116  # puts "*********"
5117  return [list $ret $result]
5118 }
5119 
5120 ## @brief Handle git commands without causing an error if ret is not 0
5121 #
5122 # It can be used with lassign like this: lassign [GitRet <git command> <possibly files> ] ret result
5123 #
5124 # @param[in] command: the git command to be run including refs (branch, tags, sha, etc.), except files.
5125 # @param[in] files: files given to git as argument. They will always be separated with -- to avoid weird accidents
5126 # Sometimes you need to remove the --. To do that just set files to " "
5127 #
5128 # @returns a list of 2 elements: the return value (0 if no error occurred) and the output of the git command
5129 proc GitRet {command {files ""}} {
5130  global env
5131  if {$files eq ""} {
5132  set ret [catch {exec -ignorestderr git {*}$command} result]
5133  } else {
5134  set ret [catch {exec -ignorestderr git {*}$command -- {*}$files} result]
5135  }
5136  return [list $ret $result]
5137 }
5138 
5139 ## @brief Check git version installed in this machine
5140 #
5141 # @param[in] target_version the version required by the current project
5142 #
5143 # @return Returns 1, if the system git version is greater or equal to the target
5144 proc GitVersion {target_version} {
5145  set ver [split $target_version "."]
5146  set v [Git --version]
5147  #Msg Info "Found Git version: $v"
5148  set current_ver [split [lindex $v 2] "."]
5149  set target [expr {[lindex $ver 0] * 100000 + [lindex $ver 1] * 100 + [lindex $ver 2]}]
5150  set current [expr {[lindex $current_ver 0] * 100000 + [lindex $current_ver 1] * 100 + [lindex $current_ver 2]}]
5151  return [expr {$target <= $current}]
5152 }
5153 
5154 ## @brief Check if a file is present in an Rclone remote repository
5155 #
5156 # The output of rclone is captured rather than printed, so that the error messages that rclone
5157 # emits when the file (or its parent directory) is not there do not pollute the Hog log.
5158 # Any other rclone failure (e.g. wrong credentials, unreachable remote) is reported instead.
5159 #
5160 # @param[in] remote_file: the full rclone path of the file to look for
5161 # @param[in] config_path: the rclone configuration file to be used
5162 #
5163 # @return 1 if the file exists, 0 if it does not exist or if rclone could not be run
5164 proc RcloneFileExists {remote_file config_path} {
5165  if {[catch {exec rclone ls $remote_file --config $config_path 2>@1} result opt] == 0} {
5166  return 1
5167  }
5168  # rclone exits with 3 (directory not found) or 4 (file not found) when the file is simply not there
5169  set rclone_ret [lindex [dict get $opt -errorcode] end]
5170  if {$rclone_ret ne "3" && $rclone_ret ne "4"} {
5171  Msg CriticalWarning "Could not check if $remote_file is in the Rclone repository: $result"
5172  } else {
5173  Msg Debug "$remote_file not found in the Rclone repository (rclone exit code $rclone_ret)."
5174  }
5175  return 0
5176 }
5177 
5178 ## @brief Copy IP generated files from/to a remote o local directory (possibly EOS)
5179 #
5180 # @param[in] what_to_do: the action you want to perform, either
5181 # "push", if you want to copy the local IP synth result to the remote directory
5182 # "pull" if you want to copy the files from thre remote directory to your local repository
5183 # @param[in] xci_file: the .xci file of the IP you want to handle
5184 # @param[in] ip_path: the path of the directory you want the IP to be saved (possibly EOS)
5185 # @param[in] repo_path: the main path of your repository
5186 # @param[in] gen_dir: the directory where generated files are placed, \
5187 # by default the files are placed in the same folder as the .xci
5188 # @param[in] force: if not set to 0, will copy the IP to the remote directory even if it is already present
5189 #
5190 proc HandleIP {what_to_do xci_file ip_path repo_path on_eos on_rclone rclone_config_path {gen_dir "."} {force 0}} {
5191  global env
5192  if {!($what_to_do eq "push") && !($what_to_do eq "pull")} {
5193  Msg Error "You must specify push or pull as first argument."
5194  }
5195 
5196  if {[catch {package require tar} TARPACKAGE]} {
5197  Msg CriticalWarning "Cannot find package tar. You can fix this by installing package \"tcllib\""
5198  return -1
5199  }
5200 
5201  set old_path [pwd]
5202  cd $repo_path
5203 
5204  if {!([file exists $xci_file])} {
5205  Msg CriticalWarning "Could not find $xci_file."
5206  cd $old_path
5207  return -1
5208  }
5209 
5210 
5211  set xci_path [file dirname $xci_file]
5212  set xci_name [file tail $xci_file]
5213  set xci_ip_name [file rootname [file tail $xci_file]]
5214  set xci_dir_name [file tail $xci_path]
5215  set gen_path $gen_dir
5216 
5217  set hash [Md5Sum $xci_file]
5218  set file_name $xci_name\_$hash
5219 
5220  # Check if the IP is a subcore of a BD file
5221 
5222  set scope [get_property -quiet SCOPE [get_ips $xci_ip_name]]
5223  if {$scope != ""} {
5224  Msg Debug "IP $xci_name is a subcore of a BD file, will not pull/push it from/to the remote directory."
5225  return 0
5226  }
5227 
5228  Msg Info "Preparing to $what_to_do IP: $xci_name ($file_name)."
5229 
5230  if {$what_to_do eq "push"} {
5231  set will_copy 0
5232  set will_remove 0
5233  if {$on_rclone == 1} {
5234  # lassign [ExecuteRet rclone ls $ip_path/$file_name.tar --config $rclone_config_path] ret result
5235  if {[RcloneFileExists $ip_path/$file_name.tar $rclone_config_path] == 0} {
5236  set will_copy 1
5237  } else {
5238  if {$force == 0} {
5239  Msg Info "IP already in the Rclone repository, will not copy..."
5240  } else {
5241  Msg Info "IP already in the Rclone repository, will forcefully replace..."
5242  set will_copy 1
5243  set will_remove 1
5244  }
5245  }
5246  } elseif {$on_eos == 1} {
5247  lassign [eos "ls $ip_path/$file_name.tar"] ret result
5248  if {$ret != 0} {
5249  set will_copy 1
5250  } else {
5251  if {$force == 0} {
5252  Msg Info "IP already in the EOS repository, will not copy..."
5253  } else {
5254  Msg Info "IP already in the EOS repository, will forcefully replace..."
5255  set will_copy 1
5256  set will_remove 1
5257  }
5258  }
5259  } else {
5260  if {[file exists "$ip_path/$file_name.tar"]} {
5261  if {$force == 0} {
5262  Msg Info "IP already in the local repository, will not copy..."
5263  } else {
5264  Msg Info "IP already in the local repository, will forcefully replace..."
5265  set will_copy 1
5266  set will_remove 1
5267  }
5268  } else {
5269  set will_copy 1
5270  }
5271  }
5272 
5273  if {$will_copy == 1} {
5274  # Check if there are files in the .gen directory first and copy them into the right place
5275  Msg Info "Looking for generated files in $gen_path..."
5276  set ip_gen_files [glob -nocomplain $gen_path/*]
5277 
5278  #here we should remove the .xci file from the list if it's there
5279 
5280  if {[llength $ip_gen_files] > 0} {
5281  Msg Info "Found some IP synthesised files matching $xci_ip_name"
5282  if {$will_remove == 1} {
5283  Msg Info "Removing old synthesised directory $ip_path/$file_name.tar..."
5284  if {$on_rclone == 1} {
5285  lassign [ExecuteRet rclone delete $ip_path/$file_name.tar --config $rclone_config_path] ret result
5286  if {$ret != 0} {
5287  Msg CriticalWarning "Could not delete file from Rclone: $result"
5288  }
5289  } elseif {$on_eos == 1} {
5290  eos "rm -rf $ip_path/$file_name.tar" 5
5291  } else {
5292  file delete -force "$ip_path/$file_name.tar"
5293  }
5294  }
5295 
5296  Msg Info "Creating local archive with IP generated files..."
5297  set tar_files []
5298 
5299  set at_least_one_long 0
5300  foreach f $ip_gen_files {
5301  set new_f "[Relative [file normalize $repo_path] $f]"
5302  set len [string length $new_f]
5303  if {$len > 254} {
5304  Msg Warning "One file in $xci_ip_name is too long ($len chars): $new_f"
5305  set at_least_one_long 1
5306  }
5307  lappend tar_files $new_f
5308  }
5309 
5310  Msg Debug "Tar files: $tar_files"
5311  if {$at_least_one_long == 1} {
5312  Msg Warning "Using regular tar, please cross your fingers..."
5313  #lassign [ExecuteRet tar --format=pax -cf $file_name.tar {*}$tar_files] ret_tar result_tar
5314  lassign [ExecuteRet tar -cf $file_name.tar {*}$tar_files] ret_tar result_tar
5315  if {$ret_tar != 0} {
5316  Msg CriticalWarning "Something went wrong when using regular tar. Error message: $result_tar"
5317  }
5318  } else {
5319  if {[catch { ::tar::create $file_name.tar $tar_files } err]} {
5320  Msg Warning "Tcl built-in tar failed: $err, will try regular tar..."
5321  #lassign [ExecuteRet tar --format=pax -cf $file_name.tar {*}$tar_files] ret_tar result_tar
5322  lassign [ExecuteRet tar -cf $file_name.tar {*}$tar_files] ret_tar result_tar
5323  if {$ret_tar != 0} {
5324  Msg CriticalWarning "Something went wrong when using regular tar. Error message: $result_tar"
5325  }
5326  }
5327  }
5328 
5329  Msg Info "Copying IP generated files for $xci_name..."
5330  if {$on_rclone == 1} {
5331  lassign [ExecuteRet rclone copyto $file_name.tar $ip_path/$file_name.tar --config $rclone_config_path] ret result
5332  if {$ret != 0} {
5333  Msg CriticalWarning "Something went wrong when copying the IP files to Rclone. Error message: $result"
5334  }
5335  } elseif {$on_eos == 1} {
5336  lassign [ExecuteRet xrdcp -f -s $file_name.tar $::env(EOS_MGM_URL)//$ip_path/] ret msg
5337  if {$ret != 0} {
5338  Msg CriticalWarning "Something went wrong when copying the IP files to EOS. Error message: $msg"
5339  }
5340  } else {
5341  Copy "$file_name.tar" "$ip_path/"
5342  }
5343  Msg Info "Removing local archive"
5344  file delete $file_name.tar
5345  } else {
5346  Msg Warning "Could not find synthesized files matching $gen_path/$file_name*"
5347  }
5348  }
5349  } elseif {$what_to_do eq "pull"} {
5350  if {$on_rclone == 1} {
5351  # lassign [ExecuteRet rclone ls $ip_path/$file_name.tar --config $rclone_config_path] ret result
5352  if {[RcloneFileExists $ip_path/$file_name.tar $rclone_config_path] == 0} {
5353  Msg Info "Nothing for $xci_name was found in the Rclone repository, cannot pull."
5354  cd $old_path
5355  return -1
5356  } else {
5357  Msg Info "IP $xci_name found in the Rclone repository $ip_path, copying it locally to $repo_path..."
5358  lassign [ExecuteRet rclone copyto $ip_path/$file_name.tar $file_name.tar --config $rclone_config_path] ret_copy result_copy
5359  if {$ret_copy != 0} {
5360  Msg CriticalWarning "Something went wrong when copying the IP files from Rclone. Error message: $result_copy"
5361  }
5362  }
5363  } elseif {$on_eos == 1} {
5364  lassign [eos "ls $ip_path/$file_name.tar"] ret result
5365  if {$ret != 0} {
5366  Msg Info "Nothing for $xci_name was found in the EOS repository, cannot pull."
5367  cd $old_path
5368  return -1
5369  } else {
5370  set remote_tar "$::env(EOS_MGM_URL)//$ip_path/$file_name.tar"
5371  Msg Info "IP $xci_name found in the repository $remote_tar, copying it locally to $repo_path..."
5372 
5373  lassign [ExecuteRet xrdcp -f -r -s $remote_tar $repo_path] ret msg
5374  if {$ret != 0} {
5375  Msg CriticalWarning "Something went wrong when copying the IP files to EOS. Error message: $msg"
5376  }
5377  }
5378  } else {
5379  if {[file exists "$ip_path/$file_name.tar"]} {
5380  Msg Info "IP $xci_name found in local repository $ip_path/$file_name.tar, copying it locally to $repo_path..."
5381  Copy $ip_path/$file_name.tar $repo_path
5382  } else {
5383  Msg Info "Nothing for $xci_name was found in the local IP repository, cannot pull."
5384  cd $old_path
5385  return -1
5386  }
5387  }
5388 
5389  if {[file exists $file_name.tar]} {
5390  remove_files $xci_file
5391  Msg Info "Extracting IP files from archive to $repo_path..."
5392  ::tar::untar $file_name.tar -dir $repo_path -noperms
5393  Msg Info "Removing local archive"
5394  file delete $file_name.tar
5395  add_files -norecurse -fileset sources_1 $xci_file
5396  }
5397  }
5398  cd $old_path
5399  return 0
5400 }
5401 
5402 ## Convert hex version to M.m.p string
5403 #
5404 # @param[in] version the version (in 32-bit hexadecimal format 0xMMmmpppp) to be converted
5405 #
5406 # @return a string containing the version in M.m.p format
5407 #
5408 proc HexVersionToString {version} {
5409  scan [string range $version 0 1] %x M
5410  scan [string range $version 2 3] %x m
5411  scan [string range $version 4 7] %x c
5412  return "$M.$m.$c"
5413 }
5414 
5415 # @brief Import TCL Lib from an external installation for Libero, Synplify and Diamond
5416 proc ImportTclLib {} {
5417  global env
5418  if {[IsLibero] || [IsDiamond] || [IsSynplify]} {
5419  if {[info exists env(HOG_TCLLIB_PATH)]} {
5420  lappend auto_path $env(HOG_TCLLIB_PATH)
5421  return 1
5422  } else {
5423  puts "ERROR: To run Hog with Microsemi Libero SoC or Lattice Diamond, you need to define the HOG_TCLLIB_PATH variable."
5424  return 0
5425  }
5426  }
5427 }
5428 
5429 # @brief Initialise the Launcher and returns a list of project parameters: directive project project_name group_name repo_path old_path bin_dir top_path cmd ide
5430 #
5431 # @param[in] script The launch.tcl script
5432 # @param[in] tcl_path The launch.tcl script path
5433 # @param[in] parameters The allowed parameters for launch.tcl
5434 # @param[in] commands The allowed directives for launch.tcl
5435 # @param[in] argv The input arguments passed to launch.tcl
5436 # @param[in] custom_commands Custom commands to be added to the list of commands
5437 
5438 proc InitLauncher {script tcl_path parameters commands argv {custom_commands ""}} {
5439  set repo_path [file normalize "$tcl_path/../.."]
5440  set old_path [pwd]
5441  set bin_path [file normalize "$tcl_path/../../bin"]
5442  set top_path [file normalize "$tcl_path/../../Top"]
5443 
5444  set cmd_lines [split $commands "\n"]
5445 
5446  set command_options [dict create]
5447  set directive_descriptions [dict create]
5448  set directive_names [dict create]
5449  set common_directive_names [dict create]
5450  set directives_with_optional_projects ""
5451  set custom_command ""
5452  set custom_command_options ""
5453 
5454  foreach l $cmd_lines {
5455  #excludes direcitve with a # just after the \{
5456  if {[regexp {\\(.*) \{\#} $l minc d]} {
5457  lappend directives_with_projects $d
5458  set current_directive $d
5459  }
5460 
5461  if {[regexp {^[^#]* allow_empty_proj} $l minc dd]} {
5462  lappend directives_with_optional_projects $current_directive
5463  }
5464 
5465  #gets all the regexes
5466  if {[regexp {\\(.*) \{} $l minc regular_expression]} {
5467  lappend directive_regex $regular_expression
5468  }
5469 
5470  #gets all common directives
5471  if {[regexp {\#\s*NAME(\*)?:\s*(.*)\s*} $l minc star name]} {
5472  dict set directive_names $name $regular_expression
5473  if {$star eq "*"} {
5474  dict set common_directive_names $name $regular_expression
5475  }
5476  }
5477  set directive_names [DictSort $directive_names]
5478  set common_directive_names [DictSort $common_directive_names]
5479 
5480  #gets all the descriptions
5481  if {[regexp {\#\s*DESCRIPTION:\s*(.*)\s*} $l minc x]} {
5482  dict set directive_descriptions $regular_expression $x
5483  }
5484 
5485  #gets all the list of options
5486  if {[regexp {\#\s*OPTIONS:\s*(.*)\s*} $l minc x]} {
5487  dict set command_options $regular_expression [split [regsub -all {[ \t\n]+} $x {}] ","]
5488  }
5489  }
5490 
5491  set short_usage "usage: ./Hog/Do \[OPTIONS\] <directive> \[project\]\n\nMost common directives (case insensitive):"
5492 
5493  dict for {key value} $common_directive_names {
5494  set short_usage "$short_usage\n - $key: [dict get $directive_descriptions $value]"
5495  }
5496 
5497  if {[string length $custom_commands] > 0} {
5498  Msg Debug "Found custom commands to add to short short_usage."
5499  set short_usage "$short_usage\n\nCustom commands:"
5500  dict for {key command} $custom_commands {
5501  Msg Debug "Adding $key : [dict get $command DESCRIPTION]"
5502  set short_usage "$short_usage\n - $key: [dict get $command DESCRIPTION]"
5503  }
5504  }
5505 
5506 
5507  set short_usage "$short_usage\n\n\
5508  To see all the available directives, run:\n./Hog/Do HELP\n\n\
5509  To list available options for the chosen directive run:\n\
5510  ./Hog/Do <directive> HELP\n
5511  "
5512 
5513  set usage "usage: ./Hog/Do \[OPTIONS\] <directive> \[project\]\n\nDirectives (case insensitive):"
5514 
5515  dict for {key value} $directive_names {
5516  set usage "$usage\n - $key: [dict get $directive_descriptions $value]"
5517  }
5518 
5519  # if length of custom commands is greater than 0, add them to the short usage"
5520  if {[string length $custom_commands] > 0} {
5521  Msg Debug "Found custom commands to add to short usage."
5522  set usage "$usage\n\nCustom commands:"
5523  dict for {key command} $custom_commands {
5524  Msg Debug "Adding $key : [dict get $command DESCRIPTION]"
5525  set usage "$usage\n - $key: [dict get $command DESCRIPTION]"
5526  }
5527  }
5528 
5529 
5530  set usage "$usage\n\nTo list available options for the chosen directive run:\n./Hog/Do <directive> HELP"
5531 
5532  if {[IsTclsh]} {
5533  #Just display the logo the first time, not when the script is run in the IDE
5534  Logo $repo_path
5535  }
5536 
5537  # Check if HogEnv.conf exists and parse it
5538  if {[file exists [Hog::LoggerLib::GetUserFilePath "HogEnv.conf"]]} {
5539  Msg Debug "HogEnv.conf found"
5540  set loggerdict [Hog::LoggerLib::ParseTOML [Hog::LoggerLib::GetUserFilePath "HogEnv.conf"]]
5541  set HogEnvDict [Hog::LoggerLib::GetTOMLDict]
5542  Hog::LoggerLib::PrintTOMLDict $HogEnvDict
5543  }
5544 
5545 
5546  if {[catch {package require cmdline} ERROR]} {
5547  Msg Debug "The cmdline Tcl package was not found, sourcing it from Hog..."
5548  source $tcl_path/utils/cmdline.tcl
5549  }
5550 
5551  set argv [regsub -all {(?i) HELP\y} $argv " -help"]
5552 
5553 
5554  #Gather up all custom parameters
5555  #NOTE: right now user can accidentally redefine their own custom parameters, there is no check for that...
5556  set custom_parameters [list]
5557  dict for {key command} $custom_commands {
5558  set custom_parameters [concat $custom_parameters [dict get $command CUSTOM_OPTIONS]]
5559  }
5560 
5561  lassign [GetOptions $argv [concat $custom_parameters $parameters]] option_list arg_list
5562 
5563  if {[IsInList "-all" $option_list]} {
5564  set list_all 1
5565  } else {
5566  set list_all 2
5567  }
5568 
5569  #option_list will be emptied by the next instruction
5570 
5571  # Argv here is modified and the options are removed
5572  set directive [string toupper [lindex $arg_list 0]]
5573  set min_n_of_args 0
5574  set max_n_of_args 2
5575  set argument_is_no_project 1
5576 
5577  set NO_DIRECTIVE_FOUND 0
5578  switch -regexp -- $directive "$commands"
5579 
5580  if {$NO_DIRECTIVE_FOUND == 1} {
5581  if {[string length $custom_commands] > 0 && [dict exists $custom_commands $directive]} {
5582  set custom_command $directive
5583  set custom_command_dict [DictGet $custom_commands $directive]
5584  set custom_command_hog_parameters [DictGet $custom_command_dict OPTIONS]
5585  set custom_command_options [DictGet $custom_command_dict CUSTOM_OPTIONS]
5586  set custom_command_options [concat $custom_command_hog_parameters $custom_command_options]
5587  } else {
5588  Msg Status "ERROR: Unknown directive $directive.\n\n"
5589  puts $usage
5590  exit
5591  }
5592  }
5593 
5594  if {[IsInList $directive $directives_with_projects 1]} {
5595  set argument_is_no_project 0
5596  }
5597 
5598  if {[IsInList "-help" $option_list] || [IsInList "-?" $option_list] || [IsInList "-h" $option_list]} {
5599  if {$directive != ""} {
5600  if {[IsInList $directive $directives_with_projects 1]} {
5601  puts "usage: ./Hog/Do \[OPTIONS\] $directive <project>\n"
5602  } elseif {[regexp "^COMPSIM(LIB)?$" $directive]} {
5603  puts "usage: ./Hog/Do \[OPTIONS\] $directive <simulator>\n"
5604  } else {
5605  puts "usage: ./Hog/Do \[OPTIONS\] $directive \n"
5606  }
5607 
5608  dict for {dir desc} $directive_descriptions {
5609  if {[regexp $dir $directive]} {
5610  puts "$desc\n"
5611  break
5612  }
5613  }
5614 
5615  #if custom command, parse custom options instead
5616  if {$custom_command ne ""} {
5617  if {[llength $custom_command_options] > 0} {
5618  puts "Available options:"
5619  }
5620  foreach custom_option $custom_command_options {
5621  set n [llength $custom_option]
5622  if {$n == 2} {
5623  lassign $custom_option opt help
5624  puts " -$opt"
5625  puts " $help"
5626  } elseif {$n == 3} {
5627  lassign $custom_option opt def help
5628  puts " -$opt <argument>"
5629  if {$def ne ""} {
5630  puts " $help (default: $def)"
5631  } else {
5632  puts " $help"
5633  }
5634  } else {
5635  Msg Warning "Custom option spec has invalid arity (expected 2 or 3): $custom_option"
5636  }
5637  }
5638  }
5639 
5640  dict for {dir opts} $command_options {
5641  if {[regexp $dir $directive]} {
5642  puts "Available options:"
5643  foreach opt $opts {
5644  foreach par $parameters {
5645  if {$opt == [lindex $par 0]} {
5646  if {[regexp {\.arg$} $opt]} {
5647  set opt_name [regsub {\.arg$} $opt ""]
5648  puts " -$opt_name <argument>"
5649  } else {
5650  puts " -$opt"
5651  }
5652  puts " [lindex $par [llength $par]-1]"
5653  }
5654  }
5655  }
5656  puts ""
5657  }
5658  }
5659  } else {
5660  puts $usage
5661  }
5662  # Msg Info [cmdline::usage $parameters $usage]
5663  exit 0
5664  }
5665 
5666  # Gather the options supported by the chosen directive
5667  set directive_options ""
5668  set directive_found 0
5669  if {$custom_command ne ""} {
5670  set directive_options $custom_command_options
5671  set directive_found 1
5672  } else {
5673  dict for {dir opts} $command_options {
5674  if {[regexp $dir $directive]} {
5675  set directive_options $opts
5676  set directive_found 1
5677  break
5678  }
5679  }
5680  }
5681 
5682  # Get the directive name without `.arg` suffix
5683  set directive_option_names {}
5684  foreach opt $directive_options {
5685  lappend directive_option_names [regsub {\.arg$} [lindex $opt 0] ""]
5686  }
5687 
5688  if {$custom_command ne ""} {
5689  set parameters [concat $parameters $custom_command_options]
5690  }
5691 
5692  if {[catch {array set options [cmdline::getoptions option_list $parameters $usage]} err]} {
5693  Msg Status "\nERROR: Syntax error, probably unknown option.\n\n USAGE: $err"
5694  exit 1
5695  }
5696 
5697  # Ignore the options that are not supported by the chosen directive, restoring their default value
5698  if {$directive_found == 1} {
5699  set default_option_list {}
5700  array set default_options [cmdline::getoptions default_option_list $parameters $usage]
5701  foreach {key value} [array get options] {
5702  if {[IsInList $key $directive_option_names] || ![info exists default_options($key)]} {
5703  continue
5704  }
5705  if {$value ne $default_options($key)} {
5706  Msg Warning "Option -$key is not supported by directive $directive, ignoring it."
5707  set options($key) $default_options($key)
5708  }
5709  }
5710  }
5711 
5712  if {[llength $arg_list] <= $min_n_of_args || [llength $arg_list] > $max_n_of_args} {
5713  Msg Status "\nERROR: Wrong number of arguments: [llength $argv]"
5714  puts $short_usage
5715  exit 1
5716  }
5717 
5718  set project [lindex $arg_list 1]
5719  set optional_project [IsInList $directive $directives_with_optional_projects 1]
5720 
5721  if {$argument_is_no_project == 0} {
5722  # Remove leading Top/ or ./Top/ if in project_name
5723  regsub "^(\./)?Top/" $project "" project
5724  # Remove trailing / and spaces if in project_name
5725  regsub "/? *\$" $project "" project
5726 
5727  if {$project eq "" && $optional_project == 1} {
5728  set proj_conf 0
5729  } else {
5730  set proj_conf [ProjectExists $project $repo_path]
5731  }
5732  } else {
5733  set proj_conf 0
5734  }
5735 
5736  Msg Debug "Option list:"
5737 
5738  foreach {key value} [array get options] {
5739  Msg Debug "$key => $value"
5740  }
5741 
5742  set cmd ""
5743 
5744  if {[IsTclsh]} {
5745  # command is filled with the IDE exectuable when this function is called by Tcl scrpt
5746  if {$proj_conf != 0} {
5747  CheckLatestHogRelease $repo_path
5748 
5749  lassign [GetIDECommand $proj_conf] cmd before_tcl_script after_tcl_script end_marker
5750  Msg Info "Project $project uses $cmd IDE"
5751 
5752  ## The following is the IDE command to launch:
5753  set command "$cmd $before_tcl_script$script$after_tcl_script$argv$end_marker"
5754  } else {
5755  if {$custom_command ne ""} {
5756  if {[dict exists $custom_commands $directive IDE]} {
5757  lassign [GetIDECommand "" [dict get $custom_commands $directive IDE]] cmd before_tcl_script after_tcl_script end_marker
5758  Msg Info "Custom command: $custom_command uses $cmd IDE"
5759  set command "$cmd $before_tcl_script$script$after_tcl_script$argv$end_marker"
5760  } else {
5761  set command "custom_tcl"
5762  }
5763  } elseif {$argument_is_no_project == 1} {
5764  set command -4
5765  Msg Debug "$project will be used as first argument"
5766  } elseif {$project != ""} {
5767  #Project not given
5768  set command -1
5769  } elseif {$min_n_of_args < 0} {
5770  #Project not needed
5771  set command -3
5772  } else {
5773  #Project not found
5774  if {$optional_project == 0} {
5775  set command -2
5776  } else {
5777  set command -3
5778  }
5779  }
5780  }
5781  } else {
5782  # When the launcher is executed from within an IDE, command is set to 0
5783  set command 0
5784  }
5785 
5786  set project_group [file dirname $project]
5787  set project_name $project
5788  set project [file tail $project]
5789  Msg Debug "InitLauncher: project_group=$project_group, project_name=$project_name, project=$project"
5790 
5791  return [list $directive $project $project_name $project_group $repo_path $old_path\
5792  $bin_path $top_path $usage $short_usage $command $cmd [array get options]\
5793  $directive_options]
5794 }
5795 
5796 # @brief Returns 1 if a commit is an ancestor of another, otherwise 0
5797 #
5798 # @param[in] ancestor The potential ancestor commit
5799 # @param[in] commit The potential descendant commit
5800 proc IsCommitAncestor {ancestor commit} {
5801  lassign [GitRet "merge-base --is-ancestor $ancestor $commit"] status result
5802  if {$status == 0} {
5803  return 1
5804  } else {
5805  return 0
5806  }
5807 }
5808 
5809 proc IsDiamond {} {
5810  return [expr {[info commands sys_install] != ""}]
5811 }
5812 
5813 ## @brief Returns true if the IDE is MicroSemi Libero
5814 proc IsLibero {} {
5815  return [expr {[info commands get_libero_version] != ""}]
5816 }
5817 
5818 # @brief Returns 1 if an element is a list, 0 otherwise
5819 #
5820 # @param[in] element The element to search
5821 # @param[in] list The list to search into
5822 # @param[in] regex An optional regex to match. If 0, the element should match exactly an object in the list
5823 # @param[in] nocase If 1, perform case-insensitive comparison
5824 proc IsInList {element list {regex 0} {nocase 0}} {
5825  foreach x $list {
5826  if {$regex == 1} {
5827  if {$nocase == 1} {
5828  if {[regexp -nocase $x $element]} {
5829  return 1
5830  }
5831  } else {
5832  if {[regexp $x $element]} {
5833  return 1
5834  }
5835  }
5836  } elseif {$regex == 0} {
5837  if {$nocase == 1} {
5838  if {[string tolower $x] eq [string tolower $element]} {
5839  return 1
5840  }
5841  } else {
5842  if {$x eq $element} {
5843  return 1
5844  }
5845  }
5846  }
5847  }
5848  return 0
5849 }
5850 
5851 
5852 ## @brief Returns true, if the IDE is ISE/PlanAhead
5853 proc IsISE {} {
5854  if {[IsXilinx]} {
5855  return [expr {[string first PlanAhead [version]] == 0}]
5856  } else {
5857  return 0
5858  }
5859 }
5860 
5861 ## @brief Returns true, if IDE is Quartus
5862 proc IsQuartus {} {
5863  if {[catch {package require ::quartus::flow} result]} {
5864  # not available
5865  return 0
5866  } else {
5867  # available
5868  return 1
5869  }
5870 }
5871 
5872 ## Check if a path is absolute or relative
5873 #
5874 # @param[in] the path to check
5875 #
5876 proc IsRelativePath {path} {
5877  if {[string index $path 0] == "~"} {
5878  return 0
5879  }
5880  return [expr {[file pathtype $path] eq "relative"}]
5881 }
5882 
5883 ## @brief Returns true if the Synthesis tool is Synplify
5884 proc IsSynplify {} {
5885  return [expr {[info commands program_version] != ""}]
5886 }
5887 
5888 ## @brief Returns true, if we are in tclsh
5889 proc IsTclsh {} {
5890  return [expr {![IsQuartus] && ![IsXilinx] && ![IsVitisClassic] && ![IsVitisUnified] && ![IsLibero] && ![IsSynplify] && ![IsDiamond]}]
5891 }
5892 
5893 # @brief Find out if the given file is a Verilog or SystemVerilog file
5894 #
5895 # @param[in] file The file to check
5896 # @param[out] 1 if it's Verilog/SystemVerilog 0 if it's not
5897 #
5898 proc IsVerilog {file} {
5899  if {[file extension $file] == ".v" || [file extension $file] == ".sv"} {
5900  return 1
5901  } else {
5902  return 0
5903  }
5904 }
5905 
5906 ## @brief Find out if the given Xilinx part is a Versal chip
5907 #
5908 # @param[out] 1 if it's Versal 0 if it's not
5909 # @param[in] part The FPGA part
5910 #
5911 proc IsVersal {part} {
5912  if {[get_property ARCHITECTURE [get_parts $part]] eq "versal"} {
5913  return 1
5914  } else {
5915  return 0
5916  }
5917 }
5918 
5919 ## @brief Returns true, if the IDE is Vivado
5920 proc IsVivado {} {
5921  if {[IsXilinx]} {
5922  return [expr {[string first Vivado [version]] == 0}]
5923  } else {
5924  return 0
5925  }
5926 }
5927 
5928 ## @brief Return true, if the IDE is Xilinx (Vivado or ISE)
5929 proc IsXilinx {} {
5930  if {[info commands version] != ""} {
5931  set current_version [version]
5932  if {[string first PlanAhead $current_version] == 0 || [string first Vivado $current_version] == 0} {
5933  return 1
5934  } elseif {[string first xsct $current_version] == 0} {
5935  return 0
5936  } else {
5937  Msg Warning "This IDE has the version command but it is not PlanAhead or Vivado: $current_version"
5938  return 0
5939  }
5940  } else {
5941  return 0
5942  }
5943 }
5944 
5945 ## @brief Returns true, if the IDE is vitis_classic
5946 proc IsVitisClassic {} {
5947  if {[info exists globalSettings::vitis_classic]} {
5948  return $globalSettings::vitis_classic
5949  }
5950  return [expr {[info commands platform] != ""}]
5951 }
5952 
5953 ## @brief Returns true, if the IDE is vitis_unified
5954 proc IsVitisUnified {} {
5955  if {[info exists globalSettings::vitis_unified]} {
5956  return $globalSettings::vitis_unified
5957  }
5958  return 0
5959 }
5960 
5961 ## @brief Execute a Python command via Vitis Unified command-line tool and display output in real-time
5962 #
5963 # @param[in] python_script Full path to the Python script (e.g., PlatformCommands.py or AppCommands.py)
5964 # @param[in] command The command to execute (e.g., "create_platform", "configure_app", "app_list")
5965 # @param[in] args List of arguments to pass to the command
5966 # @param[in] error_prefix Prefix for error messages (e.g., "Failed to create platform" or "Failed to configure app")
5967 # @param[in] output_var Optional variable name to store the output (if not provided, output is only printed)
5968 # @param[out] 1 on success, 0 on failure
5969 #
5970 proc ExecuteVitisUnifiedCommand {python_script command args {error_prefix "Failed to execute command"} {output_var ""}} {
5971  set cmdlist [list vitis -s $python_script $command]
5972  foreach arg $args {
5973  lappend cmdlist $arg
5974  }
5975  lappend cmdlist 2>@1
5976 
5977  Msg Debug "Executing: vitis -s $python_script $command $args"
5978 
5979  # Set PYTHONUNBUFFERED environment variable for real-time output
5980  set ::env(PYTHONUNBUFFERED) "1"
5981 
5982  # Open pipe and configure for line buffering
5983  if {[catch {set pipe [open "|$cmdlist" "r"]} err]} {
5984  Msg Error "$error_prefix: Failed to open pipe: $err"
5985  return 0
5986  }
5987 
5988  fconfigure $pipe -buffering line
5989  set script_output ""
5990  set vitis_version ""
5991 
5992  # Patterns to identify Vitis banner messages, these will be filtered out
5993  set vitis_banner_patterns {
5994  "*Vitis Development Environment*"
5995  "*Vitis v*"
5996  "*SW Build*"
5997  "*Copyright*Xilinx*"
5998  "*Copyright*Advanced Micro Devices*"
5999  "*All Rights Reserved*"
6000  }
6001 
6002  # Read and display output line by line
6003  while {[gets $pipe line] >= 0} {
6004  if {$line ne ""} {
6005  if {[string match "*Vitis v*" $line]} {
6006  if {[regexp {Vitis\s+v([0-9]+)\.([0-9]+)(?:\.[0-9]+)?} $line -> major minor]} {
6007  set year_last_two [string range $major end-1 end]
6008  set vitis_version "$year_last_two.$minor"
6009  }
6010  }
6011 
6012  # Filter out Vitis banner messages
6013  set is_banner 0
6014  foreach pattern $vitis_banner_patterns {
6015  if {[string match $pattern $line]} {
6016  set is_banner 1
6017  break
6018  }
6019  }
6020  if {!$is_banner} {
6021  if {![string match "INFO:*" $line] && ![string match "WARNING:*" $line] && ![string match "ERROR:*" $line] && ![string match "DEBUG:*" $line]} {
6022  if {$vitis_version ne ""} {
6023  set line "INFO: \[Vitis_v$vitis_version\] $line"
6024  } else {
6025  set line "INFO: $line"
6026  }
6027  }
6028  puts "$line"
6029  append script_output "$line\n"
6030  }
6031  }
6032  }
6033 
6034  # Close pipe and check exit code
6035  set exit_code 0
6036  if {[catch {close $pipe} err]} {
6037  if {[regexp {exit (\d+)} $err -> exit_code]} {
6038  if {$exit_code != 0} {
6039  Msg Error "$error_prefix (exit code: $exit_code)"
6040  if {$output_var ne ""} {
6041  upvar $output_var output
6042  set output $script_output
6043  }
6044  return 0
6045  }
6046  } else {
6047  Msg Error "$error_prefix: $err"
6048  if {$output_var ne ""} {
6049  upvar $output_var output
6050  set output $script_output
6051  }
6052  return 0
6053  }
6054  }
6055 
6056  # Return output if requested
6057  if {$output_var ne ""} {
6058  upvar $output_var output
6059  set output $script_output
6060  }
6061 
6062  return 1
6063 }
6064 
6065 ## @brief Get the applications defined in the Vitis workspace
6066 #
6067 # In Vitis Unified this spawns an external "vitis -s" process which opens and
6068 # locks the workspace, so the result must be cached by the caller rather than
6069 # queried repeatedly.
6070 #
6071 # @param[in] vitis_workspace Path of the Vitis Unified workspace (not needed in Vitis Classic)
6072 # @param[in] python_script Full path to AppCommands.py (not needed in Vitis Classic)
6073 # @param[out] A dict with the app names as keys, or an empty string if the list could not be retrieved
6074 #
6075 proc GetVitisApps {{vitis_workspace ""} {python_script ""}} {
6076  if {[IsVitisClassic]} {
6077  # TODO: "app list -dict" return wrong configuration parameters for Vitis Classic versions older than 2022.1
6078  if {[catch {set ws_apps [app list -dict]}]} {
6079  set ws_apps ""
6080  }
6081  return $ws_apps
6082  }
6083 
6084  if {![IsVitisUnified]} {
6085  return ""
6086  }
6087 
6088  set json_output ""
6089  if {
6090  ![ExecuteVitisUnifiedCommand $python_script "app_list" [list $vitis_workspace] \
6091  "Failed to get app list from Vitis Unified workspace $vitis_workspace" json_output]
6092  } {
6093  return ""
6094  }
6095 
6096  if {[catch {package require json}]} {
6097  Msg Warning "JSON package not available for parsing Vitis Unified app list"
6098  return ""
6099  }
6100 
6101  set json_output_filtered ""
6102  if {[regexp -lineanchor {\{.*\}} $json_output json_output_filtered]} {
6103  return [json::json2dict $json_output_filtered]
6104  }
6105  return [json::json2dict $json_output]
6106 }
6107 
6108 ## @brief Find out if the given Xilinx part is a Versal chip
6109 #
6110 # @param[out] 1 if it's Zynq 0 if it's not
6111 # @param[in] part The FPGA part
6112 #
6113 proc IsZynq {part} {
6114  if {[regexp {^(xc7z|xczu).*} $part]} {
6115  return 1
6116  } else {
6117  return 0
6118  }
6119 }
6120 
6121 proc ImportGHDL {project_name repo_path simset_name simset_dict {ext_path ""}} {
6122  set list_path "$repo_path/Top/$project_name/list"
6123  lassign [GetHogFiles -list_files {.src,.ext,.sim} -ext_path $ext_path $list_path $repo_path] src_files properties filesets
6124  cd $repo_path
6125 
6126 
6127  # Get Properties
6128  set properties [DictGet $simset_dict "properties"]
6129  set options [DictGet $properties "options"]
6130 
6131  # Import GHDL files
6132  set workdir Projects/$project_name/ghdl
6133  file delete -force $workdir
6134  file mkdir $workdir
6135  set import_log "$workdir/ghdl-import-${simset_name}.log"
6136  dict for {lib sources} $src_files {
6137  set libname [file rootname $lib]
6138  foreach f $sources {
6139  if {[file extension $f] != ".vhd" && [file extension $f] != ".vhdl"} {
6140  Msg Info "File $f is not a VHDL file, copying it in workfolder..."
6141  file copy -force $f $workdir
6142  } else {
6143  set file_path [Relative $repo_path $f]
6144  set import_log_file [open $import_log "a"]
6145  puts "ghdl -i --work=$libname --workdir=$workdir -fsynopsys --ieee=standard $options $file_path"
6146  puts $import_log_file "ghdl -i --work=$libname --workdir=$workdir -fsynopsys --ieee=standard $options $file_path"
6147  close $import_log_file
6148  lassign [GHDL "-i --work=$libname --workdir=$workdir -fsynopsys --ieee=standard $options $file_path" $import_log] ret result
6149  if {$ret != 0} {
6150  Msg CriticalWarning "GHDL import failed for file $f: $result"
6151  }
6152  }
6153  }
6154  }
6155  PrintFileContent $import_log
6156 }
6157 
6158 proc LaunchGHDL {project_name repo_path simset_name simset_dict {ext_path ""}} {
6159  set top_sim ""
6160  # Setting Simulation Properties
6161  set sim_props [DictGet $simset_dict "properties"]
6162  set options [DictGet $sim_props "options"]
6163  set runopts [DictGet $sim_props "run_options"]
6164 
6165  dict for {prop_name prop_val} $sim_props {
6166  set prop_name [string toupper $prop_name]
6167  if {$prop_name == "TOP"} {
6168  set top_sim $prop_val
6169  }
6170  }
6171  set workdir $repo_path/Projects/$project_name/ghdl
6172  set make_log "$workdir/ghdl-make-${simset_name}.log"
6173  set run_log "$workdir/ghdl-run-${simset_name}.log"
6174  cd $workdir
6175  # Analyse and elaborate the design
6176  set make_log_file [open $make_log "w"]
6177 
6178  puts "ghdl -m --work=$simset_name -fsynopsys --ieee=standard $options $top_sim"
6179  puts $make_log_file "ghdl -m --work=$simset_name -fsynopsys --ieee=standard $options $top_sim"
6180  close $make_log_file
6181 
6182  lassign [GHDL "-m --work=$simset_name -fsynopsys --ieee=standard $options $top_sim" $make_log] ret result
6183  PrintFileContent $make_log
6184  if {$ret != 0} {
6185  Msg Error "GHDL make failed for $top_sim: $result"
6186  return
6187  }
6188 
6189  set run_log_file [open $run_log "w"]
6190  puts "ghdl -r --work=$simset_name -fsynopsys --ieee=standard $options $top_sim $runopts"
6191  puts $run_log_file "ghdl -r --work=$simset_name -fsynopsys --ieee=standard $options $top_sim $runopts"
6192  close $run_log_file
6193 
6194  lassign [GHDL "-r --work=$simset_name -fsynopsys --ieee=standard $options $top_sim $runopts" $run_log] ret result
6195  PrintFileContent $run_log
6196 
6197  if {$ret != 0} {
6198  Msg Error "GHDL run failed for $top_sim: $result"
6199  return
6200  }
6201 
6202  cd $repo_path
6203 }
6204 
6205 # @brief Launch the Implementation, for the current IDE and project
6206 #
6207 # @param[in] reset Reset the Implementation run
6208 # @param[in] do_create Recreate the project
6209 # @param[in] run_folder The folder where to store the run results
6210 # @param[in] project_name The name of the project
6211 # @param[in] repo_path The main path of the git repository (Default .)
6212 # @param[in] njobs The number of parallel CPU jobs for the Implementation (Default 4)
6213 proc LaunchImplementation {reset do_create run_folder project_name {repo_path .} {njobs 4} {do_bitstream 0}} {
6214  Msg Info "Starting implementation flow..."
6215  if {[IsXilinx]} {
6216  if {$reset == 1} {
6217  Msg Info "Resetting run before launching implementation..."
6218  reset_run impl_1
6219  }
6220 
6221  # check for and remove any previous timing results in the folder
6222  if {[file exist "$run_folder/timing_ok.txt"]} {
6223  file delete "$run_folder/timing_ok.txt"
6224  }
6225  if {[file exist "$run_folder/timing_error.txt"]} {
6226  file delete "$run_folder/timing_error.txt"
6227  }
6228 
6229  if {[IsISE]} {
6230  source $repo_path/Hog/Tcl/integrated/pre-implementation.tcl
6231  }
6232 
6233  if {$do_bitstream == 1} {
6234  launch_runs impl_1 -to_step [BinaryStepName [get_property PART [current_project]]] -jobs $njobs -dir $run_folder
6235  } else {
6236  launch_runs impl_1 -jobs $njobs -dir $run_folder
6237  }
6238  wait_on_run impl_1
6239 
6240  if {[IsISE]} {
6241  Msg Info "running post-implementation"
6242  source $repo_path/Hog/Tcl/integrated/post-implementation.tcl
6243  if {$do_bitstream == 1} {
6244  Msg Info "running pre-bitstream"
6245  source $repo_path/Hog/Tcl/integrated/pre-bitstream.tcl
6246  Msg Info "running post-bitstream"
6247  source $repo_path/Hog/Tcl/integrated/post-bitstream.tcl
6248  }
6249  }
6250 
6251  set prog [get_property PROGRESS [get_runs impl_1]]
6252  set status [get_property STATUS [get_runs impl_1]]
6253  Msg Info "Run: impl_1 progress: $prog, status : $status"
6254 
6255  # Check timing
6256  if {[IsISE]} {
6257  set status_file [open "$run_folder/timing.txt" "w"]
6258  puts $status_file "## $project_name Timing summary"
6259 
6260  set f [open [lindex [glob "$run_folder/impl_1/*.twr" 0]]]
6261  set errs -1
6262  while {[gets $f line] >= 0} {
6263  if {[string match "Timing summary:" $line]} {
6264  while {[gets $f line] >= 0} {
6265  if {[string match "Timing errors:*" $line]} {
6266  set errs [regexp -inline -- {[0-9]+} $line]
6267  }
6268  if {[string match "*Footnotes*" $line]} {
6269  break
6270  }
6271  puts $status_file "$line"
6272  }
6273  }
6274  }
6275 
6276  close $f
6277  close $status_file
6278 
6279  if {$errs == 0} {
6280  Msg Info "Time requirements are met"
6281  file rename -force "$run_folder/timing.txt" "$run_folder/timing_ok.txt"
6282  set timing_ok 1
6283  } else {
6284  Msg CriticalWarning "Time requirements are NOT met"
6285  file rename -force "$run_folder/timing.txt" "$run_folder/timing_error.txt"
6286  set timing_ok 0
6287  }
6288  }
6289 
6290  if {[IsVivado]} {
6291  set wns [get_property STATS.WNS [get_runs [current_run]]]
6292  set tns [get_property STATS.TNS [get_runs [current_run]]]
6293  set whs [get_property STATS.WHS [get_runs [current_run]]]
6294  set ths [get_property STATS.THS [get_runs [current_run]]]
6295  set tpws [get_property STATS.TPWS [get_runs [current_run]]]
6296 
6297  if {$wns >= 0 && $whs >= 0 && $tpws >= 0} {
6298  Msg Info "Time requirements are met"
6299  set status_file [open "$run_folder/timing_ok.txt" "w"]
6300  set timing_ok 1
6301  } else {
6302  Msg CriticalWarning "Time requirements are NOT met"
6303  set status_file [open "$run_folder/timing_error.txt" "w"]
6304  set timing_ok 0
6305  }
6306 
6307  Msg Status "*** Timing summary ***"
6308  Msg Status "WNS: $wns"
6309  Msg Status "TNS: $tns"
6310  Msg Status "WHS: $whs"
6311  Msg Status "THS: $ths"
6312  Msg Status "TPWS: $tpws"
6313 
6314  struct::matrix m
6315  m add columns 5
6316  m add row
6317 
6318  puts $status_file "## $project_name Timing summary"
6319 
6320  m add row "| **Parameter** | \"**value (ns)**\" |"
6321  m add row "| --- | --- |"
6322  m add row "| WNS: | $wns |"
6323  m add row "| TNS: | $tns |"
6324  m add row "| WHS: | $whs |"
6325  m add row "| THS: | $ths |"
6326  m add row "| TPWS: | $tpws |"
6327 
6328  puts $status_file [m format 2string]
6329  puts $status_file "\n"
6330  if {$timing_ok == 1} {
6331  puts $status_file " Time requirements are met."
6332  } else {
6333  puts $status_file "Time requirements are **NOT** met."
6334  }
6335  puts $status_file "\n\n"
6336  close $status_file
6337  }
6338 
6339  if {$prog ne "100%"} {
6340  Msg Error "Implementation error"
6341  }
6342 
6343  #Go to repository path
6344  cd $repo_path
6345  set describe [GetHogDescribe [file normalize ./Top/$project_name] $repo_path]
6346  Msg Info "Git describe set to $describe"
6347 
6348  set dst_dir [file normalize "$repo_path/bin/$project_name\-$describe"]
6349 
6350  file mkdir $dst_dir
6351 
6352  #Version table
6353  if {[file exists $run_folder/versions.txt]} {
6354  file copy -force $run_folder/versions.txt $dst_dir
6355  } else {
6356  Msg Warning "No versions file found in $run_folder/versions.txt"
6357  }
6358  #Timing file
6359  set timing_files [glob -nocomplain "$run_folder/timing_*.txt"]
6360  set timing_file [file normalize [lindex $timing_files 0]]
6361 
6362  if {[file exists $timing_file]} {
6363  file copy -force $timing_file $dst_dir/
6364  } else {
6365  Msg Warning "No timing file found, not a problem if running locally"
6366  }
6367 
6368  #### XSA here only for Versal Segmented Configuration
6369  if {[IsVersal [get_property part [current_project]]]} {
6370  if {[get_property segmented_configuration [current_project]] == 1} {
6371  Msg Info "Versal Segmented configuration detected: exporting XSA file..."
6372  set xsa_name "$dst_dir/[file tail $project_name]\-$describe.xsa"
6373  write_hw_platform -fixed -force -file $xsa_name
6374  }
6375  }
6376  } elseif {[IsQuartus]} {
6377  set revision [get_current_revision]
6378 
6379  set ic [get_global_assignment -name INCREMENTAL_COMPILATION]
6380  if {$ic ne "" && [string toupper $ic] ne "OFF"} {
6381  Msg Info "Incremental compilation enabled ($ic), running Partition Merge..."
6382  if {[catch {execute_module -tool cdb -args "--merge=on"} result]} {
6383  Msg Error "Result: $result\nPartition Merge failed. See the report file.\n"
6384  }
6385  }
6386 
6387  if {[catch {execute_module -tool fit} result]} {
6388  Msg Error "Result: $result\n"
6389  Msg Error "Place & Route failed. See the report file.\n"
6390  } else {
6391  Msg Info "\nINFO: Place & Route was successful for revision $revision.\n"
6392  }
6393 
6394  if {[catch {execute_module -tool sta -args "--do_report_timing"} result]} {
6395  Msg Error "Result: $result\n"
6396  Msg Error "Time Quest failed. See the report file.\n"
6397  } else {
6398  Msg Info "Time Quest was successfully run for revision $revision.\n"
6399  load_package report
6400  load_report
6401  set panel "Timing Analyzer||Timing Analyzer Summary"
6402  set device [get_report_panel_data -name $panel -col 1 -row_name "Device Name"]
6403  set timing_model [get_report_panel_data -name $panel -col 1 -row_name "Timing Models"]
6404  set delay_model [get_report_panel_data -name $panel -col 1 -row_name "Delay Model"]
6405  #set slack [ get_timing_analysis_summary_results -slack ]
6406  Msg Info "*******************************************************************"
6407  Msg Info "Device: $device"
6408  Msg Info "Timing Models: $timing_model"
6409  Msg Info "Delay Model: $delay_model"
6410  Msg Info "Slack:"
6411  #Msg Info $slack
6412  Msg Info "*******************************************************************"
6413  }
6414  } elseif {[IsLibero]} {
6415  Msg Info "Starting implementation flow..."
6416  if {[catch {run_tool -name {PLACEROUTE}}]} {
6417  Msg Error "PLACEROUTE FAILED!"
6418  } else {
6419  Msg Info "PLACEROUTE PASSED."
6420  }
6421 
6422  #Go to repository path
6423  cd $repo_path
6424 
6425  # Check timing
6426  Msg Info "Run VERIFYTIMING ..."
6427  if {[catch {run_tool -name {VERIFYTIMING} -script [file normalize "$repo_path/Hog/Tcl/integrated/libero_timing.tcl"]}]} {
6428  Msg CriticalWarning "VERIFYTIMING FAILED!"
6429  } else {
6430  Msg Info "VERIFYTIMING PASSED \n"
6431  }
6432 
6433  set describe [GetHogDescribe [file normalize ./Top/$project_name] $repo_path]
6434  Msg Info "Git describe set to $describe"
6435 
6436  set dst_dir [file normalize "$repo_path/bin/$project_name\-$describe"]
6437  file mkdir $dst_dir/reports
6438 
6439  #Version table
6440  if {[file exists $run_folder/versions.txt]} {
6441  file copy -force $run_folder/versions.txt $dst_dir
6442  } else {
6443  Msg Warning "No versions file found in $run_folder/versions.txt"
6444  }
6445  #Timing file
6446  set timing_file_path [file normalize "$repo_path/Projects/timing_libero.txt"]
6447  if {[file exists $timing_file_path]} {
6448  file copy -force $timing_file_path $dst_dir/reports/Timing.txt
6449  set timing_file [open $timing_file_path "r"]
6450  set status_file [open "$dst_dir/timing.txt" "w"]
6451  puts $status_file "## $project_name Timing summary\n\n"
6452  puts $status_file "| | |"
6453  puts $status_file "| --- | --- |"
6454  while {[gets $timing_file line] >= 0} {
6455  if {[string match "SUMMARY" $line]} {
6456  while {[gets $timing_file line] >= 0} {
6457  if {[string match "END SUMMARY" $line]} {
6458  break
6459  }
6460  if {[string first ":" $line] == -1} {
6461  continue
6462  }
6463  set out_string "| [string map {: | } $line] |"
6464  puts $status_file "$out_string"
6465  }
6466  }
6467  }
6468  } else {
6469  Msg Warning "No timing file found, not a problem if running locally"
6470  }
6471  } elseif {[IsDiamond]} {
6472  set force_rst ""
6473  if {$reset == 1} {
6474  set force_rst "-forceOne"
6475  }
6476  prj_run Map $force_rst
6477  prj_run PAR $force_rst
6478 
6479  # TODO: Check Timing for Diamond
6480  }
6481 }
6482 
6483 # @brief Re-generate the bitstream, for the current IDE and project (Vivado only for the moment). \
6484 # Useful for a Vivado-Vitis project to update the bitstream with a new ELF or to generate a new \
6485 # bootimage (ZYNQ) without running the full workflow.
6486 #
6487 # @param[in] project_name The name of the project
6488 # @param[in] repo_path The main path of the git repository (Default .)
6489 proc GenerateBitstreamOnly {project_name {repo_path .}} {
6490  cd $repo_path
6491 
6492  # Open the project first
6493  set project_file [file normalize "$repo_path/Projects/$project_name/$project_name.xpr"]
6494  if {![file exists $project_file]} {
6495  Msg Error "Project file not found: $project_file. Please create the project first."
6496  return
6497  }
6498 
6499 
6500  # Check if impl_1 run exists
6501  set impl_runs [get_runs -quiet impl_1]
6502  if {[llength $impl_runs] == 0} {
6503  Msg Error "Implementation run 'impl_1' does not exist. Please run implementation first."
6504  return
6505  }
6506 
6507  # The binary file is written in the standard implementation run directory,
6508  # the post-bitstream script will then copy it (and all the other artifacts) into the bin directory
6509  set run_dir [get_property DIRECTORY [get_runs impl_1]]
6510  if {![file exists $run_dir]} {
6511  Msg Error "Implementation run directory not found: $run_dir. Please check your implementation run."
6512  return
6513  }
6514  cd $run_dir
6515 
6516  Msg Info "Running pre-bitstream..."
6517  source $repo_path/Hog/Tcl/integrated/pre-bitstream.tcl
6518 
6519  Msg Info "Writing bitstream for $project_name..."
6520  open_run impl_1
6521  set top_name [GetTopModule]
6522  write_bitstream -force [file normalize "$run_dir/$top_name.bit"]
6523 
6524  Msg Info "Running post-bitstream..."
6525  source $repo_path/Hog/Tcl/integrated/post-bitstream.tcl
6526 }
6527 
6528 # @brief Launch the simulation (Vivado only for the moment)
6529 #
6530 # @param[in] project_name The name of the project
6531 # @param[in] lib_path The path to the simulation libraries
6532 # @param[in] simsets The simulation sets to simulate
6533 # @param[in] repo_path The main path of the git repository
6534 proc LaunchSimulation {project_name lib_path simsets {repo_path .} {scripts_only 0} {compile_only 0}} {
6535  if {[IsVivado]} {
6536  ##################### SIMULATION #######################
6537  set project [file tail $project_name]
6538  set main_sim_folder [file normalize "$repo_path/Projects/$project_name/$project.sim/"]
6539  set simsets_todo ""
6540  if {$simsets != ""} {
6541  dict for {simset sim_dict} $simsets {
6542  lappend simsets_todo $simset
6543  }
6544  Msg Info "Will run only the following simulation's sets (if they exist): $simsets_todo"
6545  }
6546 
6547  if {$scripts_only == 1} {
6548  Msg Info "Only generating simulation scripts, not running simulations..."
6549  }
6550 
6551  if {$compile_only == 1} {
6552  Msg Info "Only compiling simulation libraries, not running simulations..."
6553  }
6554 
6555  set failed []
6556  set success []
6557  set sim_dic [dict create]
6558 
6559  Msg Info "Retrieving list of simulation sets..."
6560  foreach s [get_filesets] {
6561  # Default behaviour, dont use simpass string and simulation is not quiet
6562  set use_simpass_str 0
6563  set quiet_sim ""
6564 
6565  set type [get_property FILESET_TYPE $s]
6566  if {$type eq "SimulationSrcs"} {
6567  if {$simsets_todo != "" && $s ni $simsets_todo} {
6568  Msg Info "Skipping $s as it was not specified with the -simset option..."
6569  continue
6570  }
6571  set sim_dict [DictGet $simsets $s]
6572  set simulator [DictGet $sim_dict "simulator"]
6573  set_property "target_simulator" $simulator [current_project]
6574  set hog_sim_props [DictGet $sim_dict "hog"]
6575  dict for {prop_name prop_val} $hog_sim_props {
6576  # If HOG_SIMPASS_STR is set, use the HOG_SIMPASS_STR string to search for in logs, after simulation is done
6577  if {[string toupper $prop_name] == "HOG_SIMPASS_STR" && $prop_val != ""} {
6578  Msg Info "Setting simulation pass string as '$prop_val'"
6579  set use_simpass_str 1
6580  set simpass_str $prop_val
6581  }
6582  if {[string toupper $prop_name] == "HOG_SILENT_SIM" && $prop_val == 1} {
6583  set quiet_sim " -quiet"
6584  } else {
6585  set quiet_sim ""
6586  }
6587  }
6588 
6589  Msg Info "Creating simulation scripts for $s..."
6590  if {[file exists $repo_path/Top/$project_name/pre-simulation.tcl]} {
6591  Msg Info "Running $repo_path/Top/$project_name/pre-simulation.tcl"
6592  source $repo_path/Top/$project_name/pre-simulation.tcl
6593  }
6594  if {[file exists $repo_path/Top/$project_name/pre-$s-simulation.tcl]} {
6595  Msg Info "Running $repo_path/Top/$project_name/pre-$s-simulation.tcl"
6596  source $repo_path/Top/$project_name/pre-$s-simulation.tcl
6597  }
6598  current_fileset -simset $s
6599  set sim_dir $main_sim_folder/$s/behav
6600  set sim_output_logfile $sim_dir/xsim/simulate.log
6601  if {([string tolower $simulator] eq "xsim")} {
6602  set sim_name "xsim:$s"
6603 
6604  set simulation_command "launch_simulation $quiet_sim -simset [get_filesets $s]"
6605  if {[catch $simulation_command log]} {
6606  # Explicitly close xsim simulation, without closing Vivado
6607  close_sim
6608  Msg CriticalWarning "Simulation failed for $s, error info: $::errorInfo"
6609  lappend failed $sim_name
6610  } else {
6611  # Explicitly close xsim simulation, without closing Vivado
6612  close_sim
6613  # If we use simpass_str, search for the string and update return code from simulation if the string is not found in simulation log
6614  if {$use_simpass_str == 1} {
6615  # Get the simulation output log
6616  # Note, xsim should always output simulation.log, hence no check for existence
6617  set file_desc [open $sim_output_logfile r]
6618  set log [read $file_desc]
6619  close $file_desc
6620 
6621  Msg Info "Searching for simulation pass string: '$simpass_str'"
6622  if {[string first $simpass_str $log] == -1} {
6623  Msg CriticalWarning "Simulation failed for $s, error info: '$simpass_str' NOT found!"
6624  lappend failed $sim_name
6625  } else {
6626  # HOG_SIMPASS_STR found, success
6627  lappend success $sim_name
6628  }
6629  } else {
6630  #Rely on simulator exit code
6631  lappend success $sim_name
6632  }
6633  }
6634  } else {
6635  Msg Info "Simulation library path is set to $lib_path."
6636  set simlib_ok 1
6637  if {!([file exists $lib_path])} {
6638  Msg Warning "Could not find simulation library path: $lib_path, $simulator simulation will not work."
6639  set simlib_ok 0
6640  }
6641 
6642  if {$simlib_ok == 1} {
6643  set_property "compxlib.${simulator}_compiled_library_dir" [file normalize $lib_path] [current_project]
6644  launch_simulation -scripts_only -simset [get_filesets $s]
6645  set top_name [get_property TOP $s]
6646  set sim_script [file normalize $sim_dir/$simulator/]
6647  Msg Info "Adding simulation script location $sim_script for $s..."
6648  lappend sim_scripts $sim_script
6649  dict append sim_dic $sim_script $s
6650  } else {
6651  Msg Error "Cannot run $simulator simulations without a valid library path"
6652  exit -1
6653  }
6654  }
6655  }
6656  }
6657 
6658  if {[info exists sim_scripts] && $scripts_only == 0} {
6659  # Only for modelsim/questasim
6660  Msg Info "Generating IP simulation targets, if any..."
6661 
6662  foreach ip [get_ips] {
6663  generate_target simulation -quiet $ip
6664  }
6665 
6666 
6667  Msg Status "\n\n"
6668  Msg Info "====== Starting simulations runs ======"
6669  Msg Status "\n\n"
6670 
6671  foreach s $sim_scripts {
6672  cd $s
6673  set cmd ./compile.sh
6674  Msg Info " ************* Compiling: $s ************* "
6675  lassign [ExecuteRet $cmd] ret log
6676  set sim_name "comp:[dict get $sim_dic $s]"
6677  if {$ret != 0} {
6678  Msg CriticalWarning "Compilation failed for $s, error info: $::errorInfo"
6679  lappend failed $sim_name
6680  } else {
6681  lappend success $sim_name
6682  }
6683  Msg Info "###################### Compilation log starts ######################"
6684  Msg Info "\n\n$log\n\n"
6685  Msg Info "###################### Compilation log ends ######################"
6686 
6687  if {$compile_only == 1} {
6688  continue
6689  }
6690  if {[file exists "./elaborate.sh"]} {
6691  set cmd ./elaborate.sh
6692  Msg Info " ************* Elaborating: $s ************* "
6693  lassign [ExecuteRet $cmd] ret log
6694  set sim_name "elab:[dict get $sim_dic $s]"
6695  if {$ret != 0} {
6696  Msg CriticalWarning "Elaboration failed for $s, error info: $::errorInfo"
6697  lappend failed $sim_name
6698  } else {
6699  lappend success $sim_name
6700  }
6701  Msg Info "###################### Elaboration log starts ######################"
6702  Msg Info "\n\n$log\n\n"
6703  Msg Info "###################### Elaboration log ends ######################"
6704  }
6705  set cmd ./simulate.sh
6706  Msg Info " ************* Simulating: $s ************* "
6707  lassign [ExecuteRet $cmd] ret log
6708 
6709 
6710  # If SIMPASS_STR is set, search log for the string
6711  if {$use_simpass_str == 1} {
6712  if {[string first $simpass_str $log] == -1} {
6713  set ret 1
6714  }
6715  } else {
6716  Msg Debug "Simulation pass string not set, relying on simulator exit code."
6717  }
6718 
6719 
6720  set sim_name "sim:[dict get $sim_dic $s]"
6721  if {$ret != 0} {
6722  Msg CriticalWarning "Simulation failed for $s, error info: $::errorInfo"
6723  lappend failed $sim_name
6724  } else {
6725  lappend success $sim_name
6726  }
6727  Msg Info "###################### Simulation log starts ######################"
6728  Msg Info "\n\n$log\n\n"
6729  Msg Info "###################### Simulation log ends ######################"
6730  }
6731  }
6732 
6733 
6734  if {[llength $success] > 0} {
6735  set successes [join $success "\n"]
6736  Msg Info "The following simulation sets were successful:\n\n$successes\n\n"
6737  }
6738 
6739  if {[llength $failed] > 0} {
6740  set failures [join $failed "\n"]
6741  Msg Error "The following simulation sets have failed:\n\n$failures\n\n"
6742  exit -1
6743  } elseif {[llength $success] > 0} {
6744  Msg Info "All the [llength $success] compilations, elaborations and simulations were successful."
6745  }
6746 
6747  Msg Info "Simulation done."
6748  } else {
6749  Msg Warning "Simulation is not yet supported for [GetIDEName]."
6750  }
6751 }
6752 
6753 # @brief Launch the RTL Analysis, for the current IDE and project
6754 #
6755 # @param[in] repo_path The main path of the git repository (Default .)
6756 proc LaunchRTLAnalysis {repo_path {pre_rtl_file ""} {post_rtl_file ""}} {
6757  if {[IsVivado]} {
6758  if {[file exists $pre_rtl_file]} {
6759  Msg Info "Found pre-rtl Tcl script $pre_rtl_file, executing it..."
6760  source $pre_rtl_file
6761  }
6762  Msg Info "Starting RTL Analysis..."
6763  cd $repo_path
6764  synth_design -rtl -name rtl_1
6765  if {[file exists $post_rtl_file]} {
6766  Msg Info "Found post-rtl Tcl script $post_rtl_file, executing it..."
6767  source $post_rtl_file
6768  }
6769  } else {
6770  Msg Warning "RTL Analysis is not yet supported for [GetIDEName]."
6771  }
6772 }
6773 
6774 # @brief Launch the synthesis, for the current IDE and project
6775 #
6776 # @param[in] reset Reset the Synthesis run
6777 # @param[in] do_create Recreate the project
6778 # @param[in] run_folder The folder where to store the run results
6779 # @param[in] project_name The name of the project
6780 # @param[in] repo_path The main path of the git repository (Default .)
6781 # @param[in] ext_path The path of source files external to the git repo (Default "")
6782 # @param[in] njobs The number of parallel CPU jobs for the synthesis (Default 4)
6783 proc LaunchSynthesis {reset do_create run_folder project_name {repo_path .} {ext_path ""} {njobs 4}} {
6784  if {[IsXilinx]} {
6785  if {$reset == 1} {
6786  Msg Info "Resetting run before launching synthesis..."
6787  reset_run synth_1
6788  }
6789  if {[IsISE]} {
6790  source $repo_path/Hog/Tcl/integrated/pre-synthesis.tcl
6791  }
6792  launch_runs synth_1 -jobs $njobs -dir $run_folder
6793  wait_on_run synth_1
6794  set prog [get_property PROGRESS [get_runs synth_1]]
6795  set status [get_property STATUS [get_runs synth_1]]
6796  Msg Info "Run: synth_1 progress: $prog, status : $status"
6797  # Copy IP reports in bin/
6798  set ips [get_ips *]
6799 
6800  #go to repository path
6801  cd $repo_path
6802 
6803  set describe [GetHogDescribe [file normalize ./Top/$project_name] $repo_path]
6804  Msg Info "Git describe set to $describe"
6805 
6806  foreach ip $ips {
6807  set xci_file [get_property IP_FILE $ip]
6808 
6809  set xci_path [file dirname $xci_file]
6810  set xci_ip_name [file rootname [file tail $xci_file]]
6811  foreach rptfile [glob -nocomplain -directory $xci_path *.rpt] {
6812  file copy $rptfile $repo_path/bin/$project_name-$describe/reports
6813  }
6814  }
6815 
6816  if {$prog ne "100%"} {
6817  Msg Error "Synthesis error, status is: $status"
6818  }
6819  } elseif {[IsQuartus]} {
6820  # TODO: Missing reset
6821  set project [file tail [file rootname $project_name]]
6822 
6823  Msg Info "Number of jobs set to $njobs."
6824  set_global_assignment -name NUM_PARALLEL_PROCESSORS $njobs
6825 
6826 
6827  # keep track of the current revision and of the top level entity name
6828  set describe [GetHogDescribe [file normalize $repo_path/Top/$project_name] $repo_path]
6829  #set top_level_name [ get_global_assignment -name TOP_LEVEL_ENTITY ]
6830  set revision [get_current_revision]
6831 
6832  #run PRE_FLOW_SCRIPT by hand
6833  set tool_and_command [split [get_global_assignment -name PRE_FLOW_SCRIPT_FILE] ":"]
6834  set tool [lindex $tool_and_command 0]
6835  set pre_flow_script [lindex $tool_and_command 1]
6836  set cmd "$tool -t $pre_flow_script quartus_map $project $revision"
6837  #Close project to avoid conflict with pre synthesis script
6838  project_close
6839 
6840  lassign [ExecuteRet {*}$cmd] ret log
6841  if {$ret != 0} {
6842  Msg Warning "Can not execute command $cmd"
6843  Msg Warning "LOG: $log"
6844  } else {
6845  Msg Info "Pre flow script executed!"
6846  Msg Info "Pre flow script log: \n$log"
6847  }
6848 
6849  # Re-open project
6850  if {![is_project_open]} {
6851  Msg Info "Re-opening project file $project_name..."
6852  project_open $project -current_revision
6853  }
6854 
6855  # Generate IP Files
6856  if {[catch {execute_module -tool ipg -args "--clean"} result]} {
6857  Msg Error "Result: $result\n"
6858  Msg Error "IP Generation failed. See the report file.\n"
6859  } else {
6860  Msg Info "IP Generation was successful for revision $revision.\n"
6861  }
6862 
6863  # Execute synthesis
6864  if {[catch {execute_module -tool map -args "--parallel"} result]} {
6865  Msg Error "Result: $result\n"
6866  Msg Error "Analysis & Synthesis failed. See the report file.\n"
6867  } else {
6868  Msg Info "Analysis & Synthesis was successful for revision $revision.\n"
6869  }
6870  } elseif {[IsLibero]} {
6871  # TODO: Missing Reset
6872  defvar_set -name RWNETLIST_32_64_MIXED_FLOW -value 0
6873 
6874  Msg Info "Run SYNTHESIS..."
6875  if {[catch {run_tool -name {SYNTHESIZE}}]} {
6876  Msg Error "SYNTHESIZE FAILED!"
6877  } else {
6878  Msg Info "SYNTHESIZE PASSED!"
6879  }
6880  } elseif {[IsDiamond]} {
6881  # TODO: Missing Reset
6882  set force_rst ""
6883  if {$reset == 1} {
6884  set force_rst "-forceOne"
6885  }
6886  prj_run Synthesis $force_rst
6887  if {[prj_syn] == "synplify"} {
6888  prj_run Translate $force_rst
6889  }
6890  } else {
6891  Msg Error "Impossible condition. You need to run this in an IDE."
6892  exit 1
6893  }
6894 }
6895 
6896 
6897 # @brief Launch the Vitis build
6898 #
6899 # @param[in] project_name The name of the project
6900 # @param[in] repo_path The main path of the git repository (Default ".")
6901 # @param[in] stage The stage of the build (Default "presynth")
6902 proc LaunchVitisBuild {project_name {repo_path .} {stage "presynth"}} {
6903  set proj_name $project_name
6904  set bin_dir [file normalize "$repo_path/bin"]
6905 
6906  cd $repo_path
6907 
6908  # Get app list
6909  if {[IsVitisUnified]} {
6910  set vitis_workspace [file normalize "$repo_path/Projects/$project_name/vitis_unified"]
6911  set python_script [file normalize "$repo_path/Hog/Other/Python/VitisUnified/AppCommands.py"]
6912  set ws_apps [GetVitisApps $vitis_workspace $python_script]
6913  } elseif {[IsVitisClassic]} {
6914  set ws_apps [GetVitisApps]
6915  } else {
6916  Msg Error "Impossible condition. You need to run this in a Vitis Unified or Vitis Classic IDE."
6917  exit 1
6918  }
6919 
6920  # Get repository versions
6921  lassign [GetRepoVersions [file normalize $repo_path/Top/$proj_name] $repo_path] commit version hog_hash hog_ver top_hash top_ver \
6922  libs hashes vers cons_ver cons_hash ext_names ext_hashes xml_hash xml_ver user_ip_repos user_ip_hashes user_ip_vers \
6923  cheby_hash cheby_ver
6924  set this_commit [GetSHA]
6925  if {$commit == 0} {set commit $this_commit}
6926  set flavour [GetProjectFlavour $project_name]
6927  lassign [GetDateAndTime $commit] date timee
6928 
6929  # Configure apps only for Vitis Classic, build-config is not supported in Vitis Unified
6930  # build directory seems to be the default
6931  if {[IsVitisClassic]} {
6932  foreach app_name [dict keys $ws_apps] {
6933  app config -name $app_name -set build-config Release
6934  }
6935  }
6936 
6937  WriteGenerics "vitisbuild" $repo_path $proj_name $date $timee $commit $version $top_hash $top_ver $hog_hash $hog_ver $cons_ver $cons_hash $libs \
6938  $vers $hashes $ext_names $ext_hashes $user_ip_repos $user_ip_vers $user_ip_hashes $flavour $xml_ver $xml_hash \
6939  $cheby_ver $cheby_hash
6940 
6941  # Build apps
6942  foreach app_name [dict keys $ws_apps] {
6943  if {[IsVitisUnified]} {
6944  # Build vitis unified app
6945  if {![ExecuteVitisUnifiedCommand $python_script "build_app" [list $app_name $vitis_workspace] "Failed to build app $app_name"]} {
6946  Msg Error "Failed to build app $app_name"
6947  continue
6948  }
6949  } elseif {[IsVitisClassic]} {
6950  app build -name $app_name
6951  }
6952  }
6953 
6954  if {$stage == "presynth"} {
6955  Msg Info "Done building apps for $project_name..."
6956  }
6957 
6958  if {[info exists ::globalSettings::vitis_only_pass] && $::globalSettings::vitis_only_pass == 1} {
6959  Msg Info "Skipping bin directory creation in vitis_only mode (post-bitstream.tcl handles artifacts)."
6960  return
6961  }
6962 
6963  Msg Info "Evaluating Hog describe for $project_name..."
6964  set describe [GetHogDescribe [file normalize ./Top/$project_name] $repo_path]
6965  Msg Info "Hog describe set to: $describe"
6966  set dst_dir [file normalize "$bin_dir/$proj_name\-$describe"]
6967  if {![file exists $dst_dir]} {
6968  Msg Info "Creating $dst_dir..."
6969  file mkdir $dst_dir
6970  }
6971 
6972  foreach app_name [dict keys $ws_apps] {
6973  if {[IsVitisUnified]} {
6974  set main_file "$repo_path/Projects/$project_name/vitis_unified/$app_name/build/$app_name.elf"
6975  } elseif {[IsVitisClassic]} {
6976  set main_file "$repo_path/Projects/$project_name/vitis_classic/$app_name/Release/$app_name.elf"
6977  }
6978  set dst_main [file normalize "$dst_dir/[file tail $proj_name]\-$app_name\-$describe.elf"]
6979 
6980  if {![file exists $main_file]} {
6981  Msg Error "No Vitis .elf file found. Perhaps there was an issue building it?"
6982  continue
6983  }
6984 
6985  Msg Info "Copying main binary file $main_file into $dst_main..."
6986  file copy -force $main_file $dst_main
6987  }
6988 }
6989 
6990 # @brief Launch the HLS build for all [hls:*] components in the project
6991 #
6992 # For each HLS component defined in hog.conf, this proc runs:
6993 # - C synthesis
6994 # - Implementation
6995 # - Collects reports (.rpt, .xml, .log) into bin/ for CI
6996 # Packaging is controlled by hls_config.cfg (package.output.format, etc.)
6997 # Simulations (CSIM/COSIM) are handled by LaunchHlsSimulation via the S command.
6998 #
6999 # @param[in] project_name The name of the project
7000 # @param[in] repo_path The main path of the git repository (Default ".")
7001 proc LaunchHlsBuild {project_name {repo_path .}} {
7002  set proj_name $project_name
7003  set bin_dir [file normalize "$repo_path/bin"]
7004 
7005  cd $repo_path
7006 
7007  set conf_file [file normalize "$repo_path/Top/$project_name/hog.conf"]
7008  if {![file exists $conf_file]} {
7009  Msg Error "Configuration file not found: $conf_file"
7010  return
7011  }
7012  set properties [ReadConf $conf_file]
7013  set hls_components [dict filter $properties key {hls:*}]
7014 
7015  if {[dict size $hls_components] == 0} {
7016  Msg Info "No HLS components found for project $project_name"
7017  return
7018  }
7019 
7020  set python_script [file normalize "$repo_path/Hog/Other/Python/VitisUnified/HlsCommands.py"]
7021 
7022  # Determine whether this is a mixed Vivado+Vitis project. In that case HLS
7023  # component outputs are grouped under bin/<proj>/vitis_hls/ to keep them
7024  # visually separate from Vivado's top-level utilization.txt / timing_*.txt.
7025  # For pure vitis_unified projects (no Vivado) HLS outputs sit directly under
7026  # bin/<proj>/<component>/ since there's nothing else to collide with.
7027  set ide_info [GetIDEFromConf $conf_file]
7028  set ide_name [string tolower [lindex $ide_info 0]]
7029  if {$ide_name eq "vivado_vitis_unified"} {
7030  set is_mixed_project 1
7031  } else {
7032  set is_mixed_project 0
7033  }
7034 
7035  dict for {hls_key hls_props} $hls_components {
7036  if {![regexp {^hls:(.+)$} $hls_key -> component_name]} {
7037  continue
7038  }
7039  set component_name [string trim $component_name]
7040  Msg Info "Building HLS component: $component_name"
7041 
7042  # Read HLS_CONFIG path from hog.conf (mandatory)
7043  set hls_cfg_rel ""
7044  if {[dict exists $hls_props hls_config]} {
7045  set hls_cfg_rel [dict get $hls_props hls_config]
7046  } elseif {[dict exists $hls_props HLS_CONFIG]} {
7047  set hls_cfg_rel [dict get $hls_props HLS_CONFIG]
7048  }
7049  if {$hls_cfg_rel eq ""} {
7050  Msg Error "HLS component '$component_name' missing HLS_CONFIG in hog.conf"
7051  continue
7052  }
7053 
7054  set cfg_file [file normalize "$repo_path/$hls_cfg_rel"]
7055  if {![file exists $cfg_file]} {
7056  Msg Error "HLS config file not found: $cfg_file (from HLS_CONFIG=$hls_cfg_rel)"
7057  continue
7058  }
7059 
7060  set hls_work_dir [file normalize "$repo_path/Projects/$project_name/vitis_unified/$component_name"]
7061  file mkdir $hls_work_dir
7062 
7063  # C synthesis
7064  Msg Info "Running C synthesis for HLS component '$component_name'..."
7065  if {
7066  ![ExecuteVitisUnifiedCommand $python_script "synthesis" \
7067  [list $component_name $cfg_file $hls_work_dir] \
7068  "Failed to run C synthesis for $component_name"]
7069  } {
7070  Msg Error "C synthesis failed for HLS component '$component_name'"
7071  continue
7072  }
7073 
7074  # Implementation
7075  Msg Info "Running implementation for HLS component '$component_name'..."
7076  if {
7077  ![ExecuteVitisUnifiedCommand $python_script "impl" \
7078  [list $component_name $cfg_file $hls_work_dir] \
7079  "Failed to run implementation for $component_name"]
7080  } {
7081  Msg Error "Implementation failed for HLS component '$component_name'"
7082  continue
7083  }
7084 
7085  # Export VHDL to source tree if VHDL_OUTPUT is set
7086  set vhdl_output ""
7087  if {[dict exists $hls_props vhdl_output]} {
7088  set vhdl_output [dict get $hls_props vhdl_output]
7089  } elseif {[dict exists $hls_props VHDL_OUTPUT]} {
7090  set vhdl_output [dict get $hls_props VHDL_OUTPUT]
7091  }
7092  if {$vhdl_output ne ""} {
7093  set vhdl_output_dir [file normalize "$repo_path/$vhdl_output"]
7094  Msg Info "Exporting VHDL for '$component_name' to $vhdl_output_dir..."
7095  if {
7096  ![ExecuteVitisUnifiedCommand $python_script "export_rtl" \
7097  [list $component_name $hls_work_dir $vhdl_output_dir vhdl] \
7098  "Failed to export VHDL for $component_name"]
7099  } {
7100  Msg Warning "Could not export VHDL for HLS component '$component_name'"
7101  }
7102  }
7103 
7104  # Export Verilog to source tree if VERILOG_OUTPUT is set
7105  set verilog_output ""
7106  if {[dict exists $hls_props verilog_output]} {
7107  set verilog_output [dict get $hls_props verilog_output]
7108  } elseif {[dict exists $hls_props VERILOG_OUTPUT]} {
7109  set verilog_output [dict get $hls_props VERILOG_OUTPUT]
7110  }
7111  if {$verilog_output ne ""} {
7112  set verilog_output_dir [file normalize "$repo_path/$verilog_output"]
7113  Msg Info "Exporting Verilog for '$component_name' to $verilog_output_dir..."
7114  if {
7115  ![ExecuteVitisUnifiedCommand $python_script "export_rtl" \
7116  [list $component_name $hls_work_dir $verilog_output_dir verilog] \
7117  "Failed to export Verilog for $component_name"]
7118  } {
7119  Msg Warning "Could not export Verilog for HLS component '$component_name'"
7120  }
7121  }
7122 
7123  # Export IP catalog ZIP to source tree if IP_OUTPUT is set
7124  set ip_output ""
7125  if {[dict exists $hls_props ip_output]} {
7126  set ip_output [dict get $hls_props ip_output]
7127  } elseif {[dict exists $hls_props IP_OUTPUT]} {
7128  set ip_output [dict get $hls_props IP_OUTPUT]
7129  }
7130  if {$ip_output ne ""} {
7131  set ip_output_dir [file normalize "$repo_path/$ip_output"]
7132  Msg Info "Exporting IP catalog for '$component_name' to $ip_output_dir..."
7133  if {
7134  ![ExecuteVitisUnifiedCommand $python_script "export_ip" \
7135  [list $component_name $hls_work_dir $ip_output_dir] \
7136  "Failed to export IP for $component_name"]
7137  } {
7138  Msg Error "Could not export IP for HLS component '$component_name'. Make sure package.output.format=ip_catalog is set in hls_config.cfg."
7139  }
7140  }
7141 
7142  # Collect reports into bin/ for CI and release notes
7143  Msg Info "Evaluating Hog describe for $project_name..."
7144  set describe [GetHogDescribe [file normalize ./Top/$project_name] $repo_path]
7145  Msg Info "Hog describe set to: $describe"
7146  set dst_dir [file normalize "$bin_dir/$proj_name\-$describe"]
7147  if {![file exists $dst_dir]} {
7148  Msg Info "Creating $dst_dir..."
7149  file mkdir $dst_dir
7150  }
7151 
7152  # Mixed projects group HLS components under bin/<proj>/vitis_hls/; pure
7153  # vitis_unified projects place them directly under bin/<proj>/
7154  if {$is_mixed_project} {
7155  set hls_out_dir [file normalize "$dst_dir/vitis_hls"]
7156  } else {
7157  set hls_out_dir $dst_dir
7158  }
7159 
7160  Msg Info "Collecting HLS reports for component '$component_name'..."
7161  if {
7162  ![ExecuteVitisUnifiedCommand $python_script "collect_reports" \
7163  [list $component_name $hls_work_dir $hls_out_dir] \
7164  "Failed to collect HLS reports for $component_name"]
7165  } {
7166  Msg Warning "No reports found for HLS component '$component_name'"
7167  }
7168 
7169  # Generate markdown summary files (utilization.txt, timing_ok.txt /
7170  # timing_error.txt) under <hls_out_dir>/<component>/. File names mirror the
7171  # Vivado convention so the existing CI logic (release notes assembly and
7172  # timing-failure detection) works for HLS components too
7173  Msg Info "Generating HLS release-notes summary for component '$component_name'..."
7174  if {
7175  ![ExecuteVitisUnifiedCommand $python_script "release_notes" \
7176  [list $component_name $hls_work_dir $hls_out_dir] \
7177  "Failed to generate HLS summary for $component_name"]
7178  } {
7179  Msg Warning "Could not generate HLS summary for component '$component_name'"
7180  }
7181 
7182  Msg Info "HLS component '$component_name' built successfully"
7183  }
7184 
7185  # For pure vitis_unified (HLS-only) projects, emit a top-level versions.txt
7186  # at the bin project root
7187  if {!$is_mixed_project && [info exists dst_dir] && [file isdirectory $dst_dir]} {
7188  set versions_file [file normalize "$dst_dir/versions.txt"]
7189  Msg Info "Generating top-level versions.txt for pure-HLS project at $versions_file"
7190  if {
7191  [catch {
7192  lassign [GetRepoVersions [file normalize $repo_path/Top/$project_name] $repo_path] \
7193  commit version hog_hash hog_ver top_hash top_ver \
7194  libs hashes vers cons_ver cons_hash \
7195  ext_names ext_hashes xml_hash xml_ver \
7196  user_ip_repos user_ip_hashes user_ip_vers \
7197  cheby_hash cheby_ver
7198  if {$commit == 0} {set commit [GetSHA]}
7199  set version_str [HexVersionToString $version]
7200  set hog_ver_str [HexVersionToString $hog_ver]
7201  set top_ver_str [HexVersionToString $top_ver]
7202  set fh [open $versions_file "w"]
7203  puts $fh "## $proj_name Version Table\n"
7204  puts $fh "| **File set** | **Commit SHA** | **Version** |"
7205  puts $fh "| --- | --- | --- |"
7206  puts $fh "| Global | $commit | $version_str |"
7207  puts $fh "| Top Directory | $top_hash | $top_ver_str |"
7208  puts $fh "| Hog | $hog_hash | $hog_ver_str |"
7209  foreach l $libs v $vers h $hashes {
7210  set v_str [HexVersionToString $v]
7211  puts $fh "| **Lib:** $l | $h | $v_str |"
7212  }
7213  puts $fh "\n"
7214  close $fh
7215  } err]
7216  } {
7217  Msg Warning "Could not generate top-level versions.txt for pure-HLS project: $err"
7218  }
7219  }
7220 
7221  Msg Info "Done building HLS components for $project_name"
7222 }
7223 
7224 
7225 # @brief Launch HLS simulations for [hls:*] components in the project
7226 #
7227 # When called without hls_simsets (or with an empty list), runs all enabled
7228 # HLS simulations (CSIM if CSIM=true, COSIM if COSIM=true in hog.conf).
7229 # When called with specific targets (e.g. "csim:iir_lp_filter cosim:iir_lp_filter"),
7230 # runs only the requested simulations.
7231 # COSIM automatically triggers C synthesis first if not already done.
7232 # Triggered by the S (SIMULATE) command.
7233 #
7234 # @param[in] project_name The name of the project
7235 # @param[in] repo_path The main path of the git repository (Default ".")
7236 # @param[in] hls_simsets Optional list of specific HLS simsets to run (e.g. "csim:name" "cosim:name")
7237 proc LaunchHlsSimulation {project_name {repo_path .} {hls_simsets {}}} {
7238  cd $repo_path
7239 
7240  set conf_file [file normalize "$repo_path/Top/$project_name/hog.conf"]
7241  if {![file exists $conf_file]} {
7242  Msg Error "Configuration file not found: $conf_file"
7243  return
7244  }
7245  set properties [ReadConf $conf_file]
7246  set hls_components [dict filter $properties key {hls:*}]
7247 
7248  if {[dict size $hls_components] == 0} {
7249  Msg Info "No HLS components found for project $project_name"
7250  return
7251  }
7252 
7253  # Build a lookup of requested targets: component_name -> list of sim types
7254  # If hls_simsets is empty, we'll use hog.conf flags for all components
7255  set targeted_mode [expr {[llength $hls_simsets] > 0}]
7256  set targets [dict create]
7257  foreach entry $hls_simsets {
7258  if {[regexp {^(csim|cosim):(.+)$} $entry -> sim_type comp_name]} {
7259  dict lappend targets $comp_name $sim_type
7260  } else {
7261  Msg Error "Invalid HLS simset format '$entry'. Expected 'csim:<component>' or 'cosim:<component>'."
7262  Msg Info "Available HLS components in hog.conf:"
7263  dict for {hls_key hls_props} $hls_components {
7264  if {[regexp {^hls:(.+)$} $hls_key -> cname]} {
7265  Msg Info " - csim:[string trim $cname]"
7266  Msg Info " - cosim:[string trim $cname]"
7267  }
7268  }
7269  return
7270  }
7271  }
7272 
7273  set python_script [file normalize "$repo_path/Hog/Other/Python/VitisUnified/HlsCommands.py"]
7274 
7275  dict for {hls_key hls_props} $hls_components {
7276  if {![regexp {^hls:(.+)$} $hls_key -> component_name]} {
7277  continue
7278  }
7279  set component_name [string trim $component_name]
7280 
7281  # In targeted mode, skip components not in the request
7282  if {$targeted_mode && ![dict exists $targets $component_name]} {
7283  continue
7284  }
7285 
7286  # Read HLS_CONFIG path from hog.conf (mandatory)
7287  set hls_cfg_rel ""
7288  if {[dict exists $hls_props hls_config]} {
7289  set hls_cfg_rel [dict get $hls_props hls_config]
7290  } elseif {[dict exists $hls_props HLS_CONFIG]} {
7291  set hls_cfg_rel [dict get $hls_props HLS_CONFIG]
7292  }
7293  if {$hls_cfg_rel eq ""} {
7294  Msg Error "HLS component '$component_name' missing HLS_CONFIG in hog.conf"
7295  continue
7296  }
7297 
7298  set cfg_file [file normalize "$repo_path/$hls_cfg_rel"]
7299  if {![file exists $cfg_file]} {
7300  Msg Error "HLS config file not found: $cfg_file (from HLS_CONFIG=$hls_cfg_rel)"
7301  continue
7302  }
7303 
7304  set hls_work_dir [file normalize "$repo_path/Projects/$project_name/vitis_unified/$component_name"]
7305  file mkdir $hls_work_dir
7306 
7307  # Determine which simulations to run
7308  if {$targeted_mode} {
7309  # User explicitly requested these sim types via -simset
7310  set sim_types [dict get $targets $component_name]
7311  set run_csim [expr {"csim" in $sim_types}]
7312  set run_cosim [expr {"cosim" in $sim_types}]
7313 
7314  # Validate: check if the requested sim is enabled in hog.conf
7315  foreach st $sim_types {
7316  set flag_val ""
7317  if {[dict exists $hls_props $st]} {
7318  set flag_val [dict get $hls_props $st]
7319  } elseif {[dict exists $hls_props [string toupper $st]]} {
7320  set flag_val [dict get $hls_props [string toupper $st]]
7321  }
7322  set is_enabled [expr {[string tolower $flag_val] eq "true" || $flag_val eq "1"}]
7323  if {!$is_enabled} {
7324  set upper_st [string toupper $st]
7325  Msg Warning "HLS simulation '$st' requested for '$component_name' but\
7326  $upper_st is not enabled in \[hls:$component_name\] section of\
7327  hog.conf. Running it anyway."
7328  Msg Info "To enable it permanently, add '$upper_st=true' under\
7329  \[hls:$component_name\] in Top/$project_name/hog.conf"
7330  }
7331  }
7332  } else {
7333  # Default mode: read flags from hog.conf
7334  set run_csim 0
7335  set run_cosim 0
7336  foreach {key_lower key_upper} {csim CSIM cosim COSIM} {
7337  set val ""
7338  if {[dict exists $hls_props $key_lower]} {
7339  set val [dict get $hls_props $key_lower]
7340  } elseif {[dict exists $hls_props $key_upper]} {
7341  set val [dict get $hls_props $key_upper]
7342  }
7343  if {[string tolower $val] eq "true" || $val eq "1"} {
7344  set run_$key_lower 1
7345  }
7346  }
7347 
7348  if {!$run_csim && !$run_cosim} {
7349  Msg Info "No HLS simulations enabled for '$component_name' (set CSIM=true and/or COSIM=true in \[hls:$component_name\] in hog.conf)"
7350  continue
7351  }
7352  }
7353 
7354  Msg Info "Running HLS simulations for component: $component_name"
7355 
7356  # CSIM
7357  if {$run_csim} {
7358  Msg Info "Running C simulation for HLS component '$component_name'..."
7359  if {
7360  ![ExecuteVitisUnifiedCommand $python_script "csim" \
7361  [list $component_name $cfg_file $hls_work_dir] \
7362  "Failed to run C simulation for $component_name"]
7363  } {
7364  Msg Error "C simulation failed for HLS component '$component_name'"
7365  continue
7366  }
7367  }
7368 
7369  # COSIM (auto-run synthesis if needed)
7370  if {$run_cosim} {
7371  set syn_done_marker [file normalize "$hls_work_dir/hls/syn"]
7372  if {![file exists $syn_done_marker]} {
7373  Msg Info "C synthesis output not found for '$component_name', running synthesis automatically before co-simulation..."
7374  if {
7375  ![ExecuteVitisUnifiedCommand $python_script "synthesis" \
7376  [list $component_name $cfg_file $hls_work_dir] \
7377  "Failed to run C synthesis for $component_name"]
7378  } {
7379  Msg Error "C synthesis failed for HLS component '$component_name', cannot proceed with co-simulation"
7380  continue
7381  }
7382  }
7383 
7384  Msg Info "Running C/RTL co-simulation for HLS component '$component_name'..."
7385  if {
7386  ![ExecuteVitisUnifiedCommand $python_script "cosim" \
7387  [list $component_name $cfg_file $hls_work_dir] \
7388  "Failed to run co-simulation for $component_name"]
7389  } {
7390  Msg Error "C/RTL co-simulation failed for HLS component '$component_name'"
7391  continue
7392  }
7393  }
7394 
7395  Msg Info "HLS simulations completed for '$component_name'"
7396  }
7397 
7398  Msg Info "Done with HLS simulations for $project_name"
7399 }
7400 
7401 # @brief Returns the BIF file path from the properties
7402 #
7403 # @param[in] props A dictionary with the properties defined in Hog.conf
7404 # @param[in] app The application name
7405 # @return The path of the BIF file or empty string if not found
7406 proc GetProcFromProps {repo_path props platform} {
7407  if {[dict exists $props "platform:$platform" "BIF"]} {
7408  set bif_file [dict get $props "platform:$platform" "BIF"]
7409  if {[IsRelativePath $bif_file] == 1} {
7410  set bif_file "$repo_path/$bif_file"
7411  }
7412  return $bif_file
7413  } else {
7414  Msg CriticalWarning "BIF file not found in platform ($platform) properties, skipping bootable image (.bin) generation"
7415  return ""
7416  }
7417 }
7418 
7419 # @brief Returns the BIF file path from the properties
7420 #
7421 # @param[in] props A dictionary with the properties defined in Hog.conf
7422 # @param[in] platform The platform name
7423 # @return The path of the BIF file or empty string if not found
7424 proc GetBifFromProps {repo_path props platform} {
7425  if {[dict exists $props "platform:$platform" "BIF"]} {
7426  set bif_file [dict get $props "platform:$platform" "BIF"]
7427  if {[IsRelativePath $bif_file] == 1} {
7428  set bif_file "$repo_path/$bif_file"
7429  }
7430  return $bif_file
7431  } else {
7432  Msg CriticalWarning "BIF file not found in platform ($platform) properties, skipping bootable image (.bin) generation"
7433  return ""
7434  }
7435 }
7436 
7437 # @brief Returns the part number from the properties
7438 #
7439 # @param[in] props A dictionary with the properties defined in Hog.conf
7440 # @return The part number
7441 proc GetPartFromProps {props} {
7442  if {[dict exists $props "main" "PART"]} {
7443  return [string tolower [dict get $props "main" "PART"]]
7444  } else {
7445  Msg Error "Part number not found in properties"
7446  return ""
7447  }
7448 }
7449 
7450 # @brief Determines the architecture from the part number
7451 #
7452 # @param[in] part The FPGA part number (e.g., xczu4cg-fbvb900-1-e)
7453 # @return String with the architecture (zynqmp, zynq, versal, fpga, or unknown)
7454 proc GetArchFromPart {part} {
7455  set part [string tolower $part]
7456  # bootgen -arch values: zynq, zynqmp, versal, fpga
7457  if {[string match "xczu*" $part] || [string match "xqzu*" $part]} {
7458  return "zynqmp"
7459  } elseif {[string match "xc7z*" $part] || [string match "xq7z*" $part]} {
7460  return "zynq"
7461  } elseif {
7462  [string match "xcve*" $part] || [string match "xcvc*" $part] ||
7463  [string match "xcvp*" $part] || [string match "xcvm*" $part] ||
7464  [string match "xqve*" $part] || [string match "xck26*" $part]
7465  } {
7466  return "versal"
7467  } elseif {[string match "xc*" $part] || [string match "xq*" $part]} {
7468  # Non-SoC FPGA (e.g. Kintex-7 / Artix-7 / UltraScale) for MicroBlaze/RISC-V
7469  return "fpga"
7470  } else {
7471  Msg CriticalWarning "Unknown part number: $part"
7472  return "unknown"
7473  }
7474 }
7475 
7476 # @brief Returns a list of application names from the properties
7477 #
7478 # @param[in] props A dictionary with the applications properties defined in Hog.conf
7479 # @param[in] list_names If 1, returns a list of application names rather than a dictionary of applications
7480 proc GetAppsFromProps {props {list_names 0}} {
7481  set prop_apps [dict filter $props key {app:*}]
7482  set apps [dict create]
7483  set app_names [list]
7484 
7485  dict for {app_key app_value} $prop_apps {
7486  if {[regexp {^app:(.+)$} $app_key -> app_name]} {
7487  set app_name [string trim [string tolower $app_name]]
7488  # Convert only the keys of the inner dictionary to lowercase
7489  set app_value_lower [dict create]
7490  dict for {key value} $app_value {
7491  dict set app_value_lower [string tolower $key] $value
7492  }
7493  dict set apps $app_name $app_value_lower
7494  lappend app_names $app_name
7495  }
7496  }
7497  if {$list_names eq 1} {
7498  return $app_names
7499  }
7500  return $apps
7501 }
7502 
7503 # @brief Returns a list of platform names from the properties
7504 #
7505 # @param[in] props A dictionary with the platforms properties
7506 # @param[in] list_names If 1, returns a list of platform names rather than a dictionary of platforms
7507 # @param[in] lower_case If 1, returns the platform names in lowercase
7508 proc GetPlatformsFromProps {props {list_names 0} {lower_case 0}} {
7509  set platforms [dict create]
7510  set platform_names [list]
7511  set prop_platforms [dict filter $props key {platform:*}]
7512 
7513  dict for {platform_key platform_value} $prop_platforms {
7514  if {[regexp {^platform:(.+)$} $platform_key -> platform_name]} {
7515  if {$lower_case == 1} {
7516  set platform_name [string trim [string tolower $platform_name]]
7517  } else {
7518  set platform_name [string trim $platform_name]
7519  }
7520  dict set platforms $platform_name $platform_value
7521  lappend platform_names $platform_name
7522  }
7523  }
7524  if {$list_names eq 1} {
7525  return $platform_names
7526  }
7527  return $platforms
7528 }
7529 
7530 # @brief Generates boot artifacts for the application. If the application targets a soft \
7531 # processor (e.g. microblaze, riscv), the bitstream (.bit) memory is updated to include the ELF file. Otherwise, for \
7532 # applications targeting a hard processor (e.g. zynq, versal), a bootable binary image (.bin) is generated.
7533 #
7534 # @param[in] properties A dictionary with the properties defined in Hog.conf
7535 # @param[in] repo_path The main path of the git repository
7536 # @param[in] proj_dir The directory of the project
7537 # @param[in] bin_dir The directory of the generated binary files
7538 # @param[in] bitfile The bitfile to update
7539 # @param[in] mmi_file The MMI file to update
7540 proc GenerateBootArtifacts {properties repo_path proj_dir bin_dir proj_name describe bitfile mmi_file} {
7541  set elf_list [glob -nocomplain "$bin_dir/*.elf"]
7542  set apps [GetAppsFromProps $properties 0]
7543  set platforms [GetPlatformsFromProps $properties 1]
7544 
7545  if {[llength $elf_list] == 0} {
7546  Msg Warning "No ELF files found in $bin_dir, skipping generation of boot artifacts"
7547  return
7548  }
7549 
7550  if {![file exists $bitfile]} {
7551  Msg Warning "Bitfile $bitfile does not exist, skipping generation of boot artifacts"
7552  return
7553  }
7554 
7555  Msg Info "Generating boot artifacts for $proj_name..."
7556  Msg Info "Found apps: $apps"
7557  Msg Info "Found platforms: $platforms"
7558 
7559 
7560  # Update bitstream with ELF files for the applications targeting a soft processor (e.g. microblaze, riscv)
7561  foreach elf_file $elf_list {
7562  set elf_name [file rootname [file tail $elf_file]]
7563  Msg Info "Found elf name: $elf_name"
7564  Msg Info "Removing $describe from elf"
7565 
7566  # Extract application name from ELF file name
7567  if {[regexp "^(.+)-(.+)-$describe\$" $elf_name -> project_name elf_app]} {
7568  set elf_app [string trim [string tolower $elf_app]]
7569  Msg Info "Found elf_app: $elf_app"
7570  } else {
7571  Msg Error "Could not extract app name from elf file: $elf_name"
7572  continue
7573  }
7574  Msg Info "Removed project name ($project_name) and $describe from elf"
7575 
7576  set app_conf [dict get $apps $elf_app]
7577  set plat [dict get $app_conf "platform"]
7578  set app_proc [dict get $app_conf "proc"]
7579 
7580  # If the application targets a soft processor, update bitstream memory with ELF file
7581  if {[regexp -nocase {microblaze|risc} $app_proc]} {
7582  Msg Info "Detected soft processor ($app_proc) for $elf_app, updating bitstream memory with ELF file..."
7583 
7584  # updatemem needs the processor instance path as written in the MMI file, which includes
7585  # the block design wrapper hierarchy. The platform processor map is only used as a
7586  # fallback, since it contains names relative to the block design
7587  set proc_cell [GetProcInstPathFromMmi $mmi_file $app_proc]
7588  if {$proc_cell eq ""} {
7589  set proc_map_file [file normalize "$proj_dir/vitis_classic/${plat}.PROC_MAP"]
7590  set proc_map [ReadProcMap $proc_map_file]
7591  if {[dict exists $proc_map $app_proc]} {
7592  set proc_cell [dict get $proc_map $app_proc]
7593  Msg Info "Processor $app_proc not found in $mmi_file, using $proc_map_file instead."
7594  } else {
7595  Msg Error "Could not determine the instance path of processor '$app_proc' for $elf_app, \
7596  neither from $mmi_file nor from $proc_map_file. \
7597  Check that proc= in the \[app:$elf_app\] section of hog.conf matches the processor instance name."
7598  continue
7599  }
7600  }
7601  Msg Info "Updating memory at processor cell: $proc_cell"
7602 
7603  set update_mem_cmd "updatemem -force -meminfo $mmi_file -data $elf_file -bit $bitfile -proc $proc_cell -out $bitfile"
7604  set ret [catch {exec -ignorestderr {*}$update_mem_cmd >@ stdout} result]
7605  if {$ret != 0} {
7606  Msg Error "Error updating memory for $elf_app: $result"
7607  }
7608  Msg Info "Done updating memory for $elf_app"
7609  } else {
7610  Msg Info "Detected hard processor ($app_proc) for $elf_app. Make sure the .elf file is defined in the platform ($plat)\
7611  .bif file to be included in the bootable binary image (.bin) generation."
7612  }
7613  }
7614 
7615 
7616  # Generate a bootable binary image for platforms that have a .bif file defined
7617  foreach plat $platforms {
7618  set bif_file [GetBifFromProps $repo_path $properties $plat]
7619  if {$bif_file != ""} {
7620  Msg Info "Generating bootable binary image (.bin) for $plat"
7621  set arch [GetArchFromPart [GetPartFromProps $properties]]
7622  Msg Info "Architecture: $arch"
7623  Msg Info "BIF file: $bif_file"
7624  if {$arch eq "unknown"} {
7625  Msg CriticalWarning "Skipping bootable image (.bin) generation for $plat: \
7626  could not determine bootgen architecture from the FPGA part."
7627  continue
7628  }
7629  set bootgen_cmd "bootgen -arch $arch -image $bif_file -o i $bin_dir/$proj_name-$plat-$describe.bin -w on"
7630  set ret [catch {exec -ignorestderr {*}$bootgen_cmd >@ stdout} result]
7631  if {$ret != 0} {
7632  Msg Error "Error generating bootable binary image (.bin) for $plat: $result"
7633  }
7634  Msg Info "Done generating bootable binary image (.bin) for $plat"
7635  }
7636  }
7637 }
7638 
7639 ## @brief Generate output products for standalone XCI IPs
7640 #
7641 # IPs nested inside a block design, or inside another IP, must be generated by their
7642 # parent sub-design: generating them directly makes Vivado fail with
7643 # "[Vivado 12-3563] The Nested sub-design ... can only be generated by its parent sub-design".
7644 # Vivado flags every such file by setting its PARENT_COMPOSITE_FILE property, so that is what
7645 # we use to tell nested IPs from standalone ones.
7646 proc GenerateStandaloneXciTargets {} {
7647  if {![IsVivado]} {
7648  return
7649  }
7650 
7651  foreach xci [get_files -quiet *.xci] {
7652  set xci_file [get_files -quiet $xci]
7653  if {$xci_file eq ""} {
7654  continue
7655  }
7656 
7657  set parent ""
7658  catch {set parent [get_property -quiet PARENT_COMPOSITE_FILE $xci_file]}
7659  if {$parent ne ""} {
7660  Msg Debug "Skipping [file tail $xci], it is generated by its parent [file tail $parent]"
7661  continue
7662  }
7663 
7664  Msg Info "Generating targets for standalone IP [file tail $xci]..."
7665  if {[catch {generate_target all $xci_file} err]} {
7666  Msg CriticalWarning "Failed to generate targets for $xci: $err"
7667  }
7668  }
7669 }
7670 
7671 # @brief Returns the processor instance path to be used with updatemem -proc
7672 #
7673 # The updatemem -proc option must match the InstPath attribute of one of the Processor entries
7674 # of the MMI file, which Vivado writes together with the bitstream and which contains the full
7675 # hierarchical path of the processor.
7676 #
7677 # @param[in] mmi_file The path to the MMI file
7678 # @param[in] app_proc The processor name, as defined with proc= in hog.conf
7679 # @return The matching instance path, or an empty string if it could not be determined
7680 proc GetProcInstPathFromMmi {mmi_file app_proc} {
7681  if {![file exists $mmi_file]} {
7682  Msg Debug "MMI file not found: $mmi_file"
7683  return ""
7684  }
7685 
7686  set f [open $mmi_file "r"]
7687  set mmi_content [read $f]
7688  close $f
7689 
7690  set inst_paths [list]
7691  foreach {match inst_path} [regexp -all -inline {<Processor[^>]*InstPath\s*=\s*"([^"]+)"} $mmi_content] {
7692  if {[lsearch -exact $inst_paths $inst_path] < 0} {
7693  lappend inst_paths $inst_path
7694  }
7695  }
7696  Msg Debug "Processor instance paths found in $mmi_file: $inst_paths"
7697 
7698  foreach inst_path $inst_paths {
7699  if {[string equal -nocase [file tail $inst_path] $app_proc]} {
7700  return $inst_path
7701  }
7702  }
7703 
7704  # A design with a single processor is unambiguous, even if the names do not match
7705  if {[llength $inst_paths] == 1} {
7706  set inst_path [lindex $inst_paths 0]
7707  Msg Info "Processor $app_proc does not match [file tail $inst_path], \
7708  using the only processor found in the MMI file: $inst_path"
7709  return $inst_path
7710  }
7711 
7712  return ""
7713 }
7714 
7715 # @brief Reads the processor map file
7716 #
7717 # @param[in] proc_map_file The path to the processor map file
7718 # @return A dictionary with the processor map
7719 proc ReadProcMap {proc_map_file} {
7720  set proc_map [dict create]
7721  if {[file exists $proc_map_file]} {
7722  set f [open $proc_map_file "r"]
7723  while {[gets $f line] >= 0} {
7724  Msg Debug "Line: $line"
7725  if {[regexp {^(\S+)\s+(.+)$} $line -> key value]} {
7726  Msg Debug "Found key: $key, value: $value in proc map file"
7727  dict set proc_map $key $value
7728  }
7729  }
7730  close $f
7731  }
7732  return $proc_map
7733 }
7734 
7735 
7736 # Returns the list of all the Hog Projects in the repository
7737 #
7738 # @param[in] repo_path The main path of the git repository
7739 # @param[in] print if 1 print the list of projects in the repository, if 2 does not print test projects
7740 # @param[in] ret_conf if 1 returns conf file rather than list of project names
7741 proc ListProjects {{repo_path .} {print 1} {ret_conf 0} {silent 0}} {
7742  set top_path [file normalize $repo_path/Top]
7743  set confs [findFiles [file normalize $top_path] hog.conf]
7744  set projects ""
7745  set confs [lsort $confs]
7746  set g ""
7747 
7748  foreach c $confs {
7749  set p [Relative $top_path [file dirname $c]]
7750  if {$print >= 1} {
7751  set description [DescriptionFromConf $c]
7752  if {$description eq "test"} {
7753  set description " - Test project"
7754  } elseif {$description ne ""} {
7755  set description " - $description"
7756  }
7757 
7758  if {$print == 1 || $description ne " - Test project"} {
7759  set old_g $g
7760  set g [file dirname $p]
7761  # Print a list of the projects with relative IDE and description (second line comment in hog.conf)
7762  if {$g ne $old_g} {
7763  if {$silent == 0} {Msg Status ""}
7764  }
7765  if {$silent == 0} {Msg Status "$p \([GetIDEFromConf $c]\)$description"}
7766  }
7767  }
7768  lappend projects $p
7769  }
7770 
7771  if {$ret_conf == 0} {
7772  # Returns a list of project names
7773  return $projects
7774  } else {
7775  # Return the list of hog.conf with full path
7776  return $confs
7777  }
7778 }
7779 
7780 ## @brief Evaluates the md5 sum of a file
7781 #
7782 # @param[in] file_name: the name of the file of which you want to evaluate the md5 checksum
7783 proc Md5Sum {file_name} {
7784  if {!([file exists $file_name])} {
7785  Msg Warning "Could not find $file_name."
7786  set file_hash -1
7787  }
7788  if {[catch {package require md5 2.0.7} result]} {
7789  Msg Warning "Tcl package md5 version 2.0.7 not found ($result), will use command line..."
7790  set hash [lindex [Execute md5sum $file_name] 0]
7791  } else {
7792  set file_hash [string tolower [md5::md5 -hex -file $file_name]]
7793  }
7794 }
7795 
7796 ## @brief Merges two tcl dictionaries of lists
7797 #
7798 # If the dictionaries contain same keys, the list at the common key is a merging of the two
7799 #
7800 # @param[in] dict0 the name of the first dictionary
7801 # @param[in] dict1 the name of the second dictionary
7802 # @param[in] remove_duplicates if 1, removes duplicates from the merged dictionary (default 1)
7803 #
7804 # @return the merged dictionary
7805 #
7806 proc MergeDict {dict0 dict1 {remove_duplicates 1}} {
7807  set outdict [dict merge $dict1 $dict0]
7808  foreach key [dict keys $dict1] {
7809  if {[dict exists $dict0 $key]} {
7810  set temp_list [dict get $dict1 $key]
7811  foreach item $temp_list {
7812  # Avoid duplication
7813  if {[IsInList $item [DictGet $outdict $key]] == 0 || $remove_duplicates == 0} {
7814  # If the key exists in both dictionaries, append the item to the list
7815  dict lappend outdict $key $item
7816  }
7817  }
7818  }
7819  }
7820  return $outdict
7821 }
7822 
7823 # @brief Move an element in the list to the end
7824 #
7825 # @param[in] inputList the list
7826 # @param[in] element the element to move to the end of the list
7827 proc MoveElementToEnd {inputList element} {
7828  set index [lsearch $inputList $element]
7829  if {$index != -1} {
7830  set inputList [lreplace $inputList $index $index]
7831  lappend inputList $element
7832  }
7833  return $inputList
7834 }
7835 
7836 # @brief Open the project with the corresponding IDE
7837 #
7838 # @param[in] project_file The project_file
7839 # @param[in] repo_path The main path of the git repository
7840 proc OpenProject {project_file repo_path} {
7841  if {[IsXilinx]} {
7842  open_project $project_file
7843  } elseif {[IsQuartus]} {
7844  set project_folder [file dirname $project_file]
7845  set project [file tail [file rootname $project_file]]
7846  if {[file exists $project_folder]} {
7847  cd $project_folder
7848  if {![is_project_open]} {
7849  Msg Info "Opening existing project file $project_file..."
7850  project_open $project -current_revision
7851  }
7852  } else {
7853  Msg Error "Project directory not found for $project_file."
7854  return 1
7855  }
7856  } elseif {[IsLibero]} {
7857  Msg Info "Opening existing project file $project_file..."
7858  cd $repo_path
7859  open_project -file $project_file -do_backup_on_convert 1 -backup_file {./Projects/$project_file.zip}
7860  } elseif {[IsDiamond]} {
7861  Msg Info "Opening existing project file $project_file..."
7862  prj_project open $project_file
7863  } else {
7864  Msg Error "This IDE is currently not supported by Hog. Exiting!"
7865  }
7866 }
7867 
7868 ## @brief Return the operative system name
7869 proc OS {} {
7870  global tcl_platform
7871  return $tcl_platform(platform)
7872 }
7873 
7874 ## @brief Parse JSON file
7875 #
7876 # @param[in] JSON_FILE The JSON File to parse
7877 # @param[in] JSON_KEY The key to extract from the JSON file
7878 #
7879 # @returns -1 in case of failure, JSON KEY VALUE in case of success
7880 #
7881 proc ParseJSON {JSON_FILE JSON_KEY} {
7882  set result [catch {package require Tcl 8.4} TclFound]
7883  if {"$result" != "0"} {
7884  Msg CriticalWarning "Cannot find Tcl package version equal or higher than 8.4.\n $TclFound\n Exiting"
7885  return -1
7886  }
7887 
7888  set result [catch {package require json} JsonFound]
7889  if {"$result" != "0"} {
7890  Msg CriticalWarning "Cannot find JSON package equal or higher than 1.0.\n $JsonFound\n Exiting"
7891  return -1
7892  }
7893  set JsonDict [json::json2dict $JSON_FILE]
7894  set result [catch {dict get $JsonDict $JSON_KEY} RETURNVALUE]
7895  if {"$result" != "0"} {
7896  Msg CriticalWarning "Cannot find $JSON_KEY in $JSON_FILE\n Exiting"
7897  return -1
7898  } else {
7899  return $RETURNVALUE
7900  }
7901 }
7902 
7903 
7904 # @brief Check if a Hog project exists, and if it exists returns the conf file
7905 # if it doesnt returns 0
7906 #
7907 # @brief project The project name
7908 # @brief repo_path The main path of the git repository
7909 proc ProjectExists {project {repo_path .}} {
7910  set index [lsearch -exact [ListProjects $repo_path 0] $project]
7911 
7912  if {$index >= 0} {
7913  # if project exists we return the relative hog.conf file
7914  return [lindex [ListProjects $repo_path 0 1] $index]
7915  } else {
7916  Msg Warning "Project not found. Available projects in $repo_path are"
7917  ListProjects $repo_path
7918  puts ""
7919  Msg Error "Project $project not found in repository $repo_path"
7920  return 1
7921  }
7922 }
7923 
7924 ## Read a property configuration file and returns a dictionary
7925 #
7926 # @param[in] file_name the configuration file
7927 #
7928 # @return The dictionary
7929 #
7930 proc ReadConf {file_name} {
7931  if {[catch {package require inifile 0.2.3} ERROR]} {
7932  Msg Error "Could not find inifile package version 0.2.3 or higher.\n
7933  To use ghdl, libero or diamond with Hog, you need to install the tcllib package\n
7934  You can install it with 'sudo apt install tcllib' on Debian/Ubuntu or 'sudo dnf install tcllib' on Fedora/RedHat/CentOs."
7935  }
7936 
7937 
7938  ::ini::commentchar "#"
7939  set f [::ini::open $file_name]
7940  set properties [dict create]
7941  foreach sec [::ini::sections $f] {
7942  set new_sec $sec
7943  if {$new_sec == "files"} {
7944  continue
7945  }
7946  set key_pairs [::ini::get $f $sec]
7947  #manipulate strings here:
7948  regsub -all {\{\"} $key_pairs "\{" key_pairs
7949  regsub -all {\"\}} $key_pairs "\}" key_pairs
7950 
7951  dict set properties $new_sec [dict create {*}$key_pairs]
7952  }
7953 
7954  ::ini::close $f
7955 
7956  return $properties
7957 }
7958 
7959 ## @brief Function used to read the list of files generated at creation time by tcl scripts in Project/proj/.hog/extra.files
7960 #
7961 # @param[in] extra_file_name the path to the extra.files file
7962 # @returns a dictionary with the full name of the files as key and a SHA as value
7963 #
7964 proc ReadExtraFileList {extra_file_name} {
7965  set extra_file_dict [dict create]
7966  if {[file exists $extra_file_name]} {
7967  set file [open $extra_file_name "r"]
7968  set file_data [read $file]
7969  close $file
7970 
7971  set data [split $file_data "\n"]
7972  foreach line $data {
7973  if {![regexp {^ *$} $line] & ![regexp {^ *\#} $line]} {
7974  set ip_and_md5 [regexp -all -inline {\S+} $line]
7975  dict lappend extra_file_dict "[lindex $ip_and_md5 0]" "[lindex $ip_and_md5 1]"
7976  }
7977  }
7978  }
7979  return $extra_file_dict
7980 }
7981 
7982 
7983 # @brief Expand a Vitis HLS configuration file (hls_config.cfg) into the list of
7984 # repository files it references, so Hog can hash them for dirty/SHA
7985 # detection without forcing the user to duplicate the list in a .src
7986 #
7987 # @param[in] cfg_file Absolute or relative path to the hls_config.cfg file.
7988 # @return A de-duplicated list of normalized absolute file paths.
7989 #
7990 proc ExpandHlsConfigFiles {cfg_file} {
7991  set out [list]
7992  if {![file exists $cfg_file] || ![file isfile $cfg_file]} {
7993  return $out
7994  }
7995  set cfg_dir [file normalize [file dirname $cfg_file]]
7996 
7997  if {[catch {set fp [open $cfg_file r]} err]} {
7998  Msg Warning "ExpandHlsConfigFiles: cannot open $cfg_file: $err"
7999  return $out
8000  }
8001  set lines [split [read $fp] "\n"]
8002  close $fp
8003 
8004  foreach line $lines {
8005  if {[regexp {^[\t\s]*$} $line]} {continue}
8006  if {[regexp {^[\t\s]*\#} $line]} {continue}
8007  if {[regexp {^\s*\[.*\]\s*$} $line]} {continue}
8008  if {![regexp {^\s*[^=\s]+\s*=\s*(.+?)\s*$} $line -> value]} {continue}
8009 
8010  foreach tok [regexp -all -inline {\S+} $value] {
8011  if {[file pathtype $tok] eq "absolute"} {
8012  set candidate [file normalize $tok]
8013  } else {
8014  set candidate [file normalize [file join $cfg_dir $tok]]
8015  }
8016  if {[file isfile $candidate]} {
8017  lappend out $candidate
8018  } elseif {[file isdirectory $candidate]} {
8019  set stack [list $candidate]
8020  while {[llength $stack] > 0} {
8021  set d [lindex $stack 0]
8022  set stack [lrange $stack 1 end]
8023  foreach f [glob -nocomplain -directory $d -types f *] {
8024  lappend out [file normalize $f]
8025  }
8026  foreach sub [glob -nocomplain -directory $d -types d *] {
8027  lappend stack $sub
8028  }
8029  }
8030  }
8031  }
8032  }
8033  return [lsort -unique $out]
8034 }
8035 
8036 
8037 # @brief Discover HLS components declared in a project's hog.conf and return
8038 # the absolute path of each component's hls_config.cfg
8039 #
8040 # @param[in] conf_file Absolute path of the project's hog.conf
8041 # @param[in] repo_path Repository root (paths in HLS_CONFIG are relative to it)
8042 # @return A dict { component_name -> absolute_cfg_path }. Empty if no HLS
8043 proc GetHlsConfigsFromProjConf {conf_file repo_path} {
8044  set out [dict create]
8045  if {![file exists $conf_file]} {return $out}
8046  if {[catch {set properties [ReadConf $conf_file]} err]} {
8047  Msg Debug "GetHlsConfigsFromProjConf: cannot parse $conf_file: $err"
8048  return $out
8049  }
8050  set hls_components [dict filter $properties key {hls:*}]
8051  dict for {hls_key hls_props} $hls_components {
8052  if {![regexp {^hls:(.+)$} $hls_key -> component_name]} {continue}
8053  set component_name [string trim $component_name]
8054  set cfg_rel ""
8055  if {[dict exists $hls_props hls_config]} {
8056  set cfg_rel [dict get $hls_props hls_config]
8057  } elseif {[dict exists $hls_props HLS_CONFIG]} {
8058  set cfg_rel [dict get $hls_props HLS_CONFIG]
8059  }
8060  if {$cfg_rel eq ""} {continue}
8061  set cfg_abs [file normalize "$repo_path/$cfg_rel"]
8062  if {![file exists $cfg_abs]} {
8063  Msg CriticalWarning "HLS component '$component_name': HLS_CONFIG=$cfg_rel does not exist on disk."
8064  continue
8065  }
8066  dict set out $component_name $cfg_abs
8067  }
8068  return $out
8069 }
8070 
8071 
8072 # @brief Read a list file and return a list of three dictionaries
8073 #
8074 # Additional information is provided with text separated from the file name with one or more spaces
8075 #
8076 # @param[in] args The arguments are <list_file> <path> [options]
8077 # * list_file file containing vhdl list with optional properties
8078 # * path path the vhdl file are referred to in the list file
8079 # Options:
8080 # * -lib <library> name of the library files will be added to, if not given will be extracted from the file name
8081 # * -sha_mode if 1, the list files will be added as well and the IPs will be added to the file rather than to the special ip library.
8082 # The SHA mode should be used when you use the lists to calculate the git SHA, rather than to add the files to the project.
8083 #
8084 # @return a list of 3 dictionaries:
8085 # "libraries" has library name as keys and a list of filenames as values,
8086 # "properties" has as file names as keys and a list of properties as values
8087 # "filesets" has the fileset' names as keys and the list of associated libraries as values.
8088 proc ReadListFile {args} {
8089  if {[IsQuartus]} {
8090  load_package report
8091  if {[catch {package require cmdline} ERROR]} {
8092  puts "$ERROR\n If you are running this script on tclsh, you can fix this by installing 'tcllib'"
8093  return 1
8094  }
8095  }
8096  # tclint-disable line-length
8097  set parameters {
8098  {lib.arg "" "The name of the library files will be added to, if not given will be extracted from the file name."}
8099  {fileset.arg "" "The name of the library, from the main list file"}
8100  {sha_mode "If set, the list files will be added as well and the IPs will be added to the file rather than to the special IP library. The SHA mode should be used when you use the lists to calculate the git SHA, rather than to add the files to the project."}
8101  {print_log "If set, will use PrintFileTree for the VIEW directive"}
8102  {indent.arg "" "Used to indent files with the VIEW directive"}
8103  }
8104  # tclint-enable line-length
8105  set usage "USAGE: ReadListFile \[options\] <list file> <path>"
8106  if {[catch {array set options [cmdline::getoptions args $parameters $usage]}] || [llength $args] != 2} {
8107  Msg CriticalWarning "[cmdline::usage $parameters $usage]"
8108  return
8109  }
8110 
8111 
8112  set list_file [lindex $args 0]
8113  set path [lindex $args 1]
8114  set sha_mode $options(sha_mode)
8115  set lib $options(lib)
8116  set fileset $options(fileset)
8117  set print_log $options(print_log)
8118  set indent $options(indent)
8119 
8120  if {$sha_mode == 1} {
8121  set sha_mode_opt "-sha_mode"
8122  } else {
8123  set sha_mode_opt ""
8124  }
8125 
8126  if {$print_log == 1} {
8127  set print_log_opt "-print_log"
8128  } else {
8129  set print_log_opt ""
8130  }
8131 
8132  # if no library is given, work it out from the file name
8133  if {$lib eq ""} {
8134  set lib [file rootname [file tail $list_file]]
8135  }
8136  set fp [open $list_file r]
8137  set file_data [read $fp]
8138  close $fp
8139  set list_file_ext [file extension $list_file]
8140  switch $list_file_ext {
8141  .sim {
8142  if {$fileset eq ""} {
8143  # If fileset is empty, use the library name for .sim file
8144  set fileset "$lib"
8145  }
8146  }
8147  .con {
8148  set fileset "constrs_1"
8149  }
8150  default {
8151  set fileset "sources_1"
8152  }
8153  }
8154 
8155  set libraries [dict create]
8156  set filesets [dict create]
8157  set properties [dict create]
8158  # Process data file
8159  set data [split $file_data "\n"]
8160  set data [ExtractFilesSection $data]
8161  set n [llength $data]
8162  set last_printed ""
8163  if {$print_log == 1} {
8164  if {$indent eq ""} {
8165  set list_file_rel [file tail $list_file]
8166  Msg Status "\n$list_file_rel"
8167  }
8168  set last_printed [PrintFileTree $data $path "$indent"]
8169  }
8170  Msg Debug "$n lines read from $list_file."
8171  set cnt 0
8172 
8173  foreach line $data {
8174  # Exclude empty lines and comments
8175  if {![regexp {^[\t\s]*$} $line] & ![regexp {^[\t\s]*\#} $line]} {
8176  set file_and_prop [regexp -all -inline {\S+} $line]
8177  set srcfile [lindex $file_and_prop 0]
8178  set srcfile "$path/$srcfile"
8179 
8180  set srcfiles [glob -nocomplain $srcfile]
8181 
8182  # glob the file list for wildcards
8183  if {$srcfiles != $srcfile && ![string equal $srcfiles ""]} {
8184  Msg Debug "Wildcard source expanded from $srcfile to $srcfiles"
8185  } else {
8186  if {![file exists $srcfile]} {
8187  if {$print_log == 0} {
8188  Msg CriticalWarning "File: $srcfile (from list file: $list_file) does not exist."
8189  }
8190  continue
8191  }
8192  }
8193 
8194  foreach vhdlfile $srcfiles {
8195  if {[file exists $vhdlfile]} {
8196  set vhdlfile [file normalize $vhdlfile]
8197  set extension [file extension $vhdlfile]
8198  ### Set file properties
8199  set prop [lrange $file_and_prop 1 end]
8200 
8201  # The next lines should be inside the case for recursive list files, also we should check the allowed properties for the .src as well
8202  set library [lindex [regexp -inline {\ylib\s*=\s*(.+?)\y.*} $prop] 1]
8203  if {$library == ""} {
8204  set library $lib
8205  }
8206 
8207  if {$extension == $list_file_ext} {
8208  # Deal with recursive list files
8209  # In the next regex we use \S+ instead of .+? because we want to include forward slashes
8210  set ref_path [lindex [regexp -inline {\ypath\s*=\s*(\S+).*} $prop] 1]
8211  if {$ref_path eq ""} {
8212  set ref_path $path
8213  } else {
8214  set ref_path [file normalize $path/$ref_path]
8215  }
8216  Msg Debug "List file $vhdlfile found in list file, recursively opening it using path \"$ref_path\"..."
8217  if {$print_log == 1} {
8218  if {[file normalize $last_printed] ne [file normalize $vhdlfile]} {
8219  Msg Status "$indent Inside [file tail $vhdlfile]:"
8220  set last_printed ""
8221  }
8222  }
8223  lassign [ReadListFile {*}"-indent \" $indent\" -lib $library -fileset $fileset $sha_mode_opt $print_log_opt $vhdlfile $ref_path"] l p fs
8224  set libraries [MergeDict $l $libraries]
8225  set properties [MergeDict $p $properties]
8226  set filesets [MergeDict $fs $filesets]
8227  } elseif {[lsearch {.src .sim .con ReadExtraFileList} $extension] >= 0} {
8228  # Not supported extensions
8229  Msg Error "$vhdlfile cannot be included into $list_file, $extension files must be included into $extension files."
8230  } else {
8231  # Deal with single files
8232  regsub -all " *= *" $prop "=" prop
8233  # Fill property dictionary
8234  foreach p $prop {
8235  # No need to append the lib= property
8236  if {[string first "lib=" $p] == -1} {
8237  # Get property name up to the = (for QSYS properties at the moment)
8238  set pos [string first "=" $p]
8239  if {$pos == -1} {
8240  set prop_name $p
8241  } else {
8242  set prop_name [string range $p 0 [expr {$pos - 1}]]
8243  }
8244  if {[IsInList $prop_name [DictGet [ALLOWED_PROPS] $extension]]
8245  || [string first "top" $p] == 0
8246  || $list_file_ext eq ".ipb"
8247  || $list_file_ext eq ".chb"} {
8248  if {$list_file_ext eq ".ipb"} {
8249  dict lappend properties $vhdlfile $path/$p
8250  } else {
8251  dict lappend properties $vhdlfile $p
8252  }
8253  Msg Debug "Adding property $p to $vhdlfile..."
8254  } elseif {$list_file_ext != ".ipb" && $list_file_ext != ".chb"} {
8255  Msg Warning "Setting Property $p is not supported for file $vhdlfile or it is already its default. \
8256  The allowed properties for this file type are \[ [DictGet [ALLOWED_PROPS] $extension]\]"
8257  }
8258  }
8259  }
8260  if {[lsearch {.xci .ip .bd .xcix} $extension] >= 0} {
8261  # Adding IP library
8262  set lib_name "ips.src"
8263  } elseif {[IsInList $extension {.vhd .vhdl}] || $list_file_ext == ".sim"} {
8264  # VHDL files and simulation
8265  if {![IsInList $extension {.vhd .vhdl}]} {
8266  set lib_name "others.sim"
8267  } else {
8268  set lib_name "$library$list_file_ext"
8269  }
8270  } elseif {$list_file_ext == ".con"} {
8271  set lib_name "sources.con"
8272  } elseif {$list_file_ext == ".ipb"} {
8273  set lib_name "xml.ipb"
8274  } elseif {$list_file_ext == ".chb"} {
8275  set lib_name "cheby.chb"
8276  } elseif {[IsInList $list_file_ext {.src}] && [IsInList $extension {.c .cpp .h .hpp}]} {
8277  # Adding Vitis library
8278  set lib_name "$library$list_file_ext"
8279  } elseif {[IsLibero] && $list_file_ext == ".src"} {
8280  set lib_name "$library.src"
8281  } else {
8282  # Other files are stored in the OTHER dictionary from vivado (no library assignment)
8283  set lib_name "others.src"
8284  }
8285 
8286  Msg Debug "Appending $vhdlfile to $lib_name list..."
8287  dict lappend libraries $lib_name $vhdlfile
8288  if {$sha_mode != 0 && [file type $vhdlfile] eq "link"} {
8289  #if the file is a link, also add the linked file in sha mode
8290  set real_file [GetLinkedFile $vhdlfile]
8291  dict lappend libraries $lib_name $real_file
8292  Msg Debug "File $vhdlfile is a soft link, also adding the real file: $real_file"
8293  }
8294 
8295  # Auto-expand HLS config files: when a .cfg is referenced from a .src
8296  # we treat it as a Vitis HLS hls_config.cfg and add every existing
8297  # file/dir it references (syn.file, tb.file, -I include dirs, ...)
8298  # to the same library. This avoids forcing the user to duplicate the
8299  # HLS file list in both hls_config.cfg and the .src.
8300  if {$list_file_ext eq ".src" && $extension eq ".cfg"} {
8301  set hls_extras [ExpandHlsConfigFiles $vhdlfile]
8302  if {$print_log == 1 && [llength $hls_extras] > 0} {
8303  Msg Status "$indent Inside [file tail $vhdlfile] (HLS auto-expand):"
8304  }
8305  set n_extras [llength $hls_extras]
8306  set i 0
8307  foreach hls_extra $hls_extras {
8308  incr i
8309  if {$hls_extra eq $vhdlfile} {continue}
8310  Msg Debug "HLS cfg expansion: adding $hls_extra (from $vhdlfile) to $lib_name"
8311  if {$print_log == 1} {
8312  if {$i == $n_extras} {set pad "└──"} else {set pad "├──"}
8313  set rel [Relative [file dirname $vhdlfile] $hls_extra]
8314  Msg Status "$indent $pad $rel"
8315  }
8316  dict lappend libraries $lib_name $hls_extra
8317  if {$sha_mode != 0 && [file type $hls_extra] eq "link"} {
8318  set real_extra [GetLinkedFile $hls_extra]
8319  dict lappend libraries $lib_name $real_extra
8320  Msg Debug "HLS expanded file $hls_extra is a soft link, also adding $real_extra"
8321  }
8322  }
8323  }
8324 
8325 
8326  # Create the fileset (if not already) and append the library
8327  if {[dict exists $filesets $fileset] == 0} {
8328  # Fileset has not been defined yet, adding to dictionary...
8329  Msg Debug "Adding $fileset to the fileset dictionary..."
8330  Msg Debug "Adding library $lib_name to fileset $fileset..."
8331  dict set filesets $fileset $lib_name
8332  } else {
8333  # Fileset already exist in dictionary, append library to list, if not already there
8334  if {[IsInList $lib_name [DictGet $filesets $fileset]] == 0} {
8335  Msg Debug "Adding library $lib_name to fileset $fileset..."
8336  dict lappend filesets $fileset $lib_name
8337  }
8338  }
8339  }
8340  incr cnt
8341  } else {
8342  Msg CriticalWarning "File $vhdlfile not found."
8343  }
8344  }
8345  }
8346  }
8347 
8348  if {$sha_mode != 0} {
8349  #In SHA mode we also need to add the list file to the list
8350  if {$list_file_ext eq ".ipb"} {
8351  set sha_lib "xml.ipb"
8352  } elseif {$list_file_ext eq ".chb"} {
8353  set sha_lib "cheby.chb"
8354  } else {
8355  set sha_lib $lib$list_file_ext
8356  }
8357  dict lappend libraries $sha_lib [file normalize $list_file]
8358  if {[file type $list_file] eq "link"} {
8359  #if the file is a link, also add the linked file
8360  set real_file [GetLinkedFile $list_file]
8361  dict lappend libraries $lib$list_file_ext $real_file
8362  Msg Debug "List file $list_file is a soft link, also adding the real file: $real_file"
8363  }
8364  }
8365  return [list $libraries $properties $filesets]
8366 }
8367 
8368 ## @brief Returns the destination path relative to base
8369 #
8370 # @param[in] base the path with respect to witch the dst path is calculated
8371 # @param[in] dst the path to be calculated with respect to base
8372 # @param[in] quiet if 1, does not print warnings when paths are of different types
8373 #
8374 proc Relative {base dst {quiet 0}} {
8375  if {![string equal [file pathtype $base] [file pathtype $dst]]} {
8376  if {$quiet == 0} {
8377  Msg CriticalWarning "Unable to compute relation for paths of different path types: [file pathtype $base] vs. [file pathtype $dst], ($base vs. $dst)"
8378  }
8379  return ""
8380  }
8381 
8382  set base [file normalize [file join [pwd] $base]]
8383  set dst [file normalize [file join [pwd] $dst]]
8384 
8385  set save $dst
8386  set base [file split $base]
8387  set dst [file split $dst]
8388 
8389  while {[string equal [lindex $dst 0] [lindex $base 0]]} {
8390  set dst [lrange $dst 1 end]
8391  set base [lrange $base 1 end]
8392  if {![llength $dst]} {break}
8393  }
8394 
8395  set dstlen [llength $dst]
8396  set baselen [llength $base]
8397 
8398  if {($dstlen == 0) && ($baselen == 0)} {
8399  set dst .
8400  } else {
8401  while {$baselen > 0} {
8402  set dst [linsert $dst 0 ..]
8403  incr baselen -1
8404  }
8405  set dst [eval [linsert $dst 0 file join]]
8406  }
8407 
8408  return $dst
8409 }
8410 
8411 ## @brief Returns the path of filePath relative to pathName
8412 #
8413 # @param[in] pathName the path with respect to which the returned path is calculated
8414 # @param[in] filePath the path of filePath
8415 #
8416 proc RelativeLocal {pathName filePath} {
8417  if {[string first [file normalize $pathName] [file normalize $filePath]] != -1} {
8418  return [Relative $pathName $filePath]
8419  } else {
8420  return ""
8421  }
8422 }
8423 
8424 ## @brief Remove duplicates in a dictionary
8425 #
8426 # @param[in] mydict the input dictionary
8427 #
8428 # @return the dictionary stripped of duplicates
8429 proc RemoveDuplicates {mydict} {
8430  set new_dict [dict create]
8431  foreach key [dict keys $mydict] {
8432  set values [DictGet $mydict $key]
8433  foreach value $values {
8434  set idxs [lreverse [lreplace [lsearch -exact -all $values $value] 0 0]]
8435  foreach idx $idxs {
8436  set values [lreplace $values $idx $idx]
8437  }
8438  }
8439  dict set new_dict $key $values
8440  }
8441  return $new_dict
8442 }
8443 
8444 ## Reset files in the repository
8445 #
8446 # @param[in] reset_file a file containing a list of files separated by new lines or spaces (Hog-CI creates such a file in Projects/hog_reset_files)
8447 #
8448 # @return Nothing
8449 #
8450 proc ResetRepoFiles {reset_file} {
8451  if {[file exists $reset_file]} {
8452  Msg Info "Found $reset_file, opening it..."
8453  set fp [open $reset_file r]
8454  set wild_cards [lsearch -all -inline -not -regexp [split [read $fp] "\n"] "^ *$"]
8455  close $fp
8456  Msg Info "Found the following files/wild cards to restore if modified: $wild_cards..."
8457  foreach w $wild_cards {
8458  set mod_files [GetModifiedFiles "." $w]
8459  if {[llength $mod_files] > 0} {
8460  Msg Info "Found modified $w files: $mod_files, will restore them..."
8461  RestoreModifiedFiles "." $w
8462  } else {
8463  Msg Info "No modified $w files found."
8464  }
8465  }
8466  }
8467 }
8468 
8469 ## @brief Restore with checkout -- the files specified in pattern
8470 #
8471 # @param[in] repo_path the path of the git repository
8472 # @param[in] pattern the pattern with wildcards that files should match
8473 #
8474 proc RestoreModifiedFiles {{repo_path "."} {pattern "."}} {
8475  set old_path [pwd]
8476  cd $repo_path
8477  set ret [Git checkout $pattern]
8478  cd $old_path
8479  return
8480 }
8481 
8482 ## Search the Hog projects inside a directory
8483 #
8484 # @param[in] dir The directory to search
8485 #
8486 # @return The list of projects
8487 #
8488 proc SearchHogProjects {dir} {
8489  set projects_list {}
8490  if {[file exists $dir]} {
8491  if {[file isdirectory $dir]} {
8492  foreach proj_dir [glob -nocomplain -types d $dir/*] {
8493  if {![regexp {^.*Top/+(.*)$} $proj_dir dummy proj_name]} {
8494  Msg Warning "Could not parse Top directory $dir"
8495  break
8496  }
8497  if {[file exists "$proj_dir/hog.conf"]} {
8498  lappend projects_list $proj_name
8499  } else {
8500  foreach p [SearchHogProjects $proj_dir] {
8501  lappend projects_list $p
8502  }
8503  }
8504  }
8505  } else {
8506  Msg Error "Input $dir is not a directory!"
8507  }
8508  } else {
8509  Msg Error "Directory $dir doesn't exist!"
8510  }
8511  return $projects_list
8512 }
8513 
8514 ## @brief Sets the generics in all the sim.conf simulation file sets
8515 #
8516 # @param[in] repo_path: the top folder of the projectThe path to the main git repository
8517 # @param[in] proj_dir: the top folder of the project
8518 # @param[in] target: software target(vivado, questa)
8519 #
8520 proc SetGenericsSimulation {repo_path proj_dir target} {
8521  set top_dir "$repo_path/Top/$proj_dir"
8522  set simsets [get_filesets]
8523  if {$simsets != ""} {
8524  foreach simset $simsets {
8525  # Only for simulation filesets
8526  if {[get_property FILESET_TYPE $simset] != "SimulationSrcs"} {
8527  continue
8528  }
8529 
8530  set merged_generics_dict [dict create]
8531  # Get generics from sim.conf file
8532  set simset_dict [DictGet [GetSimSets $proj_dir $repo_path $simset] $simset]
8533  set hog_generics [GetGenericsFromConf $proj_dir]
8534  set simset_generics [DictGet $simset_dict "generics"]
8535  set merged_generics_dict [MergeDict $merged_generics_dict $simset_generics 0]
8536  set generic_str [GenericToSimulatorString $merged_generics_dict $target]
8537 
8538  Msg Debug "TOP = [get_property top [get_filesets sources_1]]"
8539  Msg Debug "GENERICS = [get_property generic [get_filesets sources_1]]"
8540 
8541  set_property generic $generic_str [get_filesets $simset]
8542  Msg Info "Setting generics $generic_str for simulator $target\
8543  and simulation file-set $simset..."
8544  }
8545  }
8546 }
8547 
8548 ## @brief set the top module as top module in the chosen fileset
8549 #
8550 # It automatically recognises the IDE
8551 #
8552 # @param[out] top_module Name of the top module
8553 # @param[in] fileset The name of the fileset
8554 #
8555 proc SetTopProperty {top_module fileset} {
8556  Msg Info "Setting TOP property to $top_module module"
8557  if {[IsXilinx]} {
8558  #VIVADO_ONLY
8559  set_property "top" $top_module [get_filesets $fileset]
8560  } elseif {[IsQuartus]} {
8561  #QUARTUS ONLY
8562  set_global_assignment -name TOP_LEVEL_ENTITY $top_module
8563  } elseif {[IsLibero]} {
8564  set_root -module $top_module
8565  } elseif {[IsDiamond]} {
8566  prj_impl option top $top_module
8567  }
8568 }
8569 
8570 ## @brief Returns a list of Vivado properties that expect a PATH for value
8571 proc VIVADO_PATH_PROPERTIES {} {
8572  return {"\.*\.TCL\.PRE$" "^.*\.TCL\.POST$" "^RQS_FILES$" "^INCREMENTAL\_CHECKPOINT$" "NOC\_SOLUTION\_FILE"}
8573 }
8574 
8575 ## @brief Returns a list of Vitis properties that expect a PATH for value
8576 proc VITIS_PATH_PROPERTIES {} {
8577  return {"^HW$" "^XPFM$" "^LINKER-SCRIPT$" "^LIBRARIES$" "^LIBRARY-SEARCH-PATH$"}
8578 }
8579 
8580 ## @brief Write a property configuration file from a dictionary
8581 #
8582 # @param[in] file_name the configuration file
8583 # @param[in] config the configuration dictionary
8584 # @param[in] comment comment to add at the beginning of configuration file
8585 #
8586 #
8587 proc WriteConf {file_name config {comment ""}} {
8588  if {[catch {package require inifile 0.2.3} ERROR]} {
8589  puts "$ERROR\n If you are running this script on tclsh, you can fix this by installing 'tcllib'"
8590  return 1
8591  }
8592 
8593  ::ini::commentchar "#"
8594  set f [::ini::open $file_name w]
8595 
8596  foreach sec [dict keys $config] {
8597  set section [dict get $config $sec]
8598  dict for {p v} $section {
8599  if {[string trim $v] == ""} {
8600  Msg Warning "Property $p has empty value. Skipping..."
8601  continue
8602  }
8603  ::ini::set $f $sec $p $v
8604  }
8605  }
8606 
8607  #write comment before the first section (first line of file)
8608  if {![string equal "$comment" ""]} {
8609  ::ini::comment $f [lindex [::ini::sections $f] 0] "" $comment
8610  set hog_header "Generated by Hog on [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S"]"
8611  ::ini::comment $f [lindex [::ini::sections $f] 0] "" $hog_header
8612  }
8613  ::ini::commit $f
8614 
8615  ::ini::close $f
8616 }
8617 
8618 ## @brief Set custom Verilog `define macros from the [defines] section of hog.conf
8619 #
8620 # @param[in] design The name of the design
8621 #
8622 proc WriteDefines {design} {
8623  set prj_defines [GetDefinesFromConf $design]
8624  if {[dict size $prj_defines] > 0} {
8625  if {[IsVivado]} {
8626  set define_string [GenericToSimulatorString $prj_defines "Vivado"]
8627  set_property verilog_define $define_string [current_fileset]
8628  Msg Info "Setting Verilog defines from the \[defines\] section of hog.conf..."
8629  Msg Debug "Detailed defines: $define_string"
8630  } else {
8631  set ide_name [GetIDEName]
8632  Msg Error "Project $design has a \[defines\] section in hog.conf, but Verilog defines are not supported for $ide_name projects."
8633  }
8634  }
8635 }
8636 
8637 ## Set the generics property
8638 #
8639 # @param[in] mode if it's "create", the function will assume the project is being created
8640 # @param[in] repo_path The path to the main git repository
8641 # @param[in] design The name of the design
8642 
8643 # @param[in] list of variables to be written in the generics in the usual order
8644 
8645 proc WriteGenerics {
8646  mode repo_path design date timee
8647  commit version top_hash top_ver hog_hash hog_ver
8648  cons_ver cons_hash libs vers hashes ext_names ext_hashes
8649  user_ip_repos user_ip_vers user_ip_hashes flavour {xml_ver ""} {xml_hash ""}
8650  {cheby_ver ""} {cheby_hash ""}
8651 } {
8652  Msg Info "Passing parameters/generics to project's top module..."
8653  # Read the project hog.conf once and reuse it for both the generic prefix
8654  # and the user-defined project generics
8655  set conf_file [file normalize "$repo_path/Top/$design/hog.conf"]
8656  set hog_properties [dict create]
8657  if {[file exists $conf_file]} {
8658  set hog_properties [ReadConf $conf_file]
8659  } else {
8660  Msg Warning "File $conf_file not found."
8661  }
8662  set hog_prefix [GetHogGenericPrefixFromDict $hog_properties]
8663  if {$hog_prefix ne ""} {
8664  Msg Info "Using Hog generic prefix '$hog_prefix'"
8665  }
8666  ##### Passing Hog generic to top file
8667  # set global generic variables
8668  set generic_string [concat \
8669  "[HogGenericName GLOBAL_DATE $hog_prefix]=[FormatGeneric $date]" \
8670  "[HogGenericName GLOBAL_TIME $hog_prefix]=[FormatGeneric $timee]" \
8671  "[HogGenericName GLOBAL_VER $hog_prefix]=[FormatGeneric $version]" \
8672  "[HogGenericName GLOBAL_SHA $hog_prefix]=[FormatGeneric $commit]" \
8673  "[HogGenericName TOP_SHA $hog_prefix]=[FormatGeneric $top_hash]" \
8674  "[HogGenericName TOP_VER $hog_prefix]=[FormatGeneric $top_ver]" \
8675  "[HogGenericName HOG_SHA $hog_prefix]=[FormatGeneric $hog_hash]" \
8676  "[HogGenericName HOG_VER $hog_prefix]=[FormatGeneric $hog_ver]" \
8677  "[HogGenericName CON_VER $hog_prefix]=[FormatGeneric $cons_ver]" \
8678  "[HogGenericName CON_SHA $hog_prefix]=[FormatGeneric $cons_hash]"]
8679  # xml hash
8680  if {$xml_hash != "" && $xml_ver != ""} {
8681  lappend generic_string \
8682  "[HogGenericName XML_VER $hog_prefix]=[FormatGeneric $xml_ver]" \
8683  "[HogGenericName XML_SHA $hog_prefix]=[FormatGeneric $xml_hash]"
8684  }
8685  # cheby hash
8686  if {$cheby_hash != "" && $cheby_ver != ""} {
8687  lappend generic_string \
8688  "[HogGenericName CHEBY_VER $hog_prefix]=[FormatGeneric $cheby_ver]" \
8689  "[HogGenericName CHEBY_SHA $hog_prefix]=[FormatGeneric $cheby_hash]"
8690  }
8691  #set project specific lists
8692  foreach l $libs v $vers h $hashes {
8693  set ver "[HogGenericName "[string toupper $l]_VER" $hog_prefix]=[FormatGeneric $v]"
8694  set hash "[HogGenericName "[string toupper $l]_SHA" $hog_prefix]=[FormatGeneric $h]"
8695  # Replaces all occurrences of dots (.) and hyphens (-) in the generic name
8696  # with underscores (_) to make it compatible with VHDL/Verilog syntax
8697  # Uses regsub with -all flag to replace all matches of the regex pattern [\.-]
8698  set ver [regsub -all {[\.-]} $ver {_}]
8699  set hash [regsub -all {[\.-]} $hash {_}]
8700  lappend generic_string "$ver" "$hash"
8701  }
8702 
8703  foreach e $ext_names h $ext_hashes {
8704  set hash "[HogGenericName "[string toupper $e]_SHA" $hog_prefix]=[FormatGeneric $h]"
8705  lappend generic_string "$hash"
8706  }
8707 
8708  foreach repo $user_ip_repos v $user_ip_vers h $user_ip_hashes {
8709  set repo_name [file tail $repo]
8710  set ver "[HogGenericName "[string toupper $repo_name]_VER" $hog_prefix]=[FormatGeneric $v]"
8711  set hash "[HogGenericName "[string toupper $repo_name]_SHA" $hog_prefix]=[FormatGeneric $h]"
8712  set ver [regsub -all {[\.-]} $ver {_}]
8713  set hash [regsub -all {[\.-]} $hash {_}]
8714  lappend generic_string "$ver" "$hash"
8715  }
8716 
8717  if {$flavour != -1} {
8718  lappend generic_string "[HogGenericName FLAVOUR $hog_prefix]=$flavour"
8719  }
8720 
8721  # Dealing with project generics in Vivado
8722  if {[IsVivado] || [IsVitisClassic] || [IsVitisUnified]} {
8723  set prj_generics [GenericToSimulatorString [DictGet $hog_properties generics] "Vivado"]
8724  set generic_string "$prj_generics $generic_string"
8725  }
8726 
8727  # Dealing with custom Verilog `define macros from the [defines] section of hog.conf
8728  WriteDefines $design
8729 
8730  # Extract the generics from the top level source file
8731  if {[IsXilinx]} {
8732  # Top File can be retrieved only at creation time or in ISE
8733  if {$mode == "create" || [IsISE]} {
8734  set top_file [GetTopFile]
8735  set top_name [GetTopModule]
8736  if {[file exists $top_file]} {
8737  set generics [GetFileGenerics $top_file $top_name]
8738 
8739  Msg Debug "Found top level generics $generics in $top_file"
8740 
8741  set filtered_generic_string ""
8742 
8743  foreach generic_to_set [split [string trim $generic_string]] {
8744  set key [lindex [split $generic_to_set "="] 0]
8745  if {[dict exists $generics $key]} {
8746  Msg Debug "Hog generic $key found in $top_name"
8747  lappend filtered_generic_string "$generic_to_set"
8748  } else {
8749  Msg Warning "Generic $key is passed by Hog but is NOT present in $top_name."
8750  }
8751  }
8752 
8753  # only filter in ISE
8754  if {[IsISE]} {
8755  set generic_string $filtered_generic_string
8756  }
8757  }
8758  }
8759 
8760  set_property generic $generic_string [current_fileset]
8761  Msg Info "Setting parameters/generics..."
8762  Msg Debug "Detailed parameters/generics: $generic_string"
8763 
8764 
8765  if {[IsVivado]} {
8766  # Dealing with project generics in Simulators
8767  set simulator [get_property target_simulator [current_project]]
8768  if {$mode == "create"} {
8769  SetGenericsSimulation $repo_path $design $simulator
8770  }
8771 
8772  WriteGenericsToBdIPs $mode $repo_path $design $generic_string
8773  }
8774  } elseif {[IsSynplify]} {
8775  Msg Info "Setting Synplify parameters/generics one by one..."
8776  foreach generic $generic_string {
8777  Msg Debug "Setting Synplify generic: $generic"
8778  set_option -hdl_param -set "$generic"
8779  }
8780  } elseif {[IsDiamond]} {
8781  Msg Info "Setting Diamond parameters/generics one by one..."
8782  prj_impl option -impl Implementation0 HDL_PARAM "$generic_string"
8783  } elseif {[IsVitisClassic] || [IsVitisUnified]} {
8784  if {[catch {set ws_apps [app list -dict]}]} {set ws_apps ""}
8785 
8786  foreach app_name [dict keys $ws_apps] {
8787  set defined_symbols [app config -name $app_name -get define-compiler-symbols]
8788  foreach generic_to_set [split [string trim $generic_string]] {
8789  set key [lindex [split $generic_to_set "="] 0]
8790  set value [lindex [split $generic_to_set "="] 1]
8791  if {[string match "32'h*" $value]} {
8792  set value [string map {"32'h" "0x"} $value]
8793  }
8794 
8795  foreach symbol [split $defined_symbols ";"] {
8796  if {[string match "$key=*" $symbol]} {
8797  Msg Debug "Generic $key found in $app_name, removing it..."
8798  app config -name $app_name -remove define-compiler-symbols "$symbol"
8799  }
8800  }
8801 
8802  Msg Info "Setting Vitis parameters/generics for app $app_name: $key=$value"
8803  app config -name $app_name define-compiler-symbols "$key=$value"
8804  }
8805  }
8806  }
8807 }
8808 
8809 ## @brief Applies generic values to IPs within block designs
8810 #
8811 # @param[in] mode create: to write the generics at creation time. synth to write at synthesis time
8812 # @param[in] repo_path The main path of the git repository
8813 # @param[in] proj The project name
8814 # @param[in] generic_string the string containing the generics to be applied
8815 proc WriteGenericsToBdIPs {mode repo_path proj generic_string} {
8816  Msg Debug "Parameters/generics passed to WriteGenericsToIP: $generic_string"
8817 
8818  set bd_ip_generics false
8819  set properties [ReadConf [lindex [GetConfFiles $repo_path/Top/$proj] 0]]
8820  if {[dict exists $properties "hog"]} {
8821  set propDict [dict get $properties "hog"]
8822  if {[dict exists $propDict "PASS_GENERICS_TO_BD_IPS"]} {
8823  set bd_ip_generics [dict get $propDict "PASS_GENERICS_TO_BD_IPS"]
8824  }
8825  }
8826 
8827  if {[string compare [string tolower $bd_ip_generics] "false"] == 0} {
8828  return
8829  }
8830 
8831  if {$mode == "synth"} {
8832  Msg Info "Attempting to apply generics pre-synthesis..."
8833  set PARENT_PRJ [get_property "PARENT.PROJECT_PATH" [current_project]]
8834  set workaround [open "$repo_path/Projects/$proj/.hog/presynth_workaround.tcl" "w"]
8835  puts $workaround "source \[lindex \$argv 0\];"
8836  puts $workaround "open_project \[lindex \$argv 1\];"
8837  puts $workaround "WriteGenericsToBdIPs \[lindex \$argv 2\] \[lindex \$argv 3\] \[lindex \$argv 4\] \[lindex \$argv 5\];"
8838  puts $workaround "close_project"
8839  close $workaround
8840  if {
8841  [catch {
8842  exec vivado -mode batch \
8843  -log $repo_path/Projects/$proj/.hog/presynth_workaround.log \
8844  -journal $repo_path/Projects/$proj/.hog/presynth_workaround.jou \
8845  -source $repo_path/Projects/$proj/.hog/presynth_workaround.tcl \
8846  -tclargs $repo_path/Hog/Tcl/hog.tcl $PARENT_PRJ \
8847  "childprocess" $repo_path $proj $generic_string
8848  } errMsg] != 0
8849  } {
8850  Msg Error "Encountered an error while attempting workaround: $errMsg"
8851  }
8852  file delete $repo_path/Projects/$proj/.hog/presynth_workaround.tcl
8853  ResetRepoFiles "$repo_path/Projects/hog_reset_files"
8854  Msg Info "Done applying generics pre-synthesis."
8855  return
8856  }
8857 
8858  Msg Info "Looking for IPs to add generics to..."
8859  set ips_generic_string ""
8860  foreach generic_to_set [split [string trim $generic_string]] {
8861  set key [lindex [split $generic_to_set "="] 0]
8862  set value [lindex [split $generic_to_set "="] 1]
8863  append ips_generic_string "CONFIG.$key $value "
8864  }
8865 
8866 
8867  if {[string compare [string tolower $bd_ip_generics] "true"] == 0} {
8868  set ip_regex ".*"
8869  } else {
8870  set ip_regex $bd_ip_generics
8871  }
8872 
8873  set ip_list [get_ips -regex $ip_regex]
8874  Msg Debug "IPs found with regex \{$ip_regex\}: $ip_list"
8875 
8876  set regen_targets {}
8877 
8878  foreach {ip} $ip_list {
8879  set WARN_ABOUT_IP false
8880  set ip_props [list_property [get_ips $ip]]
8881 
8882  #Not sure if this is needed, but it's here to prevent potential errors with get_property
8883  if {[lsearch -exact $ip_props "IS_BD_CONTEXT"] == -1} {
8884  continue
8885  }
8886 
8887  if {[get_property "IS_BD_CONTEXT" [get_ips $ip]] eq "1"} {
8888  foreach {ip_prop} $ip_props {
8889  if {[dict exists $ips_generic_string $ip_prop]} {
8890  if {$WARN_ABOUT_IP == false} {
8891  lappend regen_targets [get_property SCOPE [get_ips $ip]]
8892  Msg Warning "The ip \{$ip\} contains generics that are set by Hog.\
8893  If this is IP is apart of a block design, the .bd file may contain stale, unused, values.\
8894  Hog will always apply the most up-to-date values to the IP during synthesis,\
8895  however these values may or may not be reflected in the .bd file."
8896  set WARN_ABOUT_IP true
8897  }
8898 
8899  # vivado is annoying about the format when setting generics for ips
8900  # this tries to find and set the format to what vivado likes
8901  set xci_path [get_property IP_FILE [get_ips $ip]]
8902  set generic_format [GetGenericFormatFromXci $ip_prop $xci_path]
8903  if {[string equal $generic_format "ERROR"]} {
8904  Msg Warning "Could not find format for generic $ip_prop in IP $ip. Skipping..."
8905  continue
8906  }
8907 
8908  set value_to_set [dict get $ips_generic_string $ip_prop]
8909  switch -exact $generic_format {
8910  "long" {
8911  if {[string match "32'h*" $value_to_set]} {
8912  scan [string map {"32'h" ""} $value_to_set] "%x" value_to_set
8913  }
8914  }
8915  "bool" {
8916  set value_to_set [expr {$value_to_set ? "true" : "false"}]
8917  }
8918  "float" {
8919  if {[string match "32'h*" $value_to_set]} {
8920  binary scan [binary format H* [string map {"32'h" ""} $value_to_set]] d value_to_set
8921  }
8922  }
8923  "bitString" {
8924  if {[string match "32'h*" $value_to_set]} {
8925  set value_to_set [string map {"32'h" "0x"} $value_to_set]
8926  }
8927  }
8928  "string" {
8929  set value_to_set [format "%s" $value_to_set]
8930  }
8931  default {
8932  Msg Warning "Unknown generic format $generic_format for IP $ip. Will attempt to pass as string..."
8933  }
8934  }
8935 
8936 
8937  Msg Info "The IP \{$ip\} contains: $ip_prop ($generic_format), setting it to $value_to_set."
8938  if {[catch {set_property -name $ip_prop -value $value_to_set -objects [get_ips $ip]} prop_error]} {
8939  Msg CriticalWarning "Failed to set property $ip_prop to $value_to_set for IP \{$ip\}: $prop_error"
8940  }
8941  }
8942  }
8943  }
8944  }
8945 
8946  foreach {regen_target} [lsort -unique $regen_targets] {
8947  Msg Info "Regenerating target: $regen_target"
8948  if {[catch {generate_target -force all [get_files $regen_target]} prop_error]} {
8949  Msg CriticalWarning "Failed to regen targets: $prop_error"
8950  }
8951  }
8952 }
8953 
8954 ## @brief Returns the format of a generic from an XML file
8955 ## @param[in] generic_name: The name of the generic
8956 ## @param[in] xml_file: The path to the XML XCI file
8957 proc GetGenericFormatFromXciXML {generic_name xml_file} {
8958  if {![file exists $xml_file]} {
8959  Msg Error "Could not find XML file: $xml_file"
8960  return "ERROR"
8961  }
8962 
8963  set fp [open $xml_file r]
8964  set xci_data [read $fp]
8965  close $fp
8966 
8967  set paramType "string"
8968  set modelparam_regex [format {^.*\y%s\y.*$} [string map {"CONFIG." "MODELPARAM_VALUE."} $generic_name]]
8969  set format_regex {format="([^"]+)"}
8970 
8971  set line [lindex [regexp -inline -line $modelparam_regex $xci_data] 0]
8972  Msg Debug "line: $line"
8973 
8974  if {[regexp $format_regex $line match format_value]} {
8975  Msg Debug "Extracted: $format_value format from xml"
8976  set paramType $format_value
8977  } else {
8978  Msg Debug "No format found, using string"
8979  }
8980 
8981  return $paramType
8982 }
8983 
8984 ## @brief Returns the format of a generic from an XCI file
8985 ## @param[in] generic_name: The name of the generic
8986 ## @param[in] xci_file: The path to the XCI file
8987 proc GetGenericFormatFromXci {generic_name xci_file} {
8988  if {![file exists $xci_file]} {
8989  Msg Error "Could not find XCI file: $xci_file"
8990  return "ERROR"
8991  }
8992 
8993  set fp [open $xci_file r]
8994  set xci_data [read $fp]
8995  close $fp
8996 
8997  set paramType "string"
8998  if {[string first "xilinx.com:schema:json_instance:1.0" $xci_data] == -1} {
8999  Msg Debug "XCI format is not JSON, trying XML..."
9000  set xml_file "[file rootname $xci_file].xml"
9001  return [GetGenericFormatFromXciXML $generic_name $xml_file]
9002  }
9003 
9004  set generic_name [string map {"CONFIG." ""} $generic_name]
9005  set ip_inst [ParseJSON $xci_data "ip_inst"]
9006  set parameters [dict get $ip_inst parameters]
9007  set component_parameters [dict get $parameters component_parameters]
9008  if {[dict exists $component_parameters $generic_name]} {
9009  set generic_info [dict get $component_parameters $generic_name]
9010  if {[dict exists [lindex $generic_info 0] format]} {
9011  set paramType [dict get [lindex $generic_info 0] format]
9012  Msg Debug "Extracted: $paramType format from xci"
9013  return $paramType
9014  }
9015  Msg Debug "No format found, using string"
9016  return $paramType
9017  } else {
9018  return "ERROR"
9019  }
9020 }
9021 
9022 
9023 ## @brief Returns the gitlab-ci.yml snippet for a CI stage and a defined project
9024 #
9025 # @param[in] proj_name: The project name
9026 # @param[in] ci_confs: Dictionary with CI configurations
9027 #
9028 proc WriteGitLabCIYAML {proj_name {ci_conf ""}} {
9029  if {[catch {package require yaml 0.3.3} YAMLPACKAGE]} {
9030  Msg CriticalWarning "Cannot find package YAML.\n Error message: $YAMLPACKAGE. \
9031  If you are running on tclsh, you can fix this by installing package \"tcllib\""
9032  return -1
9033  }
9034 
9035  set job_list []
9036  if {$ci_conf != ""} {
9037  set ci_confs [ReadConf $ci_conf]
9038  foreach sec [dict keys $ci_confs] {
9039  if {[string first : $sec] == -1} {
9040  lappend job_list $sec
9041  }
9042  }
9043  } else {
9044  set job_list {"generate_project" "simulate_project"}
9045  set ci_confs ""
9046  }
9047 
9048  set out_yaml [huddle create]
9049  foreach job $job_list {
9050  # Check main project configurations
9051  set huddle_tags [huddle list]
9052  set tag_section ""
9053  set sec_dict [dict create]
9054 
9055  if {$ci_confs != ""} {
9056  foreach var [dict keys [dict get $ci_confs $job]] {
9057  if {$var == "tags"} {
9058  set tag_section "tags"
9059  set tags [dict get [dict get $ci_confs $job] $var]
9060  set tags [split $tags ","]
9061  foreach tag $tags {
9062  set tag_list [huddle list $tag]
9063  set huddle_tags [huddle combine $huddle_tags $tag_list]
9064  }
9065  } else {
9066  dict set sec_dict $var [dict get [dict get $ci_confs $job] $var]
9067  }
9068  }
9069  }
9070 
9071  # Check if there are extra variables in the conf file
9072  set huddle_variables [huddle create "PROJECT_NAME" $proj_name "extends" ".vars"]
9073  if {[dict exists $ci_confs "$job:variables"]} {
9074  set var_dict [dict get $ci_confs $job:variables]
9075  foreach var [dict keys $var_dict] {
9076  # puts [dict get $var_dict $var]
9077  set value [dict get $var_dict "$var"]
9078  set var_inner [huddle create "$var" "$value"]
9079  set huddle_variables [huddle combine $huddle_variables $var_inner]
9080  }
9081  }
9082 
9083 
9084  set middle [huddle create "extends" ".$job" "variables" $huddle_variables]
9085  foreach sec [dict keys $sec_dict] {
9086  set value [dict get $sec_dict $sec]
9087  set var_inner [huddle create "$sec" "$value"]
9088  set middle [huddle combine $middle $var_inner]
9089  }
9090  if {$tag_section != ""} {
9091  set middle2 [huddle create "$tag_section" $huddle_tags]
9092  set middle [huddle combine $middle $middle2]
9093  }
9094 
9095  set outer [huddle create "$job:$proj_name" $middle]
9096  set out_yaml [huddle combine $out_yaml $outer]
9097  }
9098 
9099  return [string trimleft [yaml::huddle2yaml $out_yaml] "-"]
9100 }
9101 
9102 # @brief Write the content of Hog-library-dictionary created from the project into a .src/.ext/.con list file
9103 #
9104 # @param[in] libs The Hog-Library dictionary with the list of files in the project to write
9105 # @param[in] props The Hog-library dictionary with the file sets
9106 # @param[in] list_path The path of the output list file
9107 # @param[in] repo_path The main repository path
9108 # @param[in] ext_path The external path
9109 proc WriteListFiles {libs props list_path repo_path {ext_path ""}} {
9110  # Writing simulation list files
9111  foreach lib [dict keys $libs] {
9112  if {[llength [DictGet $libs $lib]] > 0} {
9113  set list_file_name $list_path$lib
9114  set list_file [open $list_file_name w]
9115  Msg Info "Writing $list_file_name..."
9116  puts $list_file "#Generated by Hog on [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S"]"
9117  foreach file [DictGet $libs $lib] {
9118  # Retrieve file properties from prop list
9119  set prop [DictGet $props $file]
9120  # Check if file is local to the repository or external
9121  if {[RelativeLocal $repo_path $file] != ""} {
9122  set file_path [RelativeLocal $repo_path $file]
9123  puts $list_file "$file_path $prop"
9124  } elseif {[RelativeLocal $ext_path $file] != ""} {
9125  set file_path [RelativeLocal $ext_path $file]
9126  set ext_list_file [open "[file rootname $list_file].ext" a]
9127  puts $ext_list_file "$file_path $prop"
9128  close $ext_list_file
9129  } else {
9130  # File is not relative to repo or ext_path... Write a Warning and continue
9131  Msg Warning "The path of file $file is not relative to your repository. Please check!"
9132  }
9133  }
9134  close $list_file
9135  }
9136  }
9137 }
9138 
9139 # @brief Write the content of Hog-library-dictionary created from the project into a .sim list file
9140 #
9141 # @param[in] libs The Hog-Library dictionary with the list of files in the project to write
9142 # @param[in] props The Hog-library dictionary with the file sets
9143 # @param[in] simsets The Hog-library dictionary with the file sets (relevant only for simulation)
9144 # @param[in] list_path The path of the output list file
9145 # @param[in] repo_path The main repository path
9146 # @param[in] force If 1, it will overwrite the existing list files
9147 proc WriteSimListFile {simset libs props simsets list_path repo_path {force 0}} {
9148  # Writing simulation list file
9149  set list_file_name $list_path/${simset}.sim
9150  if {$force == 0 && [file exists $list_file_name]} {
9151  Msg Info "List file $list_file_name already exists, skipping..."
9152  continue
9153  }
9154 
9155  set list_file [open $list_file_name a+]
9156 
9157  # Write the header with the simulator
9158  puts $list_file "\[files\]"
9159  Msg Info "Writing $list_file_name..."
9160  foreach lib [DictGet $simsets $simset] {
9161  foreach file [DictGet $libs $lib] {
9162  # Retrieve file properties from prop list
9163  set prop [DictGet $props $file]
9164  # Check if file is local to the repository or external
9165  if {[RelativeLocal $repo_path $file] != ""} {
9166  set file_path [RelativeLocal $repo_path $file]
9167  set lib_name [file rootname $lib]
9168  if {$lib_name != $simset && [file extension $file] == ".vhd" && [file extension $file] == ""} {
9169  lappend prop "lib=$lib_name"
9170  }
9171  puts $list_file "$file_path $prop"
9172  } else {
9173  # File is not relative to repo or ext_path... Write a Warning and continue
9174  Msg Warning "The path of file $file is not relative to your repository. Please check!"
9175  }
9176  }
9177  }
9178  close $list_file
9179 }
9180 
9181 
9182 ## @brief Write into a file, and if the file exists, it will append the string
9183 #
9184 # @param[out] File The log file to write into the message
9185 # @param[in] msg The message text
9186 proc WriteToFile {File msg} {
9187  set f [open $File a+]
9188  puts $f $msg
9189  close $f
9190 }
9191 
9192 ## Write the resource utilization table into a a file (Vivado only)
9193 #
9194 # @param[in] input the input .rpt report file from Vivado
9195 # @param[in] output the output file
9196 # @param[in] project_name the name of the project
9197 # @param[in] run synthesis or implementation
9198 proc WriteUtilizationSummary {input output project_name run} {
9199  set f [open $input "r"]
9200  set o [open $output "a"]
9201  puts $o "## $project_name $run Utilization report\n\n"
9202  struct::matrix util_m
9203  util_m add columns 14
9204  util_m add row
9205  if {[GetIDEVersion] >= 2021.0} {
9206  util_m add row "| **Site Type** | **Used** | **Fixed** | **Prohibited** | **Available** | **Util%** |"
9207  util_m add row "| --- | --- | --- | --- | --- | --- |"
9208  } else {
9209  util_m add row "| **Site Type** | **Used** | **Fixed** | **Available** | **Util%** |"
9210  util_m add row "| --- | --- | --- | --- | --- |"
9211  }
9212 
9213  set luts 0
9214  set regs 0
9215  set uram 0
9216  set bram 0
9217  set dsps 0
9218  set ios 0
9219 
9220  while {[gets $f line] >= 0} {
9221  if {([string first "| CLB LUTs" $line] >= 0 || [string first "| Slice LUTs" $line] >= 0) && $luts == 0} {
9222  util_m add row $line
9223  set luts 1
9224  }
9225  if {([string first "| CLB Registers" $line] >= 0 || [string first "| Slice Registers" $line] >= 0) && $regs == 0} {
9226  util_m add row $line
9227  set regs 1
9228  }
9229  if {[string first "| Block RAM Tile" $line] >= 0 && $bram == 0} {
9230  util_m add row $line
9231  set bram 1
9232  }
9233  if {[string first "URAM " $line] >= 0 && $uram == 0} {
9234  util_m add row $line
9235  set uram 1
9236  }
9237  if {[string first "DSPs" $line] >= 0 && $dsps == 0} {
9238  util_m add row $line
9239  set dsps 1
9240  }
9241  if {[string first "Bonded IOB" $line] >= 0 && $ios == 0} {
9242  util_m add row $line
9243  set ios 1
9244  }
9245  }
9246  util_m add row
9247 
9248  close $f
9249  puts $o [util_m format 2string]
9250  close $o
9251 }
9252 
9253 # Check Git Version when sourcing hog.tcl
9254 if {[GitVersion 2.7.2] == 0} {
9255  Msg Error "Found Git version older than 2.7.2. Hog will not work as expected, exiting now."
9256 }
9257 
9258 ## @brief Tries to find the coorrect command to be launched for curl
9259 #
9260 # @details If running in vivado shell you may need to unsed LD_LIBRARY_PATH befor running curl to avoid conflicts with vivado libraries.
9261 # This procedure tests curl if execution is correct returns "curl"
9262 # If execution fails tries to run env -u LD_LIBRARY_PATH curl --silent --show-error, and returns "env -u LD_LIBRARY_PATH curl --silent --show-error" on success.
9263 # If both fail returns "curl", this will most probably generate failures later
9264 proc GetCurl {{gitlab_url "https://gitlab.com"}} {
9265  if {[auto_execok curl] == ""} {
9266  Msg Warning "Cannot find a working curl invocation"
9267  return 0
9268  }
9269 
9270  if {[IsTclsh]} {
9271  set cmd [list curl --silent --show-error]
9272  } else {
9273  set cmd [list env -u LD_LIBRARY_PATH curl --silent --show-error]
9274  }
9275 
9276  if {![catch {exec {*}$cmd -I $gitlab_url}]} {
9277  return $cmd
9278  } else {
9279  Msg Warning "Impossible to contact $gitlab_url"
9280  return 0
9281  }
9282 }