#   This file is part of the 9086 project.
#
#   Copyright (c) 2024 Efthymios Kritikos
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
SOURCES=processor.v memory.v registers.v alu.v decoder.v general.v biu.v execute.v
INCLUDES=exec_state_def.v alu_header.v config.v ucode_header.v error_header.v
MICROCODE=ucode.txt
SYSTEM_VVP=system.vvp
PRINT_PATH_PREFIX=./
BUILD_FILES_PREFIX=build/

BOOT_CODE=boot_code.txt
VERILATOR_BIN=obj_dir/Vsystem
VERILATOR_FPGA_BIN=/Vfpga_top
NO_ASM=0
include ../common.mk

$(shell mkdir -p $(BUILD_FILES_PREFIX))
FPGA_SEED ::= $(shell seq 1 200|sort -R|head -n1)

ifeq "${BUILD_SEED_DIFFERENTIATION}" "1"
BUILD_NAME=${FPGA_BOARD}_${FPGA_SEED}
else
BUILD_NAME=${FPGA_BOARD}
endif

include fpga_config/${FPGA_BOARD}/config.mk

# Synthesis and bitstream creation for ECP5
ifeq "${ECP5_DEVICE}" "25F"
NEXTPNR_ECP5_DEV=--25k
else ifeq "${ECP5_DEVICE}" "85F"
NEXTPNR_ECP5_DEV=--85k
else
$(error invalid ECP5 device ${ECP5_DEVICE})
endif

EVENT_SIM_TESTBENCH=testbench.v
VERILATOR_TESTBENCH=testbench.cpp
SIMULATION_TOP_LEVEL_SOURCE=system.v
GTKWSAVE=../gtkwave_savefile.gtkw

SIMULATED_SOURCES ::= ${SIMULATION_TOP_LEVEL_SOURCE} ${SOURCES} ${INCLUDES}
FPGA_SIM_SOURCES ::= fpga_config/${FPGA_BOARD}/fpga_top.v ${SOURCES} ${FPGA_SOC_SIM_SOURCES} ${INCLUDES}
FPGA_SOURCES ::= fpga_config/${FPGA_BOARD}/fpga_top.v ${SOURCES} ${FPGA_SOC_SOURCES} ${INCLUDES}

#build options
VERILATOR_OPTS += --cc --exe

#binary options
VERILATOR_OPTS += --trace-fst --threads 1 --autoflush

#linter options
VERILATOR_OPTS += -Wall --Wno-DECLFILENAME

#optimisation options
VERILATOR_OPTS += -x-assign fast --x-initial fast
#For testing use:
#VERILATOR_OPTS += -x-assign unique --x-initial unique


################################################################################
####                           SIMULATION RECIPES                           ####
################################################################################

# COMPILING
${SYSTEM_VVP} : ${SIMULATED_SOURCES} ${EVENT_SIM_TESTBENCH}
	${QUIET_IVERILOG}
	${Q}iverilog -g2012 -D CALCULATE_IPC -D OUTPUT_JSON_STATISTICS -o "$@" ${SIMULATION_TOP_LEVEL_SOURCE} ${SOURCES} ${EVENT_SIM_TESTBENCH}

${VERILATOR_BIN}: ${VERILATOR_BIN}.mk
	${Q}make ${MAKEOPTS} PRINT_PATH_PREFIX=${PRINT_PATH_PREFIX}obj_dir/ OPT_FAST="-O2 -march=native -mtune=native" -C obj_dir -f ../verilator_makefile Vsystem

${VERILATOR_BIN}.mk: ${VERILATOR_TESTBENCH} ${SIMULATED_SOURCES}
	${QUIET_VERILATOR}
	mkdir -p ${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/
	rm -f ${VERILATOR_BIN}.mk # Verilator doesn't update this when just changing the testbench and the makefile breaks so we remove it to make sure
	${Q}verilator -DCALCULATE_IPC -DOUTPUT_JSON_STATISTICS ${VERILATOR_OPTS} $^

${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/${VERILATOR_FPGA_BIN}: ${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/${VERILATOR_FPGA_BIN}.mk
	${Q}make ${MAKEOPTS} PRINT_PATH_PREFIX=${PRINT_PATH_PREFIX}${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/ OPT_FAST="-O2 -march=native -mtune=native" -C "${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/" -f ../../verilator_makefile_fpga Vfpga_top

${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/${VERILATOR_FPGA_BIN}.mk: fpga_config/${FPGA_BOARD}/testbench.cpp ${FPGA_SIM_SOURCES}
	${QUIET_VERILATOR}
	mkdir -p "${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/" # Verilator doesn't update this when just changing the testbench and the makefile breaks so we remove it to make sure
	rm -f ${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/${VERILATOR_FPGA_BIN}.mk
	${Q}verilator -DCALCULATE_IPC -DOUTPUT_JSON_STATISTICS --Mdir ${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/ ${VERILATOR_OPTS} ../../fpga_config/${FPGA_BOARD}/testbench.cpp ${FPGA_SIM_SOURCES}

.PHONY: fpga_sim
fpga_sim fpga_sim.fst: ../boot_code/i2c_bootloader.stxt ${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/${VERILATOR_FPGA_BIN} ${MICROCODE} simplified_ucode.txt
	$(call QUIET_VERILATOR_RUN,$(word 2,$^),$<)
	${Q} ${NUMACTL} "${BUILD_FILES_PREFIX}/sim_${FPGA_BOARD}/${VERILATOR_FPGA_BIN}" +VERSION=${VERSION} +WAVEFORM="fpga_sim.fst" +COMMIT=${COMMIT} +BOOT_CODE="../boot_code/i2c_bootloader.stxt" +MICROCODE="simplified_ucode.txt"

################################################################################
####                           FPGA/ASIC RECIPES                            ####
################################################################################

simplified_ucode.txt:ucode.txt
	${Q}tr 'x' '0' < $^ | sed 's@//.*@@' | grep ^@ |sort | sed 's/.* .//;s/ $$//' | tr -d _ > $@

external_ip/litedram_core_ecp5_phy.v:
	${QUIET_DOWNLOAD}
	${Q}../tools/gen_litedram.sh -q "$@"

external_ip/litedram_core_ecp5_phy_sim.v:
	${QUIET_DOWNLOAD}
	${Q}../tools/gen_litedram.sh --simulation -q "$@"

#########################################
##     SYNTHESIS  RECIPES

#TODO: we are relying on yosys to trim the input program txt file and hope its enough for the whole program...
${BUILD_FILES_PREFIX}synth_ecp5_${FPGA_BOARD}.json: ${FPGA_SOURCES} ${FPGA_BOOTCODE} simplified_ucode.txt
	${QUIET_YOSYS}
	${Q} yosys -q -p 'read_verilog -defer -noautowire -sv '"${FPGA_SOURCES}; attrmap -tocase keep -imap keep="true" keep=1 -imap keep="false" keep=0 -remove keep=0; synth_ecp5 -json \"$@\" -abc9 -top fpga_top"

##########################################
##     PLACE AND ROUTE RECIPES

${BUILD_FILES_PREFIX}nextpnr-ecp5_${BUILD_NAME}.bit:${BUILD_FILES_PREFIX}synth_${FPGA_BOARD}.json
	${QUIET_NEXTPNR}
	${Q}printf '\e[1;30mNotice: nextpnr rng seed is : %s\e[0m\n' "${FPGA_SEED}"
	${Q} nextpnr-ecp5 --seed ${FPGA_SEED} --Werror -q --json $< --textcfg "$@_config_temp" ${NEXTPNR_ECP5_DEV} --package ${ECP5_PACKAGE} --speed ${ECP5_SPEED_GRADE} --lpf fpga_config/${FPGA_BOARD}/pin_constraint.pcf --report=${BUILD_FILES_PREFIX}nextpnr_report_${BUILD_NAME}.json
	${Q}../tools/parse_nextpnr_stats.sh --brief ${BUILD_FILES_PREFIX}nextpnr_report_${BUILD_NAME}.json
	${Q}mv "$@_config_temp" "$@_config" # nextpnr-ecp5 will still generate a file even if it fails breaking the assumptions of the build system.
	${QUIET_ECPPACK}
	${Q}ecppack --compress --freq 38.8 --input $@_config --bit $@

nextpnr-gui: ${BUILD_FILES_PREFIX}synth_${FPGA_BOARD}.json
	${QUIET_NEXTPNR}
	${Q} nextpnr-ecp5 --seed ${FPGA_SEED} --json $< ${NEXTPNR_ECP5_DEV} --package ${ECP5_PACKAGE} --speed ${ECP5_SPEED_GRADE} --lpf fpga_config/${FPGA_BOARD}/pin_constraint.pcf --gui

##########################################
##     BITSTREAM MODIFICATION FOR/AND UPLOADING

${BUILD_FILES_PREFIX}bitstream_${BUILD_NAME}.dfu:${BUILD_FILES_PREFIX}bitstream_${BUILD_NAME}.bit
	${QUIET_DFU_SUFFIX}
	${Q}cp "$<" "$<.tempdfu"
	@#From some testing, dfu-suffix does output errors to stderr so this should be fine
	${Q}dfu-suffix --vid 1209 --pid 5af0 --add "$<.tempdfu" > /dev/null
	${Q}mv "$<.tempdfu" "$@"

dfu_upload:${BUILD_FILES_PREFIX}bitstream_${BUILD_NAME}.dfu
	${QUIET_DFU_UTIL}
	${Q}stdbuf -o0 dfu-util --download "$<" |stdbuf -o0 tr '\n' '\a' | stdbuf -o0 tr '\r' '\n' | grep Download --line-buffered | stdbuf -o0 tr '\n' '\r' |stdbuf -o0 tr '\a' '\n'

minipro_upload:
	${QUIET_MINIPRO}
	${Q}minipro -p ${ROM_PART_ID} -w ${ROM_FILE}

################################################################################
####                                CLEAN-UP                                ####
################################################################################


.PHONY: clean
clean:
	$(call QUIET_CLEAN,system)
	${Q}rm -rf ${SYSTEM_VVP} *.fst boot_code.txt boot_code.bin *memdump *memdumptxt obj_dir simplified_ucode.txt abc.history build

.PHONY: mrproper
mrproper:
	$(call QUIET_MRPROPER,system)
	${Q}rm -f external_ip/litedram_core_ecp5_phy.v  external_ip/litedram_core_ecp5_phy_sim.v
