include common.mk

PHONY += directories
MKDIR_P = mkdir -p
TSO_DIR = build_tso
SC_DIR = build_sc

CPP_SOURCES := mymemory.cc context.cc snapshot.cc snapshot-interface.cc libinterface.cc execpoint.cc main.cc eprecord.cc epvalue.cc mcexecution.cc model.cc libthreads.cc mcschedule.cc common.cc threads.cc planner.cc cgoal.cc change.cc constgen.cc constraint.cc branchrecord.cc valuerecord.cc storeloadset.cc functionrecord.cc loadrf.cc schedulebuilder.cc equalsrecord.cc inc_solver.cc
C_SOURCES := malloc.c

TSO_OBJECTS := $(CPP_SOURCES:%.cc=$(TSO_DIR)/%.o) $(C_SOURCES:%.c=$(TSO_DIR)/%.o)
SC_OBJECTS := $(CPP_SOURCES:%.cc=$(SC_DIR)/%.o) $(C_SOURCES:%.c=$(SC_DIR)/%.o)

CPPFLAGS += -Iinclude -I.
LDFLAGS := -ldl -lrt -rdynamic
SHARED := -shared

# Mac OSX options
ifeq ($(UNAME), Darwin)
LDFLAGS := -ldl
SHARED := -Wl,-undefined,dynamic_lookup -dynamiclib
endif

TESTS_DIR := test

MARKDOWN := doc/Markdown/Markdown.pl

all: directories $(TSO_LIB_SO) $(SC_LIB_SO)

directories: ${TSO_DIR} ${SC_DIR}

${TSO_DIR}:
	${MKDIR_P} ${TSO_DIR}

${SC_DIR}:
	${MKDIR_P} ${SC_DIR}

debug: CPPFLAGS += -DCONFIG_DEBUG
debug: all

PHONY += docs
docs: *.c *.cc *.h
	doxygen

$(TSO_LIB_SO): $(TSO_OBJECTS)
	$(CXX) -g $(SHARED) -o $(TSO_LIB_SO) $+ $(LDFLAGS)

$(SC_LIB_SO): $(SC_OBJECTS)
	$(CXX) -g $(SHARED) -o $(SC_LIB_SO) $+ $(LDFLAGS)

${TSO_DIR}/%.o: %.c
	$(CC) -fPIC -c $< -o $@ -DTSO -DMSPACES -DONLY_MSPACES -DHAVE_MMAP=0 $(CPPFLAGS) -Wno-unused-variable

${TSO_DIR}/%.o: %.cc
	$(CXX) -MMD -DTSO -MF $@.d -o $@ -fPIC -c $< $(CPPFLAGS)

${SC_DIR}/%.o: %.c
	$(CC) -fPIC -c $< -o $@ -DMSPACES -DONLY_MSPACES -DHAVE_MMAP=0 $(CPPFLAGS) -Wno-unused-variable

${SC_DIR}/%.o: %.cc
	$(CXX) -MMD -MF $@.d -fPIC -o $@ -c $< $(CPPFLAGS)

%.pdf: %.dot
	dot -Tpdf $< -o $@

-include $(TSO_OBJECTS:%=$TSO_DIR/.%.d)
-include $(SC_OBJECTS:%=$SC_DIR/.%.d)

PHONY += clean
clean:
	rm -f *.o *.so *.pdf *.dot dimacs.cnf dimacs.out
	rm -rf $(TSO_DIR) $(SC_DIR)
	$(MAKE) -C $(TESTS_DIR) clean

PHONY += mrclean
mrclean: clean
	rm -rf docs

PHONY += tags
tags:
	ctags -R

PHONE += tests
tests: $(LIB_SO)
	$(MAKE) -C $(TESTS_DIR)

PHONY += pdfs
pdfs: $(patsubst %.dot,%.pdf,$(wildcard *.dot))

tabbing:
	uncrustify -c C.cfg --no-backup *.cc
	uncrustify -c C.cfg --no-backup *.h

.PHONY: $(PHONY)

# A 1-inch margin PDF generated by 'pandoc'
%.pdf: %.md
	pandoc -o $@ $< -V header-includes='\usepackage[margin=1in]{geometry}'