#===-- Makefile.rules - Common make rules for LLVM ---------*- Makefile -*--===#
#
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
#
# This file is included by all of the LLVM makefiles.  For details on how to use
# it properly, please see the document MakefileGuide.html in the docs directory.
#
#===-----------------------------------------------------------------------====#

################################################################################
# TARGETS: Define standard targets that can be invoked
################################################################################

#--------------------------------------------------------------------
# Define the various target sets
#--------------------------------------------------------------------
RecursiveTargets := all clean clean-all install uninstall install-bytecode \
                    unitcheck
LocalTargets     := all-local clean-local clean-all-local check-local \
                    install-local printvars uninstall-local \
		    install-bytecode-local
TopLevelTargets  := check dist dist-check dist-clean dist-gzip dist-bzip2 \
                    dist-zip unittests
UserTargets      := $(RecursiveTargets) $(LocalTargets) $(TopLevelTargets)
InternalTargets  := preconditions distdir dist-hook

################################################################################
# INITIALIZATION: Basic things the makefile needs
################################################################################

#--------------------------------------------------------------------
# Set the VPATH so that we can find source files.
#--------------------------------------------------------------------
VPATH=$(PROJ_SRC_DIR)

#--------------------------------------------------------------------
# Reset the list of suffixes we know how to build.
#--------------------------------------------------------------------
.SUFFIXES:
.SUFFIXES: .c .cpp .cc .h .hpp .o .a .td .ps .dot .m .mm
.SUFFIXES: $(SHLIBEXT) $(SUFFIXES)

#--------------------------------------------------------------------
# Mark all of these targets as phony to avoid implicit rule search
#--------------------------------------------------------------------
.PHONY: $(UserTargets) $(InternalTargets)

#--------------------------------------------------------------------
# Make sure all the user-target rules are double colon rules and
# they are defined first.
#--------------------------------------------------------------------

$(UserTargets)::

#------------------------------------------------------------------------
# LLVMBuild Integration
#------------------------------------------------------------------------
#
# We use llvm-build to generate all the data required by the Makefile based
# build system in one swoop:
#
#  - We generate a file (a Makefile fragment) in the object root which contains
#    all the definitions that are required by Makefiles across the entire
#    project.
#
#  - We generate the library table used by llvm-config.
#
#  - We generate the dependencies for the Makefile fragment, so that we will
#    automatically reconfigure outselves.

# The path to the llvm-build tool itself.
LLVMBuildTool	:= $(PROJ_SRC_ROOT)/utils/llvm-build/llvm-build

# The files we are going to generate using llvm-build.
LLVMBuildMakeFrag := $(PROJ_OBJ_ROOT)/Makefile.llvmbuild
LLVMBuildCMakeFrag := $(PROJ_OBJ_ROOT)/LLVMBuild.cmake
LLVMBuildCMakeExportsFrag := $(PROJ_OBJ_ROOT)/cmake/modules/LLVMBuildExports.cmake
LLVMBuildMakeFrags := \
	$(LLVMBuildMakeFrag) \
	$(LLVMBuildCMakeFrag) \
	$(LLVMBuildCMakeExportsFrag)
LLVMConfigLibraryDependenciesInc := \
	$(PROJ_OBJ_ROOT)/tools/llvm-config/LibraryDependencies.inc

# This is for temporary backwards compatibility.
ifndef TARGET_NATIVE_ARCH
TARGET_NATIVE_ARCH := $(ARCH)
endif

# The rule to create the LLVMBuild Makefile fragment as well as the llvm-config
# library table.
#
# Note that this target gets its real dependencies generated for us by
# llvm-build.
#
# We include a dependency on this Makefile to ensure that changes to the
# generation command get picked up.
$(LLVMBuildMakeFrags): $(PROJ_SRC_ROOT)/Makefile.rules \
		       $(PROJ_OBJ_ROOT)/Makefile.config
	$(Echo) Constructing LLVMBuild project information.
	$(Verb)$(PYTHON) $(LLVMBuildTool) \
	  --native-target "$(TARGET_NATIVE_ARCH)" \
	  --enable-targets "$(TARGETS_TO_BUILD)" \
	  --enable-optional-components "$(OPTIONAL_COMPONENTS)" \
	  --write-library-table $(LLVMConfigLibraryDependenciesInc) \
	  --write-make-fragment $(LLVMBuildMakeFrag) \
	  --write-cmake-fragment $(LLVMBuildCMakeFrag) \
	  --write-cmake-exports-fragment $(LLVMBuildCMakeExportsFrag)

# For completeness, let Make know how the extra files are generated.
$(LLVMConfigLibraryDependenciesInc): $(LLVMBuildMakeFrags)

# Include the generated Makefile fragment.
#
# We currently only include the dependencies for the fragment itself if we are
# at the top-level. Otherwise, recursive invocations would ends up doing
# substantially more redundant stat'ing.
#
# This means that we won't properly regenerate things for developers used to
# building from a subdirectory, but that is always somewhat unreliable.
ifeq ($(LEVEL),.)
LLVMBUILD_INCLUDE_DEPENDENCIES := 1

# Clean the generated makefile fragment at the top-level.
clean-local::
	-$(Verb) $(RM) -f $(LLVMBuildMakeFrags)
endif
-include $(LLVMBuildMakeFrag)

################################################################################
# PRECONDITIONS: that which must be built/checked first
################################################################################

SrcMakefiles       := $(filter %Makefile %Makefile.tests,\
                      $(wildcard $(PROJ_SRC_DIR)/Makefile*))
ObjMakefiles       := $(subst $(PROJ_SRC_DIR),$(PROJ_OBJ_DIR),$(SrcMakefiles))
ConfigureScript    := $(PROJ_SRC_ROOT)/configure
ConfigStatusScript := $(PROJ_OBJ_ROOT)/config.status
MakefileConfigIn   := $(strip $(wildcard $(PROJ_SRC_ROOT)/Makefile.config.in))
MakefileCommonIn   := $(strip $(wildcard $(PROJ_SRC_ROOT)/Makefile.common.in))
MakefileConfig     := $(PROJ_OBJ_ROOT)/Makefile.config
MakefileCommon     := $(PROJ_OBJ_ROOT)/Makefile.common
PreConditions      := $(ConfigStatusScript) $(ObjMakefiles)
ifneq ($(MakefileCommonIn),)
PreConditions      += $(MakefileCommon)
endif

ifneq ($(MakefileConfigIn),)
PreConditions      += $(MakefileConfig)
endif

preconditions: $(PreConditions)

#------------------------------------------------------------------------
# Make sure the BUILT_SOURCES are built first
#------------------------------------------------------------------------
$(filter-out clean clean-local,$(UserTargets)):: $(BUILT_SOURCES)

clean-all-local::
ifneq ($(strip $(BUILT_SOURCES)),)
	-$(Verb) $(RM) -f $(BUILT_SOURCES)
endif

ifneq ($(PROJ_OBJ_ROOT),$(PROJ_SRC_ROOT))
spotless:
	$(Verb) if test -x config.status ; then \
	  $(EchoCmd) Wiping out $(PROJ_OBJ_ROOT) ; \
	  $(MKDIR) .spotless.save ; \
	  $(MV) config.status .spotless.save ; \
	  $(MV) mklib  .spotless.save ; \
	  $(MV) projects  .spotless.save ; \
	  $(RM) -rf * ; \
	  $(MV) .spotless.save/config.status . ; \
	  $(MV) .spotless.save/mklib . ; \
	  $(MV) .spotless.save/projects . ; \
	  $(RM) -rf .spotless.save ; \
	  $(EchoCmd) Rebuilding configuration of $(PROJ_OBJ_ROOT) ; \
	  $(ConfigStatusScript) --recheck $(ConfigureScriptFLAGS) && \
	  $(ConfigStatusScript) ; \
	else \
	  $(EchoCmd) "make spotless" can only be run from $(PROJ_OBJ_ROOT); \
	fi
else
spotless:
	$(EchoCmd) "spotless target not supported for objdir == srcdir"
endif

$(BUILT_SOURCES) : $(ObjMakefiles)

#------------------------------------------------------------------------
# Make sure we're not using a stale configuration
#------------------------------------------------------------------------
reconfigure:
	$(Echo) Reconfiguring $(PROJ_OBJ_ROOT)
	$(Verb) cd $(PROJ_OBJ_ROOT) && \
	  $(ConfigStatusScript) --recheck $(ConfigureScriptFLAGS) && \
	  $(ConfigStatusScript)

.PRECIOUS: $(ConfigStatusScript)
$(ConfigStatusScript): $(ConfigureScript)
	$(Echo) Reconfiguring with $<
	$(Verb) cd $(PROJ_OBJ_ROOT) && \
	  $(ConfigStatusScript) --recheck $(ConfigureScriptFLAGS) && \
	  $(ConfigStatusScript)

#------------------------------------------------------------------------
# Make sure the configuration makefile is up to date
#------------------------------------------------------------------------
ifneq ($(MakefileConfigIn),)
$(MakefileConfig): $(MakefileConfigIn) $(ConfigStatusScript)
	$(Echo) Regenerating $@
	$(Verb) cd $(PROJ_OBJ_ROOT) ; $(ConfigStatusScript) Makefile.config
endif

ifneq ($(MakefileCommonIn),)
$(MakefileCommon): $(MakefileCommonIn) $(ConfigStatusScript)
	$(Echo) Regenerating $@
	$(Verb) cd $(PROJ_OBJ_ROOT) ; $(ConfigStatusScript) Makefile.common
endif

#------------------------------------------------------------------------
# If the Makefile in the source tree has been updated, copy it over into the
# build tree. But, only do this if the source and object makefiles differ
#------------------------------------------------------------------------
ifndef PROJ_MAKEFILE
PROJ_MAKEFILE := $(PROJ_SRC_DIR)/Makefile
endif

ifneq ($(PROJ_OBJ_DIR),$(PROJ_SRC_DIR))

Makefile: $(PROJ_MAKEFILE) $(ExtraMakefiles)
	$(Echo) "Updating Makefile"
	$(Verb) $(MKDIR) $(@D)
	$(Verb) $(CP) -f $< $@

# Copy the Makefile.* files unless we're in the root directory which avoids
# the copying of Makefile.config.in or other things that should be explicitly
# taken care of.
$(PROJ_OBJ_DIR)/Makefile% : $(PROJ_MAKEFILE)%
	@case '$?' in \
          *Makefile.rules) ;; \
          *.in) ;; \
          *) $(EchoCmd) "Updating $(@F)" ; \
	     $(MKDIR) $(@D) ; \
	     $(CP) -f $< $@ ;; \
	esac

endif

#------------------------------------------------------------------------
# Set up the basic dependencies
#------------------------------------------------------------------------
$(UserTargets):: $(PreConditions)

all:: all-local
clean:: clean-local
clean-all:: clean-local clean-all-local
install:: install-local
uninstall:: uninstall-local
install-local:: all-local
install-bytecode:: install-bytecode-local

###############################################################################
# VARIABLES: Set up various variables based on configuration data
###############################################################################

# Variable for if this make is for a "cleaning" target
ifneq ($(strip $(filter clean clean-local dist-clean,$(MAKECMDGOALS))),)
  IS_CLEANING_TARGET=1
endif

#--------------------------------------------------------------------
# Variables derived from configuration we are building
#--------------------------------------------------------------------

CPP.Defines :=
ifeq ($(ENABLE_OPTIMIZED),1)
  BuildMode := Release
  # Don't use -fomit-frame-pointer on Darwin or FreeBSD.
  ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin Darwin DragonFly FreeBSD GNU/kFreeBSD))
    OmitFramePointer := -fomit-frame-pointer
  endif

  CXX.Flags += $(OPTIMIZE_OPTION) $(OmitFramePointer)
  C.Flags   += $(OPTIMIZE_OPTION) $(OmitFramePointer)
  LD.Flags  += $(OPTIMIZE_OPTION)
  ifdef DEBUG_SYMBOLS
    BuildMode := $(BuildMode)+Debug
    CXX.Flags += -g
    C.Flags   += -g
    KEEP_SYMBOLS := 1
  endif
else
  ifdef NO_DEBUG_SYMBOLS
    BuildMode := Unoptimized
    CXX.Flags +=
    C.Flags   +=
    KEEP_SYMBOLS := 1
  else
    BuildMode := Debug
    ifeq ($(ENABLE_SPLIT_DWARF), 1)
    CXX.Flags += -gsplit-dwarf
    C.Flags   += -gsplit-dwarf
    else
    CXX.Flags += -g
    C.Flags   += -g
    endif
    KEEP_SYMBOLS := 1
  endif
endif

ifeq ($(ENABLE_LIBCPP),1)
  CXX.Flags +=  -stdlib=libc++
  LD.Flags +=  -stdlib=libc++
endif

ifeq ($(ENABLE_CXX1Y),1)
  CXX.Flags += -std=c++1y
else
  ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
    # MinGW and Cygwin are a bit stricter and lack things like
    # 'strdup', 'stricmp', etc in c++11 mode.
    CXX.Flags += -std=gnu++11
 else
    CXX.Flags += -std=c++11
 endif
endif

ifeq ($(ENABLE_WERROR),1)
  CXX.Flags += -Werror
  C.Flags += -Werror
endif

ifeq ($(ENABLE_PROFILING),1)
  BuildMode := $(BuildMode)+Profile
  CXX.Flags := $(filter-out -fomit-frame-pointer,$(CXX.Flags)) -pg -g
  C.Flags   := $(filter-out -fomit-frame-pointer,$(C.Flags)) -pg -g
  LD.Flags  := $(filter-out -fomit-frame-pointer,$(LD.Flags)) -pg
  KEEP_SYMBOLS := 1
endif

ifeq ($(ENABLE_VISIBILITY_INLINES_HIDDEN),1)
    CXX.Flags += -fvisibility-inlines-hidden
endif

ifdef ENABLE_EXPENSIVE_CHECKS
  # GNU libstdc++ uses RTTI if you define _GLIBCXX_DEBUG, which we did above.
  # See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40160
  REQUIRES_RTTI := 1
endif

# IF REQUIRES_EH=1 is specified then don't disable exceptions
ifndef REQUIRES_EH
  CXX.Flags += -fno-exceptions
else
  # If the library requires EH, it also requires RTTI.
  REQUIRES_RTTI := 1
endif

ifdef REQUIRES_FRAME_POINTER
  CXX.Flags := $(filter-out -fomit-frame-pointer,$(CXX.Flags))
  C.Flags   := $(filter-out -fomit-frame-pointer,$(C.Flags))
  LD.Flags  := $(filter-out -fomit-frame-pointer,$(LD.Flags))
endif

# If REQUIRES_RTTI=1 is specified then don't disable run-time type id.
ifneq ($(REQUIRES_RTTI), 1)
  CXX.Flags += -fno-rtti
endif

ifeq ($(ENABLE_COVERAGE),1)
  BuildMode := $(BuildMode)+Coverage
  CXX.Flags += -ftest-coverage -fprofile-arcs
  C.Flags   += -ftest-coverage -fprofile-arcs
  LD.Flags   += -ftest-coverage -fprofile-arcs
endif

# If DISABLE_ASSERTIONS=1 is specified (make command line or configured),
# then disable assertions by defining the appropriate preprocessor symbols.
ifeq ($(DISABLE_ASSERTIONS),1)
  CPP.Defines += -DNDEBUG
else
  BuildMode := $(BuildMode)+Asserts
  CPP.Defines += -D_DEBUG
endif

# If ENABLE_EXPENSIVE_CHECKS=1 is specified (make command line or
# configured), then enable expensive checks by defining the
# appropriate preprocessor symbols.
ifeq ($(ENABLE_EXPENSIVE_CHECKS),1)
  BuildMode := $(BuildMode)+Checks
  CPP.Defines += -D_GLIBCXX_DEBUG -DXDEBUG
endif

# LOADABLE_MODULE implies several other things so we force them to be
# defined/on.
ifdef LOADABLE_MODULE
  SHARED_LIBRARY := 1
  LINK_LIBS_IN_SHARED := 1
endif

ifdef SHARED_LIBRARY
  ENABLE_PIC := 1
  PIC_FLAG = "(PIC)"
endif

ifeq ($(ENABLE_PIC),1)
  ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
    # Nothing. Win32 defaults to PIC and warns when given -fPIC
  else
    ifeq ($(HOST_OS),Darwin)
      # Common symbols not allowed in dylib files
      CXX.Flags += -fno-common
      C.Flags   += -fno-common
    else
      # Linux and others; pass -fPIC
      CXX.Flags += -fPIC
      C.Flags   += -fPIC
    endif
  endif
else
  ifeq ($(HOST_OS),Darwin)
      CXX.Flags += -mdynamic-no-pic
      C.Flags   += -mdynamic-no-pic
  endif
endif

# Support makefile variable to disable any kind of timestamp/non-deterministic
# info from being used in the build.
ifeq ($(ENABLE_TIMESTAMPS),1)
  DOTDIR_TIMESTAMP_COMMAND := $(DATE)
else
  DOTDIR_TIMESTAMP_COMMAND := echo 'Created.'
endif

ifeq ($(HOST_OS),MingW)
  # Work around PR4957
  CPP.Defines += -D__NO_CTYPE_INLINE
  ifeq ($(LLVM_CROSS_COMPILING),1)
    # Work around http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=525016
    ifdef TOOLNAME
      LD.Flags += -Wl,--allow-multiple-definition
    endif
  endif
endif

CPP.BaseFlags += $(CPP.Defines)
AR.Flags      := cru

# Make Floating point IEEE compliant on Alpha.
ifeq ($(ARCH),Alpha)
  CXX.Flags     += -mieee
  CPP.BaseFlags += -mieee
ifeq ($(ENABLE_PIC),0)
  CXX.Flags     += -fPIC
  CPP.BaseFlags += -fPIC
endif

  LD.Flags += -Wl,--no-relax
endif

# GNU ld/PECOFF accepts but ignores them below;
#   --version-script
#   --export-dynamic
#   --rpath
# FIXME: autoconf should be aware of them.
ifneq (,$(filter $(HOST_OS),Cygwin MingW))
  HAVE_LINK_VERSION_SCRIPT := 0
  RPATH :=
  RDYNAMIC := -Wl,--export-all-symbols
endif

#--------------------------------------------------------------------
# Directory locations
#--------------------------------------------------------------------
TargetMode :=
ifeq ($(LLVM_CROSS_COMPILING),1)
  BuildLLVMToolDir := $(LLVM_OBJ_ROOT)/BuildTools/$(BuildMode)/bin
endif

ObjRootDir  := $(PROJ_OBJ_DIR)/$(BuildMode)
ObjDir      := $(ObjRootDir)
LibDir      := $(PROJ_OBJ_ROOT)/$(BuildMode)/lib
LibexecDir  := $(PROJ_OBJ_ROOT)/$(BuildMode)/libexec
ShareDir    := $(PROJ_OBJ_ROOT)/$(BuildMode)/share
ToolDir     := $(PROJ_OBJ_ROOT)/$(BuildMode)/bin
ExmplDir    := $(PROJ_OBJ_ROOT)/$(BuildMode)/examples
LLVMLibDir  := $(LLVM_OBJ_ROOT)/$(BuildMode)/lib
LLVMToolDir := $(LLVM_OBJ_ROOT)/$(BuildMode)/bin
LLVMExmplDir:= $(LLVM_OBJ_ROOT)/$(BuildMode)/examples

#--------------------------------------------------------------------
# Locations of shared libraries
#--------------------------------------------------------------------

SharedPrefix     := lib
SharedLibDir     := $(LibDir)
LLVMSharedLibDir := $(LLVMLibDir)

# Win32.DLL prefers to be located on the "PATH" of binaries.
ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
  SharedLibDir     := $(ToolDir)
  LLVMSharedLibDir := $(LLVMToolDir)

  ifeq ($(HOST_OS),Cygwin)
    SharedPrefix  := cyg
  else
    SharedPrefix  :=
  endif
endif

#--------------------------------------------------------------------
# Full Paths To Compiled Tools and Utilities
#--------------------------------------------------------------------
EchoCmd  := $(ECHO) llvm[$(MAKELEVEL)]:
ifdef BUILD_DIRS_ONLY
EchoCmd  := $(EchoCmd) "(build tools)":
endif

Echo     := @$(EchoCmd)
ifndef LLVMAS
LLVMAS   := $(LLVMToolDir)/llvm-as$(EXEEXT)
endif
ifndef LLVM_TBLGEN
  ifeq ($(LLVM_CROSS_COMPILING),1)
    LLVM_TBLGEN   := $(BuildLLVMToolDir)/llvm-tblgen$(BUILD_EXEEXT)
  else
    LLVM_TBLGEN   := $(LLVMToolDir)/llvm-tblgen$(EXEEXT)
  endif
endif
ifeq ($(LLVM_CROSS_COMPILING),1)
  LLVM_CONFIG := $(BuildLLVMToolDir)/llvm-config$(BUILD_EXEEXT)
else
  LLVM_CONFIG := $(LLVMToolDir)/llvm-config$(EXEEXT)
endif
ifndef LLVMDIS
LLVMDIS  := $(LLVMToolDir)/llvm-dis$(EXEEXT)
endif
ifndef LLI
LLI      := $(LLVMToolDir)/lli$(EXEEXT)
endif
ifndef LLC
LLC      := $(LLVMToolDir)/llc$(EXEEXT)
endif
ifndef LOPT
LOPT     := $(LLVMToolDir)/opt$(EXEEXT)
endif
ifndef LBUGPOINT
LBUGPOINT := $(LLVMToolDir)/bugpoint$(EXEEXT)
endif
ifndef LLVMLINK
LLVMLINK      := $(LLVMToolDir)/llvm-link$(EXEEXT)
endif

#--------------------------------------------------------------------
# Adjust to user's request
#--------------------------------------------------------------------

ifeq ($(HOST_OS),Darwin)
 ifdef MACOSX_DEPLOYMENT_TARGET
  DARWIN_VERSION := $(MACOSX_DEPLOYMENT_TARGET)
 else
  DARWIN_VERSION := `sw_vers -productVersion`
 endif
  # Strip a number like 10.4.7 to 10.4
  DARWIN_VERSION := $(shell echo $(DARWIN_VERSION)| sed -E 's/(10.[0-9]+).*/\1/')
  # Get "4" out of 10.4 for later pieces in the makefile.
  DARWIN_MAJVERS := $(shell echo $(DARWIN_VERSION)| sed -E 's/10.([0-9]+).*/\1/')

  LoadableModuleOptions := -Wl,-flat_namespace -Wl,-undefined,suppress
  SharedLinkOptions := -dynamiclib
  ifdef DEPLOYMENT_TARGET
    SharedLinkOptions += $(DEPLOYMENT_TARGET)
  else
    ifneq ($(ARCH),ARM)
      SharedLinkOptions += -mmacosx-version-min=$(DARWIN_VERSION)
    endif
  endif
else
  SharedLinkOptions=-shared
endif

ifeq ($(TARGET_OS),Darwin)
  ifdef DEPLOYMENT_TARGET
    TargetCommonOpts += $(DEPLOYMENT_TARGET)
  else
    ifneq ($(ARCH),ARM)
      TargetCommonOpts += -mmacosx-version-min=$(DARWIN_VERSION)
    endif
  endif
endif

ifdef SHARED_LIBRARY
ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
ifneq ($(HOST_OS),Darwin)
  LD.Flags += $(RPATH) -Wl,'$$ORIGIN'
else
  LD.Flags += -Wl,-install_name  -Wl,"@rpath/lib$(LIBRARYNAME)$(SHLIBEXT)"
endif
endif
endif

ifdef TOOL_VERBOSE
  C.Flags += -v
  CXX.Flags += -v
  LD.Flags += -v
  VERBOSE := 1
endif

# Adjust settings for verbose mode
ifndef VERBOSE
  Verb := @
  AR.Flags += >/dev/null 2>/dev/null
  ConfigureScriptFLAGS += >$(PROJ_OBJ_DIR)/configure.out 2>&1
else
  ConfigureScriptFLAGS :=
endif

# By default, strip symbol information from executable
ifndef KEEP_SYMBOLS
  Strip := $(PLATFORMSTRIPOPTS)
  StripWarnMsg := "(without symbols)"
  Install.StripFlag += -s
endif

# By default, strip dead symbols at link time
ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
ifneq ($(HOST_OS),Darwin)
ifneq ($(HOST_ARCH),Mips)
  CXX.Flags += -ffunction-sections -fdata-sections
  ifeq ($(HOST_OS),SunOS)
      CXX.Flags += -falign-functions=8
  endif
endif
endif
endif
ifndef NO_DEAD_STRIP
  ifeq ($(HOST_OS),Darwin)
    LD.Flags += -Wl,-dead_strip
  else
    ifeq ($(HOST_OS),SunOS)
      LD.Flags += -Wl,-z -Wl,discard-unused=sections
    else
      ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
        LD.Flags += -Wl,--gc-sections
      endif
    endif
  endif
endif

# Adjust linker flags for building an executable
ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
  ifndef TOOL_NO_EXPORTS
    LD.Flags += $(RDYNAMIC)
  endif
  ifneq ($(HOST_OS), Darwin)
    ifdef TOOLNAME
      LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
    endif
  else
    ifneq ($(DARWIN_MAJVERS),4)
      LD.Flags += $(RPATH) -Wl,@executable_path/../lib
    endif
    ifeq ($(RC_XBS),YES)
      TempFile := $(shell mkdir -p ${OBJROOT}/dSYMs ; mktemp ${OBJROOT}/dSYMs/llvm-lto.XXXXXX)
      LD.Flags += -Wl,-object_path_lto -Wl,$(TempFile)
    endif
  endif
endif


#----------------------------------------------------------
# Options To Invoke Tools
#----------------------------------------------------------

ifdef EXTRA_LD_OPTIONS
LD.Flags += $(EXTRA_LD_OPTIONS)
endif

ifndef NO_PEDANTIC
CompileCommonOpts += -pedantic -Wno-long-long
endif
CompileCommonOpts += -Wall -W -Wno-unused-parameter -Wwrite-strings \
                     $(EXTRA_OPTIONS) $(COVERED_SWITCH_DEFAULT) \
                     $(NO_UNINITIALIZED) $(NO_MAYBE_UNINITIALIZED) \
                     $(MISSING_FIELD_INITIALIZERS) $(NO_COMMENT)
# Enable cast-qual for C++; the workaround is to use const_cast.
CXX.Flags += -Wcast-qual

ifeq ($(HOST_OS),HP-UX)
  CompileCommonOpts := -D_REENTRANT -D_HPUX_SOURCE
endif

# If we are building a universal binary on Mac OS X, pass extra options.  This
# is useful to people that want to link the LLVM libraries into their universal
# apps.
#
# The following can be optionally specified:
#   UNIVERSAL_SDK_PATH variable can be specified as a path to the SDK to use.
#      For Mac OS X 10.4 Intel machines, the traditional one is:
#      UNIVERSAL_SDK_PATH=/Developer/SDKs/MacOSX10.4u.sdk/
#   UNIVERSAL_ARCH can be optionally specified to be a list of architectures
#      to build for, e.g. UNIVERSAL_ARCH="i386 ppc ppc64".  This defaults to
#      i386/ppc only.
ifdef UNIVERSAL
  ifndef UNIVERSAL_ARCH
    UNIVERSAL_ARCH := i386 ppc
  endif
  UNIVERSAL_ARCH_OPTIONS := $(UNIVERSAL_ARCH:%=-arch %)
  TargetCommonOpts += $(UNIVERSAL_ARCH_OPTIONS)
  ifdef UNIVERSAL_SDK_PATH
    TargetCommonOpts += -isysroot $(UNIVERSAL_SDK_PATH)
  endif

  # Building universal cannot compute dependencies automatically.
  DISABLE_AUTO_DEPENDENCIES=1
else
  ifeq ($(TARGET_OS),Darwin)
    ifeq ($(ARCH),x86_64)
      TargetCommonOpts = -m64
    else
      ifeq ($(ARCH),x86)
        TargetCommonOpts = -m32
      endif
    endif
  endif
endif

ifeq ($(HOST_OS),SunOS)
CPP.BaseFlags += -include llvm/Support/Solaris.h
endif

# On Windows, SharedLibDir != LibDir. The order is important.
ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
  LD.Flags    += -L$(SharedLibDir) -L$(LibDir) -L$(LLVMToolDir) -L$(LLVMLibDir)
else
  LD.Flags    += -L$(LibDir) -L$(LLVMLibDir)
endif

CPP.BaseFlags += -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS
# All -I flags should go here, so that they don't confuse llvm-config.
CPP.Flags     += $(sort -I$(PROJ_OBJ_DIR) -I$(PROJ_SRC_DIR) \
	         $(patsubst %,-I%/include,\
	         $(PROJ_OBJ_ROOT) $(PROJ_SRC_ROOT) \
	         $(LLVM_OBJ_ROOT) $(LLVM_SRC_ROOT))) \
	         $(CPP.BaseFlags)

ifeq ($(INCLUDE_BUILD_DIR),1)
  CPP.Flags   += -I$(ObjDir)
endif

# SHOW_DIAGNOSTICS support.
ifeq ($(SHOW_DIAGNOSTICS),1)
  Compile.Wrapper := env CC_LOG_DIAGNOSTICS=1 \
	                  CC_LOG_DIAGNOSTICS_FILE="$(LLVM_OBJ_ROOT)/$(BuildMode)/diags"
else
  Compile.Wrapper :=
endif

Compile.C     = $(Compile.Wrapper) \
	          $(CC) $(CPP.Flags) $(C.Flags) $(CFLAGS) $(CPPFLAGS) \
                $(TargetCommonOpts) $(CompileCommonOpts) -c
Compile.CXX   = $(Compile.Wrapper) \
	          $(CXX) $(CPP.Flags) $(CXX.Flags) $(CXXFLAGS) $(CPPFLAGS) \
                $(TargetCommonOpts) $(CompileCommonOpts) -c
Preprocess.CXX= $(Compile.Wrapper) \
	          $(CXX) $(CPP.Flags) $(TargetCommonOpts) $(CPPFLAGS) \
                $(CompileCommonOpts) $(CXX.Flags) -E
Link          = $(Compile.Wrapper) \
	          $(CXX) $(CXXFLAGS) $(LD.Flags) $(LDFLAGS) \
                $(TargetCommonOpts) $(Strip)

Preprocess.C  = $(CC) $(CPP.Flags) $(C.Flags) $(CPPFLAGS) \
                $(TargetCommonOpts) $(CompileCommonOpts) -E

ProgInstall   = $(INSTALL) $(Install.StripFlag) -m 0755
ScriptInstall = $(INSTALL) -m 0755
DataInstall   = $(INSTALL) -m 0644

# When compiling under Mingw/Cygwin, the tblgen tool expects Windows
# paths. In this case, the SYSPATH function (defined in
# Makefile.config) transforms Unix paths into Windows paths.
TableGen.Flags= -I $(call SYSPATH, $(PROJ_SRC_DIR)) \
                -I $(call SYSPATH, $(LLVM_SRC_ROOT)/include) \
                -I $(call SYSPATH, $(PROJ_SRC_ROOT)/include) \
                -I $(call SYSPATH, $(PROJ_SRC_ROOT)/lib/Target)
LLVMTableGen  = $(LLVM_TBLGEN) $(TableGen.Flags)

Archive       = $(AR) $(AR.Flags)
ifdef RANLIB
Ranlib        = $(RANLIB)
else
Ranlib        = ranlib
endif

AliasTool     = ln -sf

#----------------------------------------------------------
# Get the list of source files and compute object file
# names from them.
#----------------------------------------------------------

ifndef SOURCES
  Sources := $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp \
             $(PROJ_SRC_DIR)/*.cc $(PROJ_SRC_DIR)/*.c))
else
  Sources := $(SOURCES)
endif

ifdef BUILT_SOURCES
Sources += $(filter %.cpp %.c %.cc,$(BUILT_SOURCES))
endif

BaseNameSources := $(sort $(basename $(Sources)))
SourceDirs := $(sort $(dir $(Sources)))

ObjectsO  := $(BaseNameSources:%=$(ObjDir)/%.o)
ObjectDirs := $(SourceDirs:%=$(ObjDir)/%)

#----------------------------------------------------------
# For Mingw MSYS bash and Python/w32:
#
# $(ECHOPATH) prints DOSish pathstring.
#   ex) $(ECHOPATH) /include/sys/types.h
#   --> C:/mingw/include/sys/types.h
# built-in "echo" does not transform path to DOSish path.
#
# FIXME: It would not be needed when MSYS's python
# were provided.
#----------------------------------------------------------

ifeq (-mingw32,$(findstring -mingw32,$(BUILD_TRIPLE)))
  ECHOPATH := $(Verb)$(PYTHON) -u -c "import sys;print ' '.join(sys.argv[1:])"
else
  ECHOPATH := $(Verb)$(ECHO)
endif

###############################################################################
# DIRECTORIES: Handle recursive descent of directory structure
###############################################################################

#---------------------------------------------------------
# Provide rules to make install dirs. This must be early
# in the file so they get built before dependencies
#---------------------------------------------------------

$(DESTDIR)$(PROJ_bindir) $(DESTDIR)$(PROJ_libdir) $(DESTDIR)$(PROJ_includedir) $(DESTDIR)$(PROJ_etcdir)::
	$(Verb) $(MKDIR) $@

# To create other directories, as needed, and timestamp their creation
%/.dir:
	$(Verb) $(MKDIR) $* > /dev/null
	$(Verb) $(DOTDIR_TIMESTAMP_COMMAND) > $@

.PRECIOUS: $(LibDir)/.dir $(ToolDir)/.dir $(ExmplDir)/.dir
.PRECIOUS: $(LLVMLibDir)/.dir $(LLVMToolDir)/.dir $(LLVMExmplDir)/.dir
.PRECIOUS: $(LibexecDir)/.dir $(ShareDir)/.dir

#---------------------------------------------------------
# Collect the object directories (as there may be more
# than one if the source code is spread across
# subdirectories).
#---------------------------------------------------------

OBJECT_DIRS := $(ObjDir)/.dir $(ObjectDirs:%=%/.dir)
.PRECIOUS: $(OBJECT_DIRS)

#---------------------------------------------------------
# Handle the DIRS options for sequential construction
#---------------------------------------------------------

SubDirs :=
ifdef DIRS
SubDirs += $(DIRS)

ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT))
$(RecursiveTargets)::
	$(Verb) for dir in $(DIRS); do \
	  if ([ ! -f $$dir/Makefile ] || \
	      command test $$dir/Makefile -ot $(PROJ_SRC_DIR)/$$dir/Makefile ); then \
	    $(MKDIR) $$dir; \
	    $(CP) $(PROJ_SRC_DIR)/$$dir/Makefile $$dir/Makefile; \
	  fi; \
	  ($(MAKE) -C $$dir $@ ) || exit 1; \
	done
else
$(RecursiveTargets)::
	$(Verb) for dir in $(DIRS); do \
	  ($(MAKE) -C $$dir $@ ) || exit 1; \
	done
endif

endif

#---------------------------------------------------------
# Handle the EXPERIMENTAL_DIRS options ensuring success
# after each directory is built.
#---------------------------------------------------------
ifdef EXPERIMENTAL_DIRS
$(RecursiveTargets)::
	$(Verb) for dir in $(EXPERIMENTAL_DIRS); do \
	  if ([ ! -f $$dir/Makefile ] || \
	      command test $$dir/Makefile -ot $(PROJ_SRC_DIR)/$$dir/Makefile ); then \
	    $(MKDIR) $$dir; \
	    $(CP) $(PROJ_SRC_DIR)/$$dir/Makefile $$dir/Makefile; \
	  fi; \
	  ($(MAKE) -C $$dir $@ ) || exit 0; \
	done
endif

#-----------------------------------------------------------
# Handle the OPTIONAL_PARALLEL_DIRS options for optional parallel construction
#-----------------------------------------------------------
ifdef OPTIONAL_PARALLEL_DIRS
  PARALLEL_DIRS += $(foreach T,$(OPTIONAL_PARALLEL_DIRS),$(shell test -d $(PROJ_SRC_DIR)/$(T) -o -f $(T)/Makefile && echo "$(T)"))
endif

#-----------------------------------------------------------
# Handle the PARALLEL_DIRS options for parallel construction
#-----------------------------------------------------------
ifdef PARALLEL_DIRS

SubDirs += $(PARALLEL_DIRS)

# Unfortunately, this list must be maintained if new recursive targets are added
all      :: $(addsuffix /.makeall      ,$(PARALLEL_DIRS))
clean    :: $(addsuffix /.makeclean    ,$(PARALLEL_DIRS))
clean-all:: $(addsuffix /.makeclean-all,$(PARALLEL_DIRS))
install  :: $(addsuffix /.makeinstall  ,$(PARALLEL_DIRS))
uninstall:: $(addsuffix /.makeuninstall,$(PARALLEL_DIRS))
install-bytecode  :: $(addsuffix /.makeinstall-bytecode,$(PARALLEL_DIRS))
unitcheck:: $(addsuffix /.makeunitcheck,$(PARALLEL_DIRS))

ParallelTargets := $(foreach T,$(RecursiveTargets),%/.make$(T))

$(ParallelTargets) :
	$(Verb) \
	  SD=$(PROJ_SRC_DIR)/$(@D); \
	  DD=$(@D); \
	  if [ ! -f $$SD/Makefile ]; then \
	    SD=$(@D); \
	    DD=$(notdir $(@D)); \
	  fi; \
	  if ([ ! -f $$DD/Makefile ] || \
	            command test $$DD/Makefile -ot \
                      $$SD/Makefile ); then \
	  $(MKDIR) $$DD; \
	  $(CP) $$SD/Makefile $$DD/Makefile; \
	fi; \
	$(MAKE) -C $$DD $(subst $(@D)/.make,,$@)
endif

#---------------------------------------------------------
# Handle the OPTIONAL_DIRS options for directores that may
# or may not exist.
#---------------------------------------------------------
ifdef OPTIONAL_DIRS

SubDirs += $(OPTIONAL_DIRS)

ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT))
$(RecursiveTargets)::
	$(Verb) for dir in $(OPTIONAL_DIRS); do \
	  if [ -d $(PROJ_SRC_DIR)/$$dir ]; then\
	    if ([ ! -f $$dir/Makefile ] || \
	        command test $$dir/Makefile -ot $(PROJ_SRC_DIR)/$$dir/Makefile ); then \
	      $(MKDIR) $$dir; \
	      $(CP) $(PROJ_SRC_DIR)/$$dir/Makefile $$dir/Makefile; \
	    fi; \
	    ($(MAKE) -C$$dir $@ ) || exit 1; \
	  fi \
	done
else
$(RecursiveTargets)::
	$(Verb) for dir in $(OPTIONAL_DIRS); do \
	  if [ -d $(PROJ_SRC_DIR)/$$dir ]; then\
	    ($(MAKE) -C$$dir $@ ) || exit 1; \
	  fi \
	done
endif
endif

#---------------------------------------------------------
# Handle the CONFIG_FILES options
#---------------------------------------------------------
ifdef CONFIG_FILES

ifdef NO_INSTALL
install-local::
	$(Echo) Install circumvented with NO_INSTALL
uninstall-local::
	$(Echo) UnInstall circumvented with NO_INSTALL
else
install-local:: $(DESTDIR)$(PROJ_etcdir) $(CONFIG_FILES)
	$(Echo) Installing Configuration Files To $(DESTDIR)$(PROJ_etcdir)
	$(Verb)for file in $(CONFIG_FILES); do \
          if test -f $(PROJ_OBJ_DIR)/$${file} ; then \
            $(DataInstall) $(PROJ_OBJ_DIR)/$${file} $(DESTDIR)$(PROJ_etcdir) ; \
          elif test -f $(PROJ_SRC_DIR)/$${file} ; then \
            $(DataInstall) $(PROJ_SRC_DIR)/$${file} $(DESTDIR)$(PROJ_etcdir) ; \
          else \
            $(ECHO) Error: cannot find config file $${file}. ; \
          fi \
	done

uninstall-local::
	$(Echo) Uninstalling Configuration Files From $(DESTDIR)$(PROJ_etcdir)
	$(Verb)for file in $(CONFIG_FILES); do \
	  $(RM) -f $(DESTDIR)$(PROJ_etcdir)/$${file} ; \
	done
endif

endif

###############################################################################
# Set up variables for building libraries
###############################################################################

#---------------------------------------------------------
# Define various command line options pertaining to the
# libraries needed when linking. There are "Proj" libs
# (defined by the user's project) and "LLVM" libs (defined
# by the LLVM project).
#---------------------------------------------------------

ifdef USEDLIBS
ProjLibsOptions := $(patsubst %.a.o, -l%, $(addsuffix .o, $(USEDLIBS)))
ProjLibsOptions := $(patsubst %.o, $(LibDir)/%.o,  $(ProjLibsOptions))
ProjUsedLibs    := $(patsubst %.a.o, lib%.a, $(addsuffix .o, $(USEDLIBS)))
ProjLibsPaths   := $(addprefix $(LibDir)/,$(ProjUsedLibs))
endif

ifdef LLVMLIBS
LLVMLibsOptions := $(patsubst %.a.o, -l%, $(addsuffix .o, $(LLVMLIBS)))
LLVMLibsOptions := $(patsubst %.o, $(LLVMLibDir)/%.o, $(LLVMLibsOptions))
LLVMUsedLibs    := $(patsubst %.a.o, lib%.a, $(addsuffix .o, $(LLVMLIBS)))
LLVMLibsPaths   := $(addprefix $(LLVMLibDir)/,$(LLVMUsedLibs))
endif

# Loadable module for Win32 requires all symbols resolved for linking.
# Then all symbols in LLVM.dll will be available.
ifeq ($(ENABLE_SHARED),1)
  ifdef LOADABLE_MODULE
    ifneq (,$(filter $(HOST_OS),Cygwin MingW))
      LINK_COMPONENTS += all
    endif
  endif
endif

ifndef IS_CLEANING_TARGET
ifdef LINK_COMPONENTS

# If LLVM_CONFIG doesn't exist, build it.  This can happen if you do a make
# clean in tools, then do a make in tools (instead of at the top level).
$(LLVM_CONFIG):
	@echo "*** llvm-config doesn't exist - rebuilding it."
	@$(MAKE) -C $(PROJ_OBJ_ROOT)/tools/llvm-config

$(ToolDir)/$(strip $(TOOLNAME))$(EXEEXT): $(LLVM_CONFIG)

ifeq ($(ENABLE_SHARED), 1)
# We can take the "auto-import" feature to get rid of using dllimport.
ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
LLVMLibsOptions += -Wl,--enable-auto-import,--enable-runtime-pseudo-reloc \
                   -L $(SharedLibDir)
endif
LLVM_SO_NAME = LLVM-$(LLVM_VERSION_MAJOR).$(LLVM_VERSION_MINOR)$(LLVM_VERSION_SUFFIX)
LLVMLibsOptions += -l$(LLVM_SO_NAME)
LLVMLibsPaths += $(SharedLibDir)/$(SharedPrefix)$(LLVM_SO_NAME)$(SHLIBEXT)
else

ifndef NO_LLVM_CONFIG
LLVMConfigLibs := $(shell $(LLVM_CONFIG) --libs $(LINK_COMPONENTS) || echo Error)
ifeq ($(LLVMConfigLibs),Error)
$(error llvm-config --libs failed)
endif
LLVMLibsOptions += $(LLVMConfigLibs)
LLVMConfigLibfiles := $(shell $(LLVM_CONFIG) --libfiles $(LINK_COMPONENTS) || echo Error)
ifeq ($(LLVMConfigLibfiles),Error)
$(error llvm-config --libfiles failed)
endif
LLVMLibsPaths += $(LLVM_CONFIG) $(LLVMConfigLibfiles)
endif

endif
endif
endif

# Set up the library exports file.
ifdef EXPORTED_SYMBOL_FILE

# First, set up the native export file, which may differ from the source
# export file.

ifeq ($(HOST_OS),Darwin)
# Darwin convention prefixes symbols with underscores.
NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE)).sed
$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
	$(Verb) sed -e 's/^/_/' < $< > $@
clean-local::
	-$(Verb) $(RM) -f $(NativeExportsFile)
else
ifeq ($(HAVE_LINK_VERSION_SCRIPT),1)
# Gold and BFD ld require a version script rather than a plain list.
NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE)).map
$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
	$(Verb) echo "{" > $@
	$(Verb) grep -q '[[:alnum:]_]' $< && echo "  global:" >> $@ || :
	$(Verb) sed -e 's/$$/;/' -e 's/^/    /' < $< >> $@
ifneq ($(HOST_OS),OpenBSD)
	$(Verb) echo "  local: *;" >> $@
endif
	$(Verb) echo "};" >> $@
clean-local::
	-$(Verb) $(RM) -f $(NativeExportsFile)
else
ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
# GNU ld Win32 accepts .DEF files that contain "DATA" entries.
NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE:.exports=.def))
$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
	$(Echo) Generating $(notdir $@)
	$(Verb) $(ECHO) "EXPORTS" > $@
	$(Verb) $(CAT) $< >> $@
clean-local::
	-$(Verb) $(RM) -f $(NativeExportsFile)
else
# Default behavior: just use the exports file verbatim.
NativeExportsFile := $(EXPORTED_SYMBOL_FILE)
endif
endif
endif

# Now add the linker command-line options to use the native export file.

# Darwin
ifeq ($(HOST_OS),Darwin)
LLVMLibsOptions += -Wl,-exported_symbols_list,$(NativeExportsFile)
endif

# gold, bfd ld, etc.
ifeq ($(HAVE_LINK_VERSION_SCRIPT),1)
LLVMLibsOptions += -Wl,--version-script,$(NativeExportsFile)
endif

# Windows
ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
# LLVMLibsOptions is invalidated at processing tools/llvm-shlib.
SharedLinkOptions += $(NativeExportsFile)
endif

endif

###############################################################################
# Library Build Rules: Four ways to build a library
###############################################################################

# if we're building a library ...
ifdef LIBRARYNAME

# Make sure there isn't any extraneous whitespace on the LIBRARYNAME option
LIBRARYNAME := $(strip $(LIBRARYNAME))
LIBRARYALIASNAME := $(strip $(LIBRARYALIASNAME))
ifdef LOADABLE_MODULE
BaseLibName.A  := $(LIBRARYNAME).a
BaseLibName.SO := $(LIBRARYNAME)$(SHLIBEXT)
BaseAliasName.SO := $(LIBRARYALIASNAME)$(SHLIBEXT)
else
BaseLibName.A  := lib$(LIBRARYNAME).a
BaseLibName.SO := $(SharedPrefix)$(LIBRARYNAME)$(SHLIBEXT)
BaseAliasName.SO := $(SharedPrefix)$(LIBRARYALIASNAME)$(SHLIBEXT)
endif
LibName.A  := $(LibDir)/$(BaseLibName.A)
LibName.SO := $(SharedLibDir)/$(BaseLibName.SO)
AliasName.SO := $(SharedLibDir)/$(BaseAliasName.SO)
LibName.O  := $(LibDir)/$(LIBRARYNAME).o

#---------------------------------------------------------
# Shared Library Targets:
#   If the user asked for a shared library to be built
#   with the SHARED_LIBRARY variable, then we provide
#   targets for building them.
#---------------------------------------------------------
ifdef SHARED_LIBRARY

all-local:: $(AliasName.SO)

$(AliasName.SO): $(LibName.SO)
ifdef SHARED_ALIAS
	$(Verb) $(AliasTool) $(BaseLibName.SO) $(AliasName.SO)
endif

ifdef EXPORTED_SYMBOL_FILE
$(LibName.SO): $(NativeExportsFile)
endif

ifdef LINK_LIBS_IN_SHARED
ifdef LOADABLE_MODULE
SharedLibKindMessage := "Loadable Module"
SharedLinkOptions := $(LoadableModuleOptions) $(SharedLinkOptions)
else
SharedLibKindMessage := "Shared Library"
endif
$(LibName.SO): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths) $(SharedLibDir)/.dir
	$(Echo) Linking $(BuildMode) $(SharedLibKindMessage) \
	  $(notdir $@)
	$(Verb) $(Link) $(SharedLinkOptions) -o $@ $(ObjectsO) \
	  $(ProjLibsOptions) $(LLVMLibsOptions) $(LIBS)
else
$(LibName.SO): $(ObjectsO) $(SharedLibDir)/.dir
	$(Echo) Linking $(BuildMode) Shared Library $(notdir $@)
	$(Verb) $(Link) $(SharedLinkOptions) -o $@ $(ObjectsO)
endif

clean-local::
ifneq ($(strip $(LibName.SO)),)
	-$(Verb) $(RM) -f $(LibName.SO)
endif

ifdef NO_INSTALL
install-local::
	$(Echo) Install circumvented with NO_INSTALL
uninstall-local::
	$(Echo) Uninstall circumvented with NO_INSTALL
else

# Win32.DLL prefers to be located on the "PATH" of binaries.
ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
DestSharedLibDir := $(DESTDIR)$(PROJ_bindir)
else
DestSharedLibDir := $(DESTDIR)$(PROJ_libdir)
endif
DestSharedLib := $(DestSharedLibDir)/$(BaseLibName.SO)
DestSharedAlias := $(DestSharedLibDir)/$(BaseAliasName.SO)

install-local:: $(DestSharedLib)

$(DestSharedLib): $(LibName.SO) $(DestSharedLibDir)
	$(Echo) Installing $(BuildMode) Shared Library $(DestSharedLib)
	$(Verb) $(INSTALL) $(LibName.SO) $(DestSharedLib)
ifdef SHARED_ALIAS
	$(Echo) Creating alias from $(DestSharedLib) to $(DestSharedAlias)
	$(Verb) $(AliasTool) $(BaseLibName.SO) $(DestSharedAlias)
endif

uninstall-local::
	$(Echo) Uninstalling $(BuildMode) Shared Library $(DestSharedLib)
	-$(Verb) $(RM) -f $(DestSharedLib)
ifdef SHARED_ALIAS
	-$(Verb) $(RM) -f $(DestSharedAlias)
endif
endif
endif

#---------------------------------------------------------
# Library Targets:
#   If neither BUILD_ARCHIVE or LOADABLE_MODULE are specified, default to
#   building an archive.
#---------------------------------------------------------
ifndef NO_BUILD_ARCHIVE
ifndef BUILD_ARCHIVE
ifndef LOADABLE_MODULE
BUILD_ARCHIVE = 1
endif
endif
endif

#---------------------------------------------------------
# Archive Library Targets:
#   If the user wanted a regular archive library built,
#   then we provide targets for building them.
#---------------------------------------------------------
ifdef BUILD_ARCHIVE

all-local:: $(LibName.A)

$(LibName.A): $(ObjectsO) $(LibDir)/.dir
	$(Echo) Building $(BuildMode) Archive Library $(notdir $@)
	-$(Verb) $(RM) -f $@
	$(Verb) $(Archive) $@ $(ObjectsO)
	$(Verb) $(Ranlib) $@

clean-local::
ifneq ($(strip $(LibName.A)),)
	-$(Verb) $(RM) -f $(LibName.A)
endif

ifdef NO_INSTALL
install-local::
	$(Echo) Install circumvented with NO_INSTALL
uninstall-local::
	$(Echo) Uninstall circumvented with NO_INSTALL
else
ifdef NO_INSTALL_ARCHIVES
install-local::
	$(Echo) Install circumvented with NO_INSTALL
uninstall-local::
	$(Echo) Uninstall circumvented with NO_INSTALL
else
DestArchiveLib := $(DESTDIR)$(PROJ_libdir)/lib$(LIBRARYNAME).a

install-local:: $(DestArchiveLib)

$(DestArchiveLib): $(LibName.A) $(DESTDIR)$(PROJ_libdir)
	$(Echo) Installing $(BuildMode) Archive Library $(DestArchiveLib)
	$(Verb) $(MKDIR) $(DESTDIR)$(PROJ_libdir)
	$(Verb) $(INSTALL) $(LibName.A) $(DestArchiveLib)

uninstall-local::
	$(Echo) Uninstalling $(BuildMode) Archive Library $(DestArchiveLib)
	-$(Verb) $(RM) -f $(DestArchiveLib)
endif
endif
endif

# endif LIBRARYNAME
endif

###############################################################################
# Tool Build Rules: Build executable tool based on TOOLNAME option
###############################################################################

ifdef TOOLNAME

#---------------------------------------------------------
# Set up variables for building a tool.
#---------------------------------------------------------
TOOLEXENAME := $(strip $(TOOLNAME))$(EXEEXT)
ifdef EXAMPLE_TOOL
ToolBuildPath   := $(ExmplDir)/$(TOOLEXENAME)
else
ToolBuildPath   := $(ToolDir)/$(TOOLEXENAME)
endif

# TOOLALIAS is a name to symlink (or copy) the tool to.
ifdef TOOLALIAS
ifdef EXAMPLE_TOOL
ToolAliasBuildPath   := $(ExmplDir)/$(strip $(TOOLALIAS))$(EXEEXT)
else
ToolAliasBuildPath   := $(ToolDir)/$(strip $(TOOLALIAS))$(EXEEXT)
endif
endif

#---------------------------------------------------------
# Prune Exports
#---------------------------------------------------------

# If the tool opts in with TOOL_NO_EXPORTS, optimize startup time of the app by
# not exporting all of the weak symbols from the binary.  This reduces dyld
# startup time by 4x on darwin in some cases.
ifdef TOOL_NO_EXPORTS
ifeq ($(HOST_OS),Darwin)

# Tiger tools don't support this.
ifneq ($(DARWIN_MAJVERS),4)
LD.Flags += -Wl,-exported_symbol,_main
endif
endif

ifeq ($(HOST_OS), $(filter $(HOST_OS), DragonFly Linux NetBSD FreeBSD GNU/kFreeBSD GNU))
ifneq ($(ARCH), Mips)
  LD.Flags += -Wl,--version-script=$(LLVM_SRC_ROOT)/autoconf/ExportMap.map
endif
endif
endif

#---------------------------------------------------------
# Tool Order File Support
#---------------------------------------------------------

ifeq ($(HOST_OS),Darwin)
ifdef TOOL_ORDER_FILE

LD.Flags += -Wl,-order_file,$(TOOL_ORDER_FILE)

endif
endif

#---------------------------------------------------------
# Tool Version Info Support
#---------------------------------------------------------

ifeq ($(HOST_OS),Darwin)
ifdef TOOL_INFO_PLIST

LD.Flags += -Wl,-sectcreate,__TEXT,__info_plist,$(ObjDir)/$(TOOL_INFO_PLIST)

$(ToolBuildPath): $(ObjDir)/$(TOOL_INFO_PLIST)

$(ObjDir)/$(TOOL_INFO_PLIST): $(PROJ_SRC_DIR)/$(TOOL_INFO_PLIST).in $(ObjDir)/.dir
	$(Echo) "Creating $(TOOLNAME) '$(TOOL_INFO_PLIST)' file..."
	$(Verb)sed -e "s#@TOOL_INFO_UTI@#$(TOOL_INFO_UTI)#g" \
	           -e "s#@TOOL_INFO_NAME@#$(TOOL_INFO_NAME)#g" \
	           -e "s#@TOOL_INFO_VERSION@#$(TOOL_INFO_VERSION)#g" \
	         -e "s#@TOOL_INFO_BUILD_VERSION@#$(TOOL_INFO_BUILD_VERSION)#g" \
	           $< > $@

endif
endif

#---------------------------------------------------------
# Provide targets for building the tools
#---------------------------------------------------------
all-local:: $(ToolBuildPath) $(ToolAliasBuildPath)

clean-local::
ifneq ($(strip $(ToolBuildPath)),)
	-$(Verb) $(RM) -f $(ToolBuildPath)
endif
ifneq ($(strip $(ToolAliasBuildPath)),)
	-$(Verb) $(RM) -f $(ToolAliasBuildPath)
endif

ifdef EXAMPLE_TOOL
$(ToolBuildPath): $(ExmplDir)/.dir
else
$(ToolBuildPath): $(ToolDir)/.dir
endif

ifdef CODESIGN_TOOLS
TOOL_CODESIGN_IDENTITY ?= -

$(ToolBuildPath): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths)
	$(Echo) Linking $(BuildMode) executable $(TOOLNAME) $(StripWarnMsg)
	$(Verb) $(Link) -o $@ $(TOOLLINKOPTS) $(ObjectsO) $(ProjLibsOptions) \
	$(LLVMLibsOptions) $(ExtraLibs) $(TOOLLINKOPTSB) $(LIBS)
	$(Echo) ======= Finished Linking $(BuildMode) Executable $(TOOLNAME) \
          $(StripWarnMsg)
	$(Echo) ======= Code-Signing $(BuildMode) Executable $(TOOLNAME)
	$(Verb) codesign -s $(TOOL_CODESIGN_IDENTITY) $@
else
$(ToolBuildPath): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths)
	$(Echo) Linking $(BuildMode) executable $(TOOLNAME) $(StripWarnMsg)
	$(Verb) $(Link) -o $@ $(TOOLLINKOPTS) $(ObjectsO) $(ProjLibsOptions) \
	$(LLVMLibsOptions) $(ExtraLibs) $(TOOLLINKOPTSB) $(LIBS)
	$(Echo) ======= Finished Linking $(BuildMode) Executable $(TOOLNAME) \
          $(StripWarnMsg)
endif

ifneq ($(strip $(ToolAliasBuildPath)),)
$(ToolAliasBuildPath): $(ToolBuildPath)
	$(Echo) Creating $(BuildMode) Alias $(TOOLALIAS) $(StripWarnMsg)
	$(Verb) $(RM) -f $(ToolAliasBuildPath)
	$(Verb) $(AliasTool) $(notdir $(ToolBuildPath)) $(ToolAliasBuildPath)
	$(Echo) ======= Finished Creating $(BuildMode) Alias $(TOOLALIAS) \
          $(StripWarnMsg)
endif

ifdef NO_INSTALL
install-local::
	$(Echo) Install circumvented with NO_INSTALL
uninstall-local::
	$(Echo) Uninstall circumvented with NO_INSTALL
else

ifdef INTERNAL_TOOL
ToolBinDir = $(DESTDIR)$(PROJ_internal_prefix)/bin
else
ToolBinDir = $(DESTDIR)$(PROJ_bindir)
endif
DestTool = $(ToolBinDir)/$(program_prefix)$(TOOLEXENAME)

install-local:: $(DestTool)

$(DestTool): $(ToolBuildPath)
	$(Echo) Installing $(BuildMode) $(DestTool)
	$(Verb) $(MKDIR) $(ToolBinDir)
	$(Verb) $(ProgInstall) $(ToolBuildPath) $(DestTool)

uninstall-local::
	$(Echo) Uninstalling $(BuildMode) $(DestTool)
	-$(Verb) $(RM) -f $(DestTool)

# TOOLALIAS install.
ifdef TOOLALIAS
DestToolAlias = $(ToolBinDir)/$(program_prefix)$(TOOLALIAS)$(EXEEXT)

install-local:: $(DestToolAlias)

$(DestToolAlias): $(DestTool)
	$(Echo) Installing $(BuildMode) $(DestToolAlias)
	$(Verb) $(RM) -f $(DestToolAlias)
	$(Verb) $(AliasTool) $(notdir $(DestTool)) $(DestToolAlias)

uninstall-local::
	$(Echo) Uninstalling $(BuildMode) $(DestToolAlias)
	-$(Verb) $(RM) -f $(DestToolAlias)
endif

endif
endif

###############################################################################
# Object Build Rules: Build object files based on sources
###############################################################################

# FIXME: This should be checking for "if not GCC or ICC", not for "if HP-UX"
ifeq ($(HOST_OS),HP-UX)
  DISABLE_AUTO_DEPENDENCIES=1
endif

COMPILE_DEPS = $(OBJECT_DIRS) $(BUILT_SOURCES) $(PROJ_MAKEFILE)

# Provide rule sets for when dependency generation is enabled
ifndef DISABLE_AUTO_DEPENDENCIES

#---------------------------------------------------------
# Create .o files in the ObjDir directory from the .cpp and .c files...
#---------------------------------------------------------

DEPEND_OPTIONS = -MMD -MP -MF "$(ObjDir)/$*.d.tmp" \
         -MT "$(ObjDir)/$*.o" -MT "$(ObjDir)/$*.d"

# If the build succeeded, move the dependency file over, otherwise
# remove it.
DEPEND_MOVEFILE = then $(MV) -f "$(ObjDir)/$*.d.tmp" "$(ObjDir)/$*.d"; \
                  else $(RM) "$(ObjDir)/$*.d.tmp"; exit 1; fi

$(ObjDir)/%.o: %.cpp $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cpp for $(BuildMode) build" $(PIC_FLAG)
	$(Verb) if $(Compile.CXX) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
	        $(DEPEND_MOVEFILE)

$(ObjDir)/%.o: %.mm $(COMPILE_DEPS)
	$(Echo) "Compiling $*.mm for $(BuildMode) build" $(PIC_FLAG)
	$(Verb) if $(Compile.CXX) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
	        $(DEPEND_MOVEFILE)

$(ObjDir)/%.o: %.cc $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cc for $(BuildMode) build" $(PIC_FLAG)
	$(Verb) if $(Compile.CXX) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
	        $(DEPEND_MOVEFILE)

$(ObjDir)/%.o: %.c $(COMPILE_DEPS)
	$(Echo) "Compiling $*.c for $(BuildMode) build" $(PIC_FLAG)
	$(Verb) if $(Compile.C) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
	        $(DEPEND_MOVEFILE)

$(ObjDir)/%.o: %.m $(COMPILE_DEPS)
	$(Echo) "Compiling $*.m for $(BuildMode) build" $(PIC_FLAG)
	$(Verb) if $(Compile.C) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
	        $(DEPEND_MOVEFILE)

# Provide alternate rule sets if dependencies are disabled
else

$(ObjDir)/%.o: %.cpp $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cpp for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.CXX) $< -o $@

$(ObjDir)/%.o: %.mm $(COMPILE_DEPS)
	$(Echo) "Compiling $*.mm for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.CXX) $< -o $@

$(ObjDir)/%.o: %.cc $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cc for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.CXX) $< -o $@

$(ObjDir)/%.o: %.c $(COMPILE_DEPS)
	$(Echo) "Compiling $*.c for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.C) $< -o $@

$(ObjDir)/%.o: %.m $(COMPILE_DEPS)
	$(Echo) "Compiling $*.m for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.C) $< -o $@
endif


## Rules for building preprocessed (.i/.ii) outputs.
$(BuildMode)/%.ii: %.cpp $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cpp for $(BuildMode) build to .ii file"
	$(Verb) $(Preprocess.CXX) $< -o $@

$(BuildMode)/%.ii: %.mm $(COMPILE_DEPS)
	$(Echo) "Compiling $*.mm for $(BuildMode) build to .ii file"
	$(Verb) $(Preprocess.CXX) $< -o $@

$(BuildMode)/%.ii: %.cc $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cc for $(BuildMode) build to .ii file"
	$(Verb) $(Preprocess.CXX) $< -o $@

$(BuildMode)/%.i: %.c $(COMPILE_DEPS)
	$(Echo) "Compiling $*.c for $(BuildMode) build to .i file"
	$(Verb) $(Preprocess.C) $< -o $@

$(BuildMode)/%.i: %.m $(COMPILE_DEPS)
	$(Echo) "Compiling $*.m for $(BuildMode) build to .i file"
	$(Verb) $(Preprocess.C) $< -o $@


$(ObjDir)/%.s: %.cpp $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cpp to asm for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.CXX) $< -o $@ -S

$(ObjDir)/%.s: %.mm $(COMPILE_DEPS)
	$(Echo) "Compiling $*.mm to asm for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.CXX) $< -o $@ -S

$(ObjDir)/%.s: %.cc $(COMPILE_DEPS)
	$(Echo) "Compiling $*.cc to asm for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.CXX) $< -o $@ -S

$(ObjDir)/%.s: %.c $(COMPILE_DEPS)
	$(Echo) "Compiling $*.c to asm for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.C) $< -o $@ -S

$(ObjDir)/%.s: %.m $(COMPILE_DEPS)
	$(Echo) "Compiling $*.m to asm for $(BuildMode) build" $(PIC_FLAG)
	$(Compile.C) $< -o $@ -S

###############################################################################
# TABLEGEN: Provide rules for running tblgen to produce *.inc files
###############################################################################

ifdef TARGET
TABLEGEN_INC_FILES_COMMON = 1
endif

ifdef TABLEGEN_INC_FILES_COMMON

INCFiles := $(filter %.inc,$(BUILT_SOURCES))
INCTMPFiles := $(INCFiles:%=$(ObjDir)/%.tmp)
.PRECIOUS: $(INCTMPFiles) $(INCFiles)

# INCFiles rule: All of the tblgen generated files are emitted to
# $(ObjDir)/%.inc.tmp, instead of emitting them directly to %.inc.  This allows
# us to only "touch" the real file if the contents of it change.  IOW, if
# tblgen is modified, all of the .inc.tmp files are regenerated, but no
# dependencies of the .inc files are, unless the contents of the .inc file
# changes.
$(INCFiles) : %.inc : $(ObjDir)/%.inc.tmp
	$(Verb) $(CMP) -s $@ $< || $(CP) $< $@

endif # TABLEGEN_INC_FILES_COMMON

ifdef TARGET

TDFiles := $(strip $(wildcard $(PROJ_SRC_DIR)/*.td) \
           $(LLVM_SRC_ROOT)/include/llvm/Target/Target.td \
           $(LLVM_SRC_ROOT)/include/llvm/Target/TargetCallingConv.td \
           $(LLVM_SRC_ROOT)/include/llvm/Target/TargetSchedule.td \
           $(LLVM_SRC_ROOT)/include/llvm/Target/TargetSelectionDAG.td \
           $(LLVM_SRC_ROOT)/include/llvm/CodeGen/ValueTypes.td) \
           $(wildcard $(LLVM_SRC_ROOT)/include/llvm/IR/Intrinsics*.td)

# All .inc.tmp files depend on the .td files.
$(INCTMPFiles) : $(TDFiles)

$(TARGET:%=$(ObjDir)/%GenRegisterInfo.inc.tmp): \
$(ObjDir)/%GenRegisterInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) register info implementation with tblgen"
	$(Verb) $(LLVMTableGen) -gen-register-info -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenInstrInfo.inc.tmp): \
$(ObjDir)/%GenInstrInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) instruction information with tblgen"
	$(Verb) $(LLVMTableGen) -gen-instr-info -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenAsmWriter.inc.tmp): \
$(ObjDir)/%GenAsmWriter.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) assembly writer with tblgen"
	$(Verb) $(LLVMTableGen) -gen-asm-writer -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenAsmWriter1.inc.tmp): \
$(ObjDir)/%GenAsmWriter1.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) assembly writer #1 with tblgen"
	$(Verb) $(LLVMTableGen) -gen-asm-writer -asmwriternum=1 -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenAsmMatcher.inc.tmp): \
$(ObjDir)/%GenAsmMatcher.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) assembly matcher with tblgen"
	$(Verb) $(LLVMTableGen) -gen-asm-matcher -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenMCCodeEmitter.inc.tmp): \
$(ObjDir)/%GenMCCodeEmitter.inc.tmp: %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) MC code emitter with tblgen"
	$(Verb) $(LLVMTableGen) -gen-emitter -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenMCPseudoLowering.inc.tmp): \
$(ObjDir)/%GenMCPseudoLowering.inc.tmp: %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) MC Pseudo instruction expander with tblgen"
	$(Verb) $(LLVMTableGen) -gen-pseudo-lowering -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenDAGISel.inc.tmp): \
$(ObjDir)/%GenDAGISel.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) DAG instruction selector implementation with tblgen"
	$(Verb) $(LLVMTableGen) -gen-dag-isel -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenDisassemblerTables.inc.tmp): \
$(ObjDir)/%GenDisassemblerTables.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) disassembly tables with tblgen"
	$(Verb) $(LLVMTableGen) -gen-disassembler -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenFastISel.inc.tmp): \
$(ObjDir)/%GenFastISel.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) \"fast\" instruction selector implementation with tblgen"
	$(Verb) $(LLVMTableGen) -gen-fast-isel -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenSubtargetInfo.inc.tmp): \
$(ObjDir)/%GenSubtargetInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) subtarget information with tblgen"
	$(Verb) $(LLVMTableGen) -gen-subtarget -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenCallingConv.inc.tmp): \
$(ObjDir)/%GenCallingConv.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) calling convention information with tblgen"
	$(Verb) $(LLVMTableGen) -gen-callingconv -o $(call SYSPATH, $@) $<

$(TARGET:%=$(ObjDir)/%GenIntrinsics.inc.tmp): \
$(ObjDir)/%GenIntrinsics.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) intrinsics information with tblgen"
	$(Verb) $(LLVMTableGen) -gen-tgt-intrinsic -o $(call SYSPATH, $@) $<

$(ObjDir)/ARMGenDecoderTables.inc.tmp : ARM.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) decoder tables with tblgen"
	$(Verb) $(LLVMTableGen) -gen-arm-decoder -o $(call SYSPATH, $@) $<

$(ObjDir)/%GenDFAPacketizer.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
	$(Echo) "Building $(<F) DFA packetizer tables with tblgen"
	$(Verb) $(LLVMTableGen) -gen-dfa-packetizer -o $(call SYSPATH, $@) $<

# Dump all the records to <target>.td.expanded.  This is useful for debugging.
$(TARGET:%=%.td.expanded): \
%.td.expanded : %.td $(LLVM_TBLGEN) $(TDFiles)
	$(Echo) "Building a fully expanded version of $(<F)"
	$(Verb) $(LLVMTableGen) -o $(call SYSPATH, $@) $<

clean-local::
	-$(Verb) $(RM) -f $(INCFiles) $(TARGET).td.expanded

endif # TARGET

###############################################################################
# OTHER RULES: Other rules needed
###############################################################################

# To create postscript files from dot files...
ifneq ($(DOT),false)
%.ps: %.dot
	$(DOT) -Tps < $< > $@
else
%.ps: %.dot
	$(Echo) "Cannot build $@: The program dot is not installed"
endif

# This rules ensures that header files that are removed still have a rule for
# which they can be "generated."  This allows make to ignore them and
# reproduce the dependency lists.
%.h:: ;
%.hpp:: ;

# Define clean-local to clean the current directory. Note that this uses a
# very conservative approach ensuring that empty variables do not cause
# errors or disastrous removal.
clean-local::
ifneq ($(strip $(ObjRootDir)),)
	-$(Verb) $(RM) -rf $(ObjRootDir)
endif
ifneq ($(strip $(SHLIBEXT)),) # Extra paranoia - make real sure SHLIBEXT is set
	-$(Verb) $(RM) -f *$(SHLIBEXT)
endif

clean-all-local::
	-$(Verb) $(RM) -rf Debug Release Profile


###############################################################################
# DEPENDENCIES: Include the dependency files if we should
###############################################################################
ifndef DISABLE_AUTO_DEPENDENCIES

# If its not one of the cleaning targets
ifndef IS_CLEANING_TARGET

# Get the list of dependency files
DependSourceFiles := $(basename $(filter %.cpp %.c %.cc %.m %.mm, $(Sources)))
DependFiles := $(DependSourceFiles:%=$(PROJ_OBJ_DIR)/$(BuildMode)/%.d)

-include $(DependFiles) ""

endif

endif

###############################################################################
# CHECK: Running the test suite
###############################################################################

check::
	$(Verb) if test -d "$(PROJ_OBJ_ROOT)/test" ; then \
	  if test -f "$(PROJ_OBJ_ROOT)/test/Makefile" ; then \
	    $(EchoCmd) Running test suite ; \
	    $(MAKE) -C $(PROJ_OBJ_ROOT)/test check-local \
	      TESTSUITE=$(TESTSUITE) ; \
	  else \
	    $(EchoCmd) No Makefile in test directory ; \
	  fi ; \
	else \
	  $(EchoCmd) No test directory ; \
	fi

# An alias dating from when both lit and DejaGNU test runners were used.
check-lit:: check

check-all::
	$(Verb) if test -d "$(PROJ_OBJ_ROOT)/test" ; then \
	  if test -f "$(PROJ_OBJ_ROOT)/test/Makefile" ; then \
	    $(EchoCmd) Running test suite ; \
	    $(MAKE) -C $(PROJ_OBJ_ROOT)/test check-local-all ; \
	  else \
	    $(EchoCmd) No Makefile in test directory ; \
	  fi ; \
	else \
	  $(EchoCmd) No test directory ; \
	fi

###############################################################################
# UNITTESTS: Running the unittests test suite
###############################################################################

unittests::
	$(Verb) if test -d "$(PROJ_OBJ_ROOT)/unittests" ; then \
	  if test -f "$(PROJ_OBJ_ROOT)/unittests/Makefile" ; then \
	    $(EchoCmd) Running unittests test suite ; \
	    $(MAKE) -C $(PROJ_OBJ_ROOT)/unittests unitcheck; \
	  else \
	    $(EchoCmd) No Makefile in unittests directory ; \
	  fi ; \
	else \
	  $(EchoCmd) No unittests directory ; \
	fi

###############################################################################
# DISTRIBUTION: Handle construction of a distribution tarball
###############################################################################

#------------------------------------------------------------------------
# Define distribution related variables
#------------------------------------------------------------------------
DistName    := $(PROJECT_NAME)-$(PROJ_VERSION)
DistDir     := $(PROJ_OBJ_ROOT)/$(DistName)
TopDistDir  := $(PROJ_OBJ_ROOT)/$(DistName)
DistTarGZip := $(PROJ_OBJ_ROOT)/$(DistName).tar.gz
DistZip     := $(PROJ_OBJ_ROOT)/$(DistName).zip
DistTarBZ2  := $(PROJ_OBJ_ROOT)/$(DistName).tar.bz2
DistAlways  := CREDITS.TXT LICENSE.TXT README.txt README AUTHORS COPYING \
	       ChangeLog INSTALL NEWS Makefile Makefile.common Makefile.rules \
	       Makefile.config.in configure autoconf
DistOther   := $(notdir $(wildcard \
               $(PROJ_SRC_DIR)/*.h \
               $(PROJ_SRC_DIR)/*.td \
               $(PROJ_SRC_DIR)/*.def \
               $(PROJ_SRC_DIR)/*.ll \
               $(PROJ_SRC_DIR)/*.in))
DistSubDirs := $(SubDirs)
DistSources  = $(Sources) $(EXTRA_DIST)
DistFiles    = $(DistAlways) $(DistSources) $(DistOther)

#------------------------------------------------------------------------
# We MUST build distribution with OBJ_DIR != SRC_DIR
#------------------------------------------------------------------------
ifeq ($(PROJ_SRC_DIR),$(PROJ_OBJ_DIR))
dist dist-check dist-clean dist-gzip dist-bzip2 dist-zip ::
	$(Echo) ERROR: Target $@ only available with OBJ_DIR != SRC_DIR

else

#------------------------------------------------------------------------
# Prevent attempt to run dist targets from anywhere but the top level
#------------------------------------------------------------------------
ifneq ($(LEVEL),.)
dist dist-check dist-clean dist-gzip dist-bzip2 dist-zip ::
	$(Echo) ERROR: You must run $@ from $(PROJ_OBJ_ROOT)
else

#------------------------------------------------------------------------
# Provide the top level targets
#------------------------------------------------------------------------

dist-gzip:: $(DistTarGZip)

$(DistTarGZip) : $(TopDistDir)/.makedistdir
	$(Echo) Packing gzipped distribution tar file.
	$(Verb) cd $(PROJ_OBJ_ROOT) ; $(TAR) chf - "$(DistName)" | \
	  $(GZIP) -c > "$(DistTarGZip)"

dist-bzip2:: $(DistTarBZ2)

$(DistTarBZ2) : $(TopDistDir)/.makedistdir
	$(Echo) Packing bzipped distribution tar file.
	$(Verb) cd $(PROJ_OBJ_ROOT) ; $(TAR) chf - $(DistName) | \
	  $(BZIP2) -c >$(DistTarBZ2)

dist-zip:: $(DistZip)

$(DistZip) : $(TopDistDir)/.makedistdir
	$(Echo) Packing zipped distribution file.
	$(Verb) rm -f $(DistZip)
	$(Verb) cd $(PROJ_OBJ_ROOT) ; $(ZIP) -rq $(DistZip) $(DistName)

dist :: $(DistTarGZip) $(DistTarBZ2) $(DistZip)
	$(Echo) ===== DISTRIBUTION PACKAGING SUCCESSFUL =====

DistCheckDir := $(PROJ_OBJ_ROOT)/_distcheckdir

dist-check:: $(DistTarGZip)
	$(Echo) Checking distribution tar file.
	$(Verb) if test -d $(DistCheckDir) ; then \
	  $(RM) -rf $(DistCheckDir) ; \
	fi
	$(Verb) $(MKDIR) $(DistCheckDir)
	$(Verb) cd $(DistCheckDir) && \
	  $(MKDIR) $(DistCheckDir)/build && \
	  $(MKDIR) $(DistCheckDir)/install && \
	  gunzip -c $(DistTarGZip) | $(TAR) xf - && \
	  cd build && \
	  ../$(DistName)/configure --prefix="$(DistCheckDir)/install" \
	    --srcdir=../$(DistName) $(DIST_CHECK_CONFIG_OPTIONS) && \
	  $(MAKE) all && \
	  $(MAKE) check && \
	  $(MAKE) unittests && \
	  $(MAKE) install && \
	  $(MAKE) uninstall && \
	  $(MAKE) dist-clean && \
	  $(EchoCmd) ===== $(DistTarGZip) Ready For Distribution =====

dist-clean::
	$(Echo) Cleaning distribution files
	-$(Verb) $(RM) -rf $(DistTarGZip) $(DistTarBZ2) $(DistZip) $(DistName) \
	  $(DistCheckDir)

endif

#------------------------------------------------------------------------
# Provide the recursive distdir target for building the distribution directory
#------------------------------------------------------------------------
distdir: $(DistDir)/.makedistdir
$(DistDir)/.makedistdir: $(DistSources)
	$(Verb) if test "$(DistDir)" = "$(TopDistDir)" ; then \
	  if test -d "$(DistDir)" ; then \
	    find $(DistDir) -type d ! -perm -200 -exec chmod u+w {} ';'  || \
	      exit 1 ; \
	  fi ; \
	  $(EchoCmd) Removing old $(DistDir) ; \
	  $(RM) -rf $(DistDir); \
	  $(EchoCmd) Making 'all' to verify build ; \
	  $(MAKE) ENABLE_OPTIMIZED=1 all ; \
	fi
	$(Echo) Building Distribution Directory $(DistDir)
	$(Verb) $(MKDIR) $(DistDir)
	$(Verb) srcdirstrip=`echo "$(PROJ_SRC_DIR)" | sed 's|.|.|g'`; \
	srcrootstrip=`echo "$(PROJ_SRC_ROOT)" | sed 's|.|.|g'`; \
	for file in $(DistFiles) ; do \
	  case "$$file" in \
	    $(PROJ_SRC_DIR)/*) \
	      file=`echo "$$file" | sed "s#^$$srcdirstrip/##"` \
	      ;; \
	    $(PROJ_SRC_ROOT)/*) \
	      file=`echo "$$file" | \
		sed "s#^$$srcrootstrip/##"` \
	      ;; \
	  esac; \
	  if test -f "$(PROJ_SRC_DIR)/$$file" || \
	     test -d "$(PROJ_SRC_DIR)/$$file" ; then \
	    from_dir="$(PROJ_SRC_DIR)" ; \
	  elif test -f "$$file" || test -d "$$file" ; then \
	    from_dir=. ; \
	  fi ; \
	  to_dir=`echo "$$file" | sed -e 's#/[^/]*$$##'` ; \
	  if test "$$to_dir" != "$$file" && test "$$to_dir" != "."; then \
	    to_dir="$(DistDir)/$$dir"; \
	    $(MKDIR) "$$to_dir" ; \
	  else \
	    to_dir="$(DistDir)"; \
	  fi; \
	  mid_dir=`echo "$$file" | sed -n -e 's#^\(.*\)/[^/]*$$#\1#p'`; \
	  if test -n "$$mid_dir" ; then \
            $(MKDIR) "$$to_dir/$$mid_dir" || exit 1; \
          fi ; \
	  if test -d "$$from_dir/$$file"; then \
	    if test -d "$(PROJ_SRC_DIR)/$$file" && \
	       test "$$from_dir" != "$(PROJ_SRC_DIR)" ; then \
	       cd $(PROJ_SRC_DIR) ; \
	       $(TAR) cf - $$file --exclude .svn --exclude CVS | \
	         ( cd $$to_dir ; $(TAR) xf - ) ; \
	       cd $(PROJ_OBJ_DIR) ; \
	    else \
	       cd $$from_dir ; \
	       $(TAR) cf - $$file --exclude .svn --exclude CVS | \
	         ( cd $$to_dir ; $(TAR) xf - ) ; \
	       cd $(PROJ_OBJ_DIR) ; \
	    fi; \
	  elif test -f "$$from_dir/$$file" ; then \
	    $(CP) -p "$$from_dir/$$file" "$(DistDir)/$$file" || exit 1; \
	  elif test -L "$$from_dir/$$file" ; then \
	    $(CP) -pd "$$from_dir/$$file" $(DistDir)/$$file || exit 1; \
	  elif echo "$(DistAlways)" | grep -v "$$file" >/dev/null ; then \
	    $(EchoCmd) "===== WARNING: Distribution Source " \
	      "$$from_dir/$$file Not Found!" ; \
	  elif test "$(Verb)" != '@' ; then \
	    $(EchoCmd) "Skipping non-existent $$from_dir/$$file" ; \
	  fi; \
	done
	$(Verb) for subdir in $(DistSubDirs) ; do \
	  if test "$$subdir" \!= "." ; then \
	    new_distdir="$(DistDir)/$$subdir" ; \
	    test -d "$$new_distdir" || $(MKDIR) "$$new_distdir" || exit 1; \
	    ( cd $$subdir && $(MAKE) ENABLE_OPTIMIZED=1 \
	      DistDir="$$new_distdir" distdir ) || exit 1; \
	  fi; \
	done
	$(Verb) if test "$(DistDir)" = "$(TopDistDir)" ; then \
	  $(EchoCmd) Eliminating CVS/.svn directories from distribution ; \
	  $(RM) -rf `find $(TopDistDir) -type d \( -name CVS -o \
                                  -name .svn \) -print` ;\
	  $(MAKE) dist-hook ; \
	  $(FIND) $(TopDistDir) -type d ! -perm -777 -exec chmod a+rwx {} \; \
	    -o ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; \
	    -o ! -type d ! -perm -400 -exec chmod a+r {} \; \
	    -o ! -type d ! -perm -444 -exec \
	      $(SHELL) $(INSTALL_SH) -c -m a+r {} {} \; \
	    || chmod -R a+r $(DistDir) ; \
	fi

# This is invoked by distdir target, define it as a no-op to avoid errors if not
# defined by user.
dist-hook::

endif

###############################################################################
# TOP LEVEL - targets only to apply at the top level directory
###############################################################################

ifeq ($(LEVEL),.)

#------------------------------------------------------------------------
# Install support for the project's include files:
#------------------------------------------------------------------------
ifdef NO_INSTALL
install-local::
	$(Echo) Install circumvented with NO_INSTALL
uninstall-local::
	$(Echo) Uninstall circumvented with NO_INSTALL
else
install-local::
	$(Echo) Installing include files
	$(Verb) $(MKDIR) $(DESTDIR)$(PROJ_includedir)
	$(Verb) if test -d "$(PROJ_SRC_ROOT)/include" ; then \
	  cd $(PROJ_SRC_ROOT)/include && \
	  for hdr in `find . -type f \
	      '(' -name LICENSE.TXT \
	       -o -name '*.def' \
	       -o -name '*.h' \
	       -o -name '*.inc' \
	       -o -name '*.td' \
	      ')' -print | grep -v CVS | \
	      grep -v .svn` ; do \
	    instdir=`dirname "$(DESTDIR)$(PROJ_includedir)/$$hdr"` ; \
	    if test \! -d "$$instdir" ; then \
	      $(EchoCmd) Making install directory $$instdir ; \
	      $(MKDIR) $$instdir ;\
	    fi ; \
	    $(DataInstall) $$hdr $(DESTDIR)$(PROJ_includedir)/$$hdr ; \
	  done ; \
	fi
ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT))
	$(Verb) if test -d "$(PROJ_OBJ_ROOT)/include" ; then \
	  cd $(PROJ_OBJ_ROOT)/include && \
	  for hdr in `find . -type f \
	      '(' -name LICENSE.TXT \
	       -o -name '*.def' \
	       -o -name '*.h' \
	       -o -name '*.inc' \
	       -o -name '*.td' \
	      ')' -print | grep -v CVS | \
	      grep -v .svn` ; do \
	    instdir=`dirname "$(DESTDIR)$(PROJ_includedir)/$$hdr"` ; \
	    if test \! -d "$$instdir" ; then \
	      $(EchoCmd) Making install directory $$instdir ; \
	      $(MKDIR) $$instdir ;\
	    fi ; \
	    $(DataInstall) $$hdr $(DESTDIR)$(PROJ_includedir)/$$hdr ; \
	  done ; \
	fi
endif

uninstall-local::
	$(Echo) Uninstalling include files
	$(Verb) if [ -d "$(PROJ_SRC_ROOT)/include" ] ; then \
	  cd $(PROJ_SRC_ROOT)/include && \
	    $(RM) -f `find . -path '*/Internal' -prune -o '(' -type f \
	      '!' '(' -name '*~' -o -name '.#*' \
        -o -name '*.in' ')' -print ')' | \
        grep -v CVS | sed 's#^#$(DESTDIR)$(PROJ_includedir)/#'` ; \
	  cd $(PROJ_SRC_ROOT)/include && \
	    $(RM) -f `find . -path '*/Internal' -prune -o '(' -type f -name '*.in' \
      -print ')' | sed 's#\.in$$##;s#^#$(DESTDIR)$(PROJ_includedir)/#'` ; \
	fi
endif
endif

check-line-length:
	@echo searching for overlength lines in files: $(Sources)
	@echo
	@echo
	egrep -n '.{81}' $(Sources) /dev/null

check-for-tabs:
	@echo searching for tabs in files: $(Sources)
	@echo
	@echo
	egrep -n '	' $(Sources) /dev/null

check-footprint:
	@ls -l $(LibDir) | awk '\
	  BEGIN { sum = 0; } \
	        { sum += $$5; } \
	  END   { printf("Libraries: %6.3f MBytes\n", sum/(1024.0*1024.0)); }'
	@ls -l $(ToolDir) | awk '\
	  BEGIN { sum = 0; } \
	        { sum += $$5; } \
	  END   { printf("Programs:  %6.3f MBytes\n", sum/(1024.0*1024.0)); }'
#------------------------------------------------------------------------
# Print out the directories used for building
#------------------------------------------------------------------------
printvars::
	$(Echo) "BuildMode    : " '$(BuildMode)'
	$(Echo) "PROJ_SRC_ROOT: " '$(PROJ_SRC_ROOT)'
	$(Echo) "PROJ_SRC_DIR : " '$(PROJ_SRC_DIR)'
	$(Echo) "PROJ_OBJ_ROOT: " '$(PROJ_OBJ_ROOT)'
	$(Echo) "PROJ_OBJ_DIR : " '$(PROJ_OBJ_DIR)'
	$(Echo) "LLVM_SRC_ROOT: " '$(LLVM_SRC_ROOT)'
	$(Echo) "LLVM_OBJ_ROOT: " '$(LLVM_OBJ_ROOT)'
	$(Echo) "PROJ_prefix  : " '$(PROJ_prefix)'
	$(Echo) "PROJ_internal_prefix  : " '$(PROJ_internal_prefix)'
	$(Echo) "PROJ_bindir  : " '$(PROJ_bindir)'
	$(Echo) "PROJ_libdir  : " '$(PROJ_libdir)'
	$(Echo) "PROJ_etcdir  : " '$(PROJ_etcdir)'
	$(Echo) "PROJ_includedir  : " '$(PROJ_includedir)'
	$(Echo) "UserTargets  : " '$(UserTargets)'
	$(Echo) "ObjMakefiles : " '$(ObjMakefiles)'
	$(Echo) "SrcMakefiles : " '$(SrcMakefiles)'
	$(Echo) "ObjDir       : " '$(ObjDir)'
	$(Echo) "LibDir       : " '$(LibDir)'
	$(Echo) "LibexecDir   : " '$(LibexecDir)'
	$(Echo) "ShareDir     : " '$(ShareDir)'
	$(Echo) "ToolDir      : " '$(ToolDir)'
	$(Echo) "ExmplDir     : " '$(ExmplDir)'
	$(Echo) "Sources      : " '$(Sources)'
	$(Echo) "TDFiles      : " '$(TDFiles)'
	$(Echo) "INCFiles     : " '$(INCFiles)'
	$(Echo) "INCTMPFiles  : " '$(INCTMPFiles)'
	$(Echo) "PreConditions: " '$(PreConditions)'
	$(Echo) "Compile.CXX  : " '$(Compile.CXX)'
	$(Echo) "Compile.C    : " '$(Compile.C)'
	$(Echo) "Archive      : " '$(Archive)'
	$(Echo) "YaccFiles    : " '$(YaccFiles)'
	$(Echo) "LexFiles     : " '$(LexFiles)'
	$(Echo) "Module       : " '$(Module)'
	$(Echo) "FilesToConfig: " '$(FilesToConfigPATH)'
	$(Echo) "SubDirs      : " '$(SubDirs)'
	$(Echo) "ProjLibsPaths: " '$(ProjLibsPaths)'
	$(Echo) "ProjLibsOptions: " '$(ProjLibsOptions)'

###
# Debugging

# General debugging rule, use 'make dbg-print-XXX' to print the
# definition, value and origin of XXX.
make-print-%:
	$(error PRINT: $(value $*) = "$($*)" (from $(origin $*)))