# synth.tcl
yosys -import

# Read liberty files (may be space-delimited for multi-lib PDKs)
foreach _lib $::env(LIBERTY_FILE) {
    read_liberty -lib $_lib
}

# For single-command Yosys operations, use DFF/ABC-specific libs when available
set _liberty_dff [expr {[info exists ::env(LIBERTY_FILE_DFF)] ? $::env(LIBERTY_FILE_DFF) : [lindex $::env(LIBERTY_FILE) 0]}]
set _liberty_abc [expr {[info exists ::env(LIBERTY_FILE_ABC)] ? $::env(LIBERTY_FILE_ABC) : [lindex $::env(LIBERTY_FILE) 0]}]

if { [ info exists ::env(YOSYS_READ_SLANG_DOTF) ] } {
  if { [ info exists ::env(TOP_MODULE) ]} {
    read_slang --ignore-initial --ignore-timing --top $::env(TOP_MODULE) -f $::env(YOSYS_READ_SLANG_DOTF)
  } else {
    read_slang --ignore-initial --ignore-timing -f $::env(YOSYS_READ_SLANG_DOTF)
  }
}
if { [ info exists ::env(YOSYS_READ_VERILOG_DOTF) ] } {
    read_verilog --ignore-initial --ignore-timing  -f $::env(YOSYS_READ_VERILOG_DOTF)
}
if { [ info exists ::env(VERILOG_FILES) ] } {
  # Setup verilog include directories
  # This is deprecated in favor of a YOSYS_READ_SLANG_DOTF or YOSYS_READ_VERILOG_DOTF.
  set vIdirsArgs ""
  if { [info exists ::env(VERILOG_INCLUDE_DIRS)] && ![string equal $::env(VERILOG_INCLUDE_DIRS) ""] } {
    foreach dir $::env(VERILOG_INCLUDE_DIRS) {
      lappend vIdirsArgs "-I$dir"
    }
    set vIdirsArgs [join $vIdirsArgs]
  }
  set slang_args [list \
    -D SYNTHESIS --keep-hierarchy --compat=vcs --ignore-assertions --top $::env(TOP_MODULE) \
    {*}$vIdirsArgs]
  if { [info exists ::env(VERILOG_DEFINES)] && ![string equal $::env(VERILOG_DEFINES) ""] } {
    lappend slang_args {*}$::env(VERILOG_DEFINES)
  }
  # slang requires all files at once
  # Split VERILOG_FILES on spaces to get individual file paths
  lappend slang_args {*}[split $::env(VERILOG_FILES)]
  # Read Verilog - split the space-separated string into a list
  # TODO(drew): this flow does not use "slang_args", need to fix.
  read_slang --ignore-initial --ignore-timing --top $::env(TOP_MODULE) {*}[split $::env(VERILOG_FILES)]
}

# Synthesize
hierarchy -check -top $::env(TOP_MODULE)
flatten
alumacc
share
synth -top $::env(TOP_MODULE)
opt -full
fsm
fsm_opt

# Technology mapping
dfflibmap -liberty $_liberty_dff
abc -liberty $_liberty_abc
opt

# Cleanup
clean

# Write outputs
write_verilog -noattr $::env(OUT_DIR)/$::env(TOP_MODULE)_$::env(FILE_SUFFIX).syn.v
stat -liberty $_liberty_abc

exit
