# Architecture selection (default: X86)
ARCH ?= X86
GEM5_BUILD = ~/gem5/build/$(ARCH)
GEM5_CONFIG = ~/gem5/configs/deprecated/example/se.py

# RISCV-specific configurations
ifeq ($(ARCH),RISCV)
    CXX = /home/zheng/.clang-dev/bin/clang
    CXXFLAGS = -march=rv64gc -O2 -static -fsanitize=signed-integer-overflow,unsigned-integer-overflow -fsanitize-hw-support=2
	ARCH_SUFFIX = _riscv
else
    # X86 configurations
    CXX = /home/zheng/.clang/bin/clang
    CXXFLAGS = -O2 -static -m64 -fsanitize=signed-integer-overflow,unsigned-integer-overflow -fsanitize-hw-support=2
	ARCH_SUFFIX = _x86
endif

# File handling
SOURCES = $(wildcard test-*.cpp)
TARGETS = $(patsubst %.cpp,%$(ARCH_SUFFIX),$(SOURCES))

.PHONY: all clean test

all: $(TARGETS)

%$(ARCH_SUFFIX): %.cpp
	$(CXX) $(CXXFLAGS) $< -o $@

clean:
	rm -f *_x86 *_riscv *.log

test: $(TARGETS)
	@echo "Testing for architecture: $(ARCH)"
	@for target in $(TARGETS); do \
		$(GEM5_BUILD)/gem5.fast $(GEM5_CONFIG) \
			--cmd=./$$target \
			--mem-size=8GB \
			--cpu-type=O3CPU \
			--caches \
			--l2cache \
			--l1d_size=32kB \
			--l1i_size=32kB \
			--l2_size=512kB > $$target.log 2>&1; \
		overflow_type=$$(grep -oP '[\w.]+\s+overflow' $$target.log | head -n1); \
		if [ -n "$$overflow_type" ]; then \
			echo "$$target: $$overflow_type detected"; \
		else \
			echo "$$target: No overflow detected"; \
		fi; \
	done

help:
	@echo "Usage:"
	@echo "  make ARCH=X86       # Build for X86 architecture (default)"
	@echo "  make ARCH=RISCV     # Build for RISC-V architecture"
	@echo "  make test ARCH=X86  # Run tests for X86"
	@echo "  make test ARCH=RISCV # Run tests for RISC-V"
	@echo "  make clean          # Remove binaries and logs"

# Validate architecture selection
ifneq ($(ARCH),X86)
ifneq ($(ARCH),RISCV)
$(error Invalid ARCH specified. Valid values: X86, RISCV)
endif
endif
