#===-- Makefile.common - Common make rules for LLVM -------*- makefile -*--====
#
# This file is included by all of the LLVM makefiles.  This file defines common
# rules to do things like compile a .cpp file or generate dependancy info.
# These are platform dependant, so this is the file used to specify these
# system dependant operations.
#
# The following functionality can be set by setting incoming variables.
# The variable $(LEVEL) *must* be set:
#
# 1. LEVEL - The level of the current subdirectory from the top of the 
#    MagicStats view.  This level should be expressed as a path, for 
#    example, ../.. for two levels deep.
#
# 2. DIRS - A list of subdirectories to be built.  Fake targets are set up
#    so that each of the targets "all", "install", and "clean" each build.
#    the subdirectories before the local target.
#
# 3. Source - If specified, this sets the source code filenames.  If this
#    is not set, it defaults to be all of the .cpp, .c, .y, and .l files 
#    in the current directory.  Also, if you want to build files in addition
#    to the local files, you can use the ExtraSource variable
#
#===-----------------------------------------------------------------------====

# Configuration file to set paths specific to local installation of LLVM
# 
include $(LEVEL)/Makefile.config

# These are options that can either be enabled here, or can be enabled on the
# make command line (ie, make ENABLE_PROFILING=1)
#

# When ENABLE_PROFILING is enabled, the llvm source base is built with profile
# information to allow gprof to be used to get execution frequencies.
#
#ENABLE_PROFILING = 1

# When ENABLE_PURIFY is enabled, the LLVM tools are linked with purify (which
# must be locally installed) to allow for some automated memory error debugging.
#
#ENABLE_PURIFY    = 1

# When ENABLE_OPTIMIZED is enabled, Release builds of all of the LLVM code are
# turned on, and Debug builds are turned off.
#
#ENABLE_OPTIMIZED = 1


# Figure out how to do platform specific stuff on this platform.  This is really
# gross and should be autoconfiscated (automake actually), but should hopefully
# work on Linux and solaris (SunOS).
#
UNAME := $(shell uname)
include $(LEVEL)/Makefile.$(UNAME)

ifdef SHARED_LIBRARY
# if SHARED_LIBRARY is specified, the default is to build the dynamic lib
dynamic ::
endif

# Default Rule:  Make sure it's also a :: rule
all ::

# Default for install is to at least build everything...
install ::


# Figure out which directory to build stuff into.  We want to build into the
# /shared directory by default because it is guaranteed to be local to the
# current machine.
#
ifeq ($(LLVM_OBJ_DIR),.)
BUILD_ROOT     = $(LLVM_OBJ_DIR)
BUILD_ROOT_TOP = $(LEVEL)
else

BUILD_ROOT := $(LLVM_OBJ_DIR)$(patsubst $(HOME)%,%,$(shell pwd))

# Calculate the BUILD_ROOT_TOP variable, which is the top of the llvm/ tree.
# Note that although this is just equal to $(BUILD_ROOT)/$(LEVEL), we cannot use
# this expression because some of the directories on the source tree may not
# exist in the build tree (for example the test/ heirarchy).  Thus we evaluate
# the directory to eliminate the ../'s
#
TOP_DIRECTORY := $(shell cd $(LEVEL); pwd)
BUILD_ROOT_TOP := $(LLVM_OBJ_DIR)$(patsubst $(HOME)%,%,$(TOP_DIRECTORY))
endif

#--------------------------------------------------------------------
# Variables derived from configuration options... 
#--------------------------------------------------------------------

#BinInstDir=/usr/local/bin
#LibInstDir=/usrl/local/lib/xxx
#DocInstDir=/usr/doc/xxx

BURG_OPTS = -I

PURIFY := $(PURIFY) -cache-dir="$(BUILD_ROOT_TOP)/../purifycache" -chain-length="30" -messages=all 

# Shorthand for commonly accessed directories
LIBDEBUG    := $(BUILD_ROOT_TOP)/lib/Debug
LIBRELEASE  := $(BUILD_ROOT_TOP)/lib/Release
TOOLDEBUG   := $(BUILD_ROOT_TOP)/tools/Debug
TOOLRELEASE := $(BUILD_ROOT_TOP)/tools/Release

# Verbosity levels
ifdef VERBOSE
VERB := 
else
VERB := @
endif

#---------------------------------------------------------
# Compilation options...
#---------------------------------------------------------

# Special tools used while building
RunBurg  := $(BURG) $(BURG_OPTS)

# Enable this for profiling support with 'gprof'
ifdef ENABLE_PROFILING
PROFILE = -pg
else
PROFILE =
endif

# Allow gnu extensions...
CPPFLAGS += -D_GNU_SOURCE

# -Wno-unused-parameter
CompileCommonOpts := $(PROFILE) -Wall -W  -Wwrite-strings -Wno-unused -I$(LEVEL)/include

# Compile a file, don't link...
Compile  := $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $(CompileCommonOpts)
CompileG := $(Compile) -g  -D_DEBUG
CompileO := $(Compile) -O3 -DNDEBUG -finline-functions -felide-constructors -fnonnull-objects -freg-struct-return -fshort-enums

# Link final executable

ifdef ENABLE_PURIFY # To enable purify, build with 'gmake ENABLE_PURIFY=1'
Link     := $(PURIFY) $(CXX) $(PROFILE) -static
else
Link     := $(CXX) $(PROFILE)
endif
LinkG    := $(Link) -g  -L $(LIBDEBUG)
LinkO    := $(Link) -O3 -L $(LIBRELEASE)

# Create one .o file from a bunch of .o files...
Relink = ld -r

# MakeSO - Create a .so file from a .o files...
MakeSO   := $(CXX) $(MakeSharedObjectOption) $(PROFILE)
MakeSOO  := $(MakeSO) -O3

# Create dependancy file from CPP file, send to stdout.
Depend   := $(CXX) -MM -I$(LEVEL)/include $(CPPFLAGS) 

# Archive a bunch of .o files into a .a file...
AR       = ar cq 

#----------------------------------------------------------

# Source includes all of the cpp files, and objects are derived from the
# source files...
# The local Makefile can list other Source files via ExtraSource = ...
# 
Source  := $(ExtraSource) $(wildcard *.cpp *.c *.y *.l)

Objs := $(sort $(patsubst Debug/%.o, %.o, $(addsuffix .o,$(basename $(Source)))))
ObjectsO = $(addprefix $(BUILD_ROOT)/Release/,$(Objs)))
ObjectsG = $(addprefix $(BUILD_ROOT)/Debug/,$(Objs))


#---------------------------------------------------------
# Handle the DIRS option
#---------------------------------------------------------

ifdef DIRS  # Only do this if we're using DIRS!

all     :: $(addsuffix /.makeall    , $(DIRS))
install :: $(addsuffix /.makeinstall, $(DIRS))
clean   :: $(addsuffix /.makeclean  , $(DIRS))

%/.makeall %/.makeclean %/.makeinstall:
	$(VERB) cd $(@D); $(MAKE) $(subst $(@D)/.make,,$@)
endif

#---------------------------------------------------------
# Handle the LIBRARYNAME option - used when building libs...
#---------------------------------------------------------
#
#  When libraries are built, they are allowed to optionally define the
#  DONT_BUILD_RELINKED make variable, which, when defined, prevents a .o file
#  from being built for the library. This .o files may then be linked to by a
#  tool if the tool does not need (or want) the semantics a .a file provides
#  (linking in only object files that are "needed").  If a library is never to
#  be used in this way, it is better to define DONT_BUILD_RELINKED, and define
#  BUILD_ARCHIVE instead.
#
#  Some libraries must be built as .a files (libscalar for example) because if
#  it's built as a .o file, then all of the constituent .o files in it will be
#  linked into tools (for example gccas) even if they only use one of the parts
#  of it.  For this reason, sometimes it's useful to use libraries as .a files.

ifdef LIBRARYNAME

LIBNAME_O    := $(LIBRELEASE)/lib$(LIBRARYNAME).so
LIBNAME_G    := $(LIBDEBUG)/lib$(LIBRARYNAME).so
LIBNAME_AO   := $(LIBRELEASE)/lib$(LIBRARYNAME).a
LIBNAME_AG   := $(LIBDEBUG)/lib$(LIBRARYNAME).a
LIBNAME_OBJO := $(LIBRELEASE)/$(LIBRARYNAME).o
LIBNAME_OBJG := $(LIBDEBUG)/$(LIBRARYNAME).o


ifndef ENABLE_OPTIMIZED
BUILD_LIBNAME_G := $(LIBNAME_G)
ifndef DONT_BUILD_RELINKED
BUILD_LIBNAME_OBJG := $(LIBNAME_OBJG)
endif
ifdef BUILD_ARCHIVE
BUILD_LIBNAME_AG := $(LIBNAME_AG)
endif
endif

# If optimized builds are enabled...
ifdef ENABLE_OPTIMIZED
BUILD_LIBNAME_O  := $(LIBNAME_O)
ifndef DONT_BUILD_RELINKED
BUILD_LIBNAME_OBJO := $(LIBNAME_OBJO)
endif
ifdef BUILD_ARCHIVE
BUILD_LIBNAME_AO := $(LIBNAME_AO)
endif
endif

all:: $(BUILD_LIBNAME_AG) $(BUILD_LIBNAME_OBJG)      # Debug
all:: $(BUILD_LIBNAME_AO) $(BUILD_LIBNAME_OBJO)      # Release
dynamic:: $(BUILD_LIBNAME_G) $(BUILD_LIBNAME_O)      # .so files

$(LIBNAME_O): $(ObjectsO) $(LibSubDirs) $(LIBRELEASE)/.dir
	@echo ======= Linking $(LIBRARYNAME) release library =======
	$(VERB) $(MakeSOO) -o $@ $(ObjectsO) $(LibSubDirs) $(LibLinkOpts)

$(LIBNAME_G): $(ObjectsG) $(LibSubDirs) $(LIBDEBUG)/.dir
	@echo ======= Linking $(LIBRARYNAME) debug library =======
	$(VERB) $(MakeSO) -g -o $@ $(ObjectsG) $(LibSubDirs) $(LibLinkOpts)

$(LIBNAME_AO): $(ObjectsO) $(LibSubDirs) $(LIBRELEASE)/.dir
	@echo ======= Linking $(LIBRARYNAME) release library =======
	@rm -f $@
	$(VERB) $(AR) $@ $(ObjectsO) $(LibSubDirs)

$(LIBNAME_AG): $(ObjectsG) $(LibSubDirs) $(LIBDEBUG)/.dir
	@echo ======= Linking $(LIBRARYNAME) debug library =======
	@rm -f $@
	$(VERB) $(AR) $@ $(ObjectsG) $(LibSubDirs)

$(LIBNAME_OBJO): $(ObjectsO) $(LibSubDirs) $(LIBRELEASE)/.dir
	@echo "Linking $@"
	$(VERB) $(Relink) -o $@ $(ObjectsO) $(LibSubDirs)

$(LIBNAME_OBJG): $(ObjectsG) $(LibSubDirs) $(LIBDEBUG)/.dir
	$(VERB) $(Relink) -o $@ $(ObjectsG) $(LibSubDirs)

endif

#------------------------------------------------------------------------
# Create a TAGS database for emacs
#------------------------------------------------------------------------

ifeq ($(LEVEL), .)
tags:
	etags -l c++ `find include lib tools -name '*.cpp' -o -name '*.h'`
all:: tags
endif

#------------------------------------------------------------------------
# Handle the TOOLNAME option - used when building tool executables...
#------------------------------------------------------------------------
#
# The TOOLNAME option should be used with a USEDLIBS variable that tells the
# libraries (and the order of the libs) that should be linked to the
# tool. USEDLIBS should contain a list of library names (some with .a extension)
# that are automatically linked in as .o files unless the .a suffix is added.
#
ifdef TOOLNAME

# TOOLEXENAME* - These compute the output filenames to generate...
TOOLEXENAME_G := $(BUILD_ROOT_TOP)/tools/Debug/$(TOOLNAME)
TOOLEXENAME_O := $(BUILD_ROOT_TOP)/tools/Release/$(TOOLNAME)
TOOLEXENAMES  := $(TOOLEXENAME_G)
ifdef ENABLE_OPTIMIZED
TOOLEXENAMES += $(TOOLEXENAME_O)
endif

# USED_LIBS_OPTIONS - Compute the options line that add -llib1 -llib2, etc.
USED_LIBS_OPTIONS   := $(patsubst %.a.o, -l%, $(addsuffix .o, $(USEDLIBS)))
USED_LIBS_OPTIONS_G := $(patsubst %.o, $(LIBDEBUG)/%.o,  $(USED_LIBS_OPTIONS))
USED_LIBS_OPTIONS_O := $(patsubst %.o, $(LIBRELEASE)/%.o,$(USED_LIBS_OPTIONS))


# USED_LIB_PATHS - Compute the path of the libraries used so that tools are
# rebuilt if libraries change.  This has to make sure to handle .a/.so and .o
# files seperately.
#
STATICUSEDLIBS   := $(patsubst %.a.o, lib%.a, $(addsuffix .o, $(USEDLIBS)))
USED_LIB_PATHS_G := $(addprefix $(LIBDEBUG)/, $(STATICUSEDLIBS))
USED_LIB_PATHS_O := $(addprefix $(LIBRELEASE)/, $(STATICUSEDLIBS))

all::   $(TOOLEXENAMES)
clean::
	$(VERB) rm -f $(TOOLEXENAMES)

$(TOOLEXENAME_G): $(ObjectsG) $(USED_LIB_PATHS_G) $(BUILD_ROOT_TOP)/tools/Debug/.dir
	@echo ======= Linking $(TOOLNAME) debug executable =======
	$(VERB) $(LinkG) -o $@ $(ObjectsG) $(USED_LIBS_OPTIONS_G) $(TOOLLINKOPTS)

$(TOOLEXENAME_O): $(ObjectsO) $(USED_LIB_PATHS_O) $(BUILD_ROOT_TOP)/tools/Release/.dir
	@echo ======= Linking $(TOOLNAME) release executable =======
	$(VERB) $(LinkO) -o $@ $(ObjectsG) $(USED_LIBS_OPTIONS_O) $(TOOLLINKOPTS)

endif



#---------------------------------------------------------
.PRECIOUS: $(BUILD_ROOT)/Depend/.dir
.PRECIOUS: $(BUILD_ROOT)/Debug/.dir $(BUILD_ROOT)/Release/.dir

# Create dependencies for the *.cpp files...
$(BUILD_ROOT)/Depend/%.d: %.cpp $(BUILD_ROOT)/Depend/.dir
	$(VERB) $(Depend) $< | sed 's|$*\.o *|$(BUILD_ROOT)/Release/& $(BUILD_ROOT)/Debug/& $(BUILD_ROOT)/Depend/$(@F)|g' > $@

# Create dependencies for the *.c files...
$(BUILD_ROOT)/Depend/%.d: %.c $(BUILD_ROOT)/Depend/.dir
	$(VERB) $(Depend) $< | sed 's|$*\.o *|Release/& Debug/& Depend/$(@F)|g' > $@

# Create .o files in the ObjectFiles directory from the .cpp and .c files...
$(BUILD_ROOT)/Release/%.o: %.cpp $(BUILD_ROOT)/Release/.dir
	@echo "Compiling $<"
	$(VERB) $(CompileO) $< -o $@

#Release/%.o: %.c Release/.dir Depend/.dir
#	$(CompileOC) $< -o $@

$(BUILD_ROOT)/Debug/%.o: %.cpp $(BUILD_ROOT)/Debug/.dir
	@echo "Compiling $<"
	$(VERB) $(CompileG) $< -o $@

#Debug/%.o: %.c Debug/.dir 
#	$(CompileGC) $< -o $@

# Create a .cpp source file from a flex input file... this uses sed to cut down
# on the warnings emited by GCC...
%.cpp: %.l
	flex -t $< | sed '/^find_rule/d' | sed 's/void yyunput/inline void yyunput/' | sed 's/void \*yy_flex_realloc/inline void *yy_flex_realloc/' > $@

# Rule for building the bison parsers...

%.cpp %.h : %.y
	$(VERB) bison -v -d -p $(<:%Parser.y=%) $(basename $@).y
	$(VERB) mv -f $(basename $@).tab.c $(basename $@).cpp
	$(VERB) mv -f $(basename $@).tab.h $(basename $@).h

# To create the directories...
%/.dir:
	$(VERB) mkdir -p $(@D)
	@date > $@

# Clean nukes the tree
clean::
	$(VERB) rm -rf $(BUILD_ROOT)/Debug $(BUILD_ROOT)/Release $(BUILD_ROOT)/Depend
	$(VERB) rm -f core *.o *.d *.so *~ *.flc

# If dependancies were generated for the file that included this file,
# include the dependancies now...
#
SourceDepend := $(addsuffix .d,$(addprefix $(BUILD_ROOT)/Depend/,$(basename $(filter-out Debug/%, $(Source)))))
ifneq ($(SourceDepend),)
include $(SourceDepend)
endif
