# =============================================================================
# Makefile for CMU 15-213 Lecture 2 demos (bits, bytes and integers)
# =============================================================================
#
#   make          build every demo
#   make run      build and run them all
#   make asm      write the assembly of demo 05's times24/div8/udiv8 for this
#                 machine and (on Apple Silicon) for x86-64, into build/
#   make ubsan    build demo 01 with UndefinedBehaviorSanitizer and run it:
#                 the oversized shifts are then reported at run time
#   make clean    remove build products
#
# [C tip] $@ = the target name, $< = the first prerequisite.
# -----------------------------------------------------------------------------

CC      ?= cc
CFLAGS  := -std=c11 -Wall -Wextra -O2 -g

BINS := 01_bit_level_ops 02_encodings 03_casting 04_extend_truncate \
        05_arithmetic 06_byte_order 07_float_fields

.PHONY: all run asm ubsan clean
all: $(BINS)

# Every demo is one .c file that includes bits.h.
%: %.c bits.h
	$(CC) $(CFLAGS) -o $@ $<

run: all
	@for b in $(BINS); do echo; ./$$b; done

# Asm flags that give textbook-looking output: no unwind-table directives,
# no frame pointer, no stack protector.
ASMFLAGS := -std=c11 -O2 -S -fno-asynchronous-unwind-tables -fomit-frame-pointer \
            -fno-stack-protector

asm: 05_arithmetic.c
	@mkdir -p build
	$(CC) $(ASMFLAGS) -o build/05_arithmetic.native.s $<
	@$(CC) $(ASMFLAGS) -arch x86_64 -o build/05_arithmetic.x86_64.s $< 2>/dev/null \
	  && echo 'wrote build/05_arithmetic.x86_64.s' \
	  || echo '(no x86-64 cross compiler on this toolchain; native asm only)'

ubsan: 01_bit_level_ops.c bits.h
	$(CC) -std=c11 -O1 -g -fsanitize=undefined -o 01_bit_level_ops.ubsan $<
	./01_bit_level_ops.ubsan 2>&1 | grep -E 'runtime error|PART E' || true

clean:
	rm -f $(BINS) 01_bit_level_ops.ubsan
	rm -rf build *.dSYM
