#=======================================================================
# Makefile for riscv-tests/isa
#-----------------------------------------------------------------------

act_dir := .
src_dir := $(act_dir)/src
ref_dir := $(act_dir)/references
work_dir := $(WORK)
work_dir_isa := $(work_dir)/rv$(XLEN)i_m/$(RISCV_DEVICE)

include $(act_dir)/Makefrag
ifneq ($(RISCV_TEST),)
	target_tests = $(RISCV_TEST).elf
	target_tests_nosim = $(empty)
endif

default: all

#--------------------------------------------------------------------
# Build rules
#--------------------------------------------------------------------

vpath %.S $(act_dir)

INCLUDE=$(TARGETDIR)/$(RISCV_TARGET)/device/rv$(XLEN)i_m/$(RISCV_DEVICE)/Makefile.include
ifeq ($(wildcard $(INCLUDE)),)
    $(error Cannot find '$(INCLUDE)`. Check that RISCV_TARGET and RISCV_DEVICE are set correctly.)
endif
-include $(INCLUDE)

#------------------------------------------------------------
# Build and run assembly tests

%.log: %.elf
	$(V) echo "Execute $(@)"
	$(V) $(RUN_TARGET)


define compile_template

$(work_dir_isa)/%.elf: $(src_dir)/%.S
	$(V) echo "Compile $$(@)"
	@mkdir -p $$(@D)
	$(V) $(COMPILE_TARGET)

.PRECIOUS: $(work_dir_isa)/%.elf

endef

target_elf = $(foreach e,$(target_tests),$(work_dir_isa)/$(e))
target_elf_nosim = $(foreach e,$(addsuffix .elf, $(target_tests_nosim)),$(work_dir_isa)/$(e))
combined_elf = $(target_elf_nosim) $(target_elf)
target_log = $(patsubst %.elf,%.log,$(target_elf))

ifdef target_tests_nosim 
compile: copy 
# now copy must be performed before compile, 
# allowing us to copy over outputs if they won't simulate on spike correctly.
endif

copy:
	@mkdir -p $(work_dir_isa)
	$(info !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)
	$(info <<<<<<<<<<<<<<<<<<<<<<<<<<<< COPYING REFERENCES WITHOUT SIMULATING >>>>>>>>>>>>>>>>>>>>>>>>>>>>)
	$(info !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)
	$(V) echo "Copying References without simulating for the following tests: $(target_tests_nosim)"
	$(V) for test in $(target_tests_nosim); do grep -o '^[^#]*' $(ref_dir)/$$test.reference_output > $(work_dir_isa)/$$test.signature.output; done

compile: $(combined_elf)
run: $(target_log) 
# note that run doesnt use the combined elf so it doesnt run the nosim tests.

#------------------------------------------------------------
# Clean up

clean:
	rm -rf $(work_dir)
