# This compiler version is not supported beyond these very strict use cases:
#     1) Building newer llvm Mountain Lion (https://trac.macports.org/ticket/53138)
#
# There should be no other usage of clang-3.7 nor llvm-3.7
#
# llvm-3.7 was the last version to use the autoconf build system.  Newer
# versions require cmake to build.  Cmake requires a C++11 toolchain, so
# clang-3.7 is being kept around in order to build cmake (or its dependencies)
# if needed on such systems.

PortSystem              1.0
PortGroup select        1.0
PortGroup active_variants 1.1

set llvm_version        3.7
set llvm_version_no_dot 37
name                    llvm-${llvm_version}
revision                7
subport                 clang-${llvm_version} { revision 9 }
set suffix              mp-${llvm_version}
set sub_prefix          ${prefix}/libexec/llvm-${llvm_version}
dist_subdir             llvm
categories              lang
platforms               darwin
license                 NCSA
maintainers             {jeremyhu @jeremyhu} {larryv @larryv}

# needs xcode to build
#see https://trac.macports.org/ticket/59677
#see https://trac.macports.org/ticket/58779
#see https://trac.macports.org/ticket/60196
use_xcode yes

if {${subport} eq "llvm-${llvm_version}"} {
    homepage            https://llvm.org/
    description         llvm is a next generation compiler infrastructure
    long_description    The LLVM Core libraries provide a modern source- and \
                        target-independent optimizer, along with code \
                        generation support for many popular CPUs (as well as \
                        some less common ones!) These libraries are built \
                        around a well specified code representation known as \
                        the LLVM intermediate representation ("LLVM IR").

    depends_lib         port:libedit port:libffi port:ncurses port:zlib
    depends_run         bin:perl:perl5 port:llvm_select
} elseif {${subport} eq "clang-${llvm_version}"} {
    homepage            https://clang.llvm.org/
    description         C, C++, Objective C and Objective C++ compiler
    long_description    Clang is an "LLVM native" C/C++/Objective-C compiler, \
                        which aims to deliver amazingly fast compiles (e.g. \
                        about 3x faster than GCC when compiling Objective-C \
                        code in a debug configuration), extremely useful error \
                        and warning messages and to provide a platform for \
                        building great source level tools. The included Clang \
                        Static Analyzer is a tool that automatically finds bugs in \
                        your code, and is a great example of the sort of tool \
                        that can be built using the Clang frontend as a \
                        library to parse C/C++ code.

    depends_lib         port:libxml2 port:llvm-${llvm_version}
    depends_run         port:clang_select port:ld64
    depends_build       port:cctools
    depends_skip_archcheck-append cctools ld64

    depends_lib-append  port:libedit port:libffi port:ncurses port:zlib

    # Avoid requiring a bootstrap version of perl5 on 10.6.
    if {${os.major} >= 11} {
        default_variants    +analyzer
    }

    # libxml2 depends on icu, which now needs a C++11 compiler
    # this is problematic for bootstrapping, and clang in fact does not require libxml2
    # (although c-index-test will optionally use it if it is installed)
    # remove the dependency, and force any installed version of libxml2 to
    # be ignored during configuration for consistent building
    if {${os.major} < 13} {
        depends_lib-delete     port:libxml2
        configure.env-append   ac_cv_lib_xml2_xmlReadFile=no
    }
}

#fetch.type              svn
#svn.revision            246024

#set compiler_rt_rev     ${svn.revision}
#set libcxx_rev          ${svn.revision}
#set clang-modernize_rev ${svn.revision}
#version                 ${llvm_version}-r${svn.revision}
#worksrcdir              trunk
#svn.url                 https://llvm.org/svn/llvm-project/llvm/trunk
#worksrcdir              release_${llvm_version_no_dot}
#svn.url                 https://llvm.org/svn/llvm-project/llvm/branches/release_${llvm_version_no_dot}
#default_variants-append +assertions

version                 ${llvm_version}.1
epoch                   1
master_sites            https://releases.llvm.org/${version}
if {${os.platform} eq "darwin" && ${os.major} < 11 && ${cxx_stdlib} eq "libc++" && ![file executable ${prefix}/bin/xz]} {
    # xz needs a macports-clang compiler to build in this configuration
    depends_extract     port:xz-bootstrap
    depends_skip_archcheck-append   xz-bootstrap
    extract.suffix      .tar.xz
    extract.cmd         ${prefix}/libexec/xz-bootstrap/bin/xz
} else {
    use_xz              yes
}
distfiles               llvm-${version}.src${extract.suffix}
worksrcdir              llvm-${version}.src

if {${distfiles} ne ""} {
    if {${subport} eq "llvm-${llvm_version}"} {
        if {[variant_isset polly]} {
            distfiles-append     polly-${version}.src${extract.suffix}
        }
    } elseif {${subport} eq "clang-${llvm_version}"} {
        distfiles-append     cfe-${version}.src${extract.suffix} compiler-rt-${version}.src${extract.suffix} libcxx-${version}.src${extract.suffix} clang-tools-extra-${version}.src${extract.suffix}
    }
}

checksums           llvm-3.7.1.src.tar.xz \
                    rmd160  677e652107e53ec1edeccaf479eff186a9f4c7d6 \
                    sha256  be7794ed0cec42d6c682ca8e3517535b54555a3defabec83554dbc74db545ad5 \
                    cfe-3.7.1.src.tar.xz \
                    rmd160  185b0f75970bc50682766a21794440578db87b5d \
                    sha256  56e2164c7c2a1772d5ed2a3e57485ff73ff06c97dff12edbeea1acc4412b0674 \
                    compiler-rt-3.7.1.src.tar.xz \
                    rmd160  d80d61d0352e4a88265999e081a745779ccc4897 \
                    sha256  9d4769e4a927d3824bcb7a9c82b01e307c68588e6de4e7f04ab82d82c5af8181 \
                    libcxx-3.7.1.src.tar.xz \
                    rmd160  b63d75f0547eb17e3f3f4df0875dfe1d0c32525d \
                    sha256  357fbd4288ce99733ba06ae2bec6f503413d258aeebaab8b6a791201e6f7f144 \
                    clang-tools-extra-3.7.1.src.tar.xz \
                    rmd160  62c82a42807ea68bebabec96d3d30d787e3996f2 \
                    sha256  4a91edaccad1ce984c7c49a4a87db186b7f7b21267b2b03bcf4bd7820715bc6b \
                    polly-3.7.1.src.tar.xz \
                    rmd160  0549da0fdf597e812d5281a01cdd0974f6742718 \
                    sha256  ce9273ad315e1904fd35dc64ac4375fd592f3c296252ab1d163b9ff593ec3542

patch.pre_args-replace  -p0 -p1
patchfiles \
        0001-Set-the-Mach-O-CPU-Subtype-to-ppc7400-when-targeting.patch \
        0002-Define-EXC_MASK_CRASH-and-MACH_EXCEPTION_CODES-if-th.patch \
        0003-MacPorts-Only-Update-install-targets-for-clang-subpo.patch \
        0004-MacPorts-Only-Use-full-path-for-the-dylib-id-instead.patch \
        0005-MacPorts-Only-Don-t-embed-the-deployment-target-in-t.patch \
        0006-MacPorts-Only-Skip-checking-for-python-in-configure.patch \
        0007-Remove-override-of-raise-abort-and-__assert_rtn.patch \
        llvm-skip-unittests.patch

if {${subport} eq "clang-${llvm_version}"} {
    patchfiles-append \
        1001-MacPorts-Only-Prepare-clang-format-for-replacement-w.patch \
        1002-MacPorts-Only-Fall-back-on-xcodebuild-sdk-when-xcrun.patch \
        1003-MacPorts-Only-Fix-name-of-scan-view-executable-insid.patch \
        1004-MacPorts-Only-Relocate-clang-resources-using-llvm-ve.patch \
        1005-Default-to-ppc7400-for-OSX-10.5.patch \
        1006-Only-call-setpriority-PRIO_DARWIN_THREAD-0-PRIO_DARW.patch \
        1007-Default-to-fragile-ObjC-runtime-when-targeting-darwi.patch \
        1008-Fixup-libstdc-header-search-paths-for-older-versions.patch \
        2001-MacPorts-Only-Comment-out-SL-cctools-workaround.patch \
        2002-Update-CheckArches-to-fallback-on-Intel-ppc-if-ld-v-.patch \
        2003-Fall-back-on-xcodebuild-sdk-when-xcrun-sdk-is-not-su.patch \
        2004-On-darwin-build-ppc-slices-of-the-compiler-runtime-i.patch \
        2005-MacPorts-Only-Don-t-build-x86_64h-slice-of-compiler-.patch \
        2006-Set-abort_on_error-to-true-by-default.patch \
        2007-cherry-pick-RemoveANSIEscapeSequencesFromString-from.patch \
        2008-Save-the-ASan-report-in-the-OS-X-crash-log.patch \
        3001-buildit-build-fix-for-Leopard.patch \
        3002-buildit-Set-compatibility-version-to-RC_ProjectSourc.patch \
        3003-Fix-local-and-iterator-when-building-with-Lion-and-n.patch \
        3004-Fix-missing-long-long-math-prototypes-when-using-the.patch \
        3005-implement-atomic-using-mutex-lock_guard-for-64b-ops-.patch \
        compiler_rt-toolchain.patch

    # I'm not sure if we need to delete this.  It seems to build fine with it
    # present, but we used to explicitly only use this patch for the llvm subport.
    patchfiles-delete \
        0005-MacPorts-Only-Skip-checking-for-python-in-configure.patch

    build.target        clang-only
    destroot.target     install-clang
}

build.env-append        VERBOSE=1 \
                        REQUIRES_RTTI=1 \
                        LLVM_SUBMIT_VERSION=3 \
                        LLVM_SUBMIT_SUBVERSION=7.1
destroot.env-append     VERBOSE=1 \
                        REQUIRES_RTTI=1 \
                        LLVM_SUBMIT_VERSION=3 \
                        LLVM_SUBMIT_SUBVERSION=7.1

configure.dir           ${workpath}/build
build.dir               ${configure.dir}

configure.cmd           ${worksrcpath}/configure
configure.pre_args-delete --prefix=${prefix}
configure.args          --enable-bindings=none --enable-libffi --enable-shared --enable-jit \
                        --enable-optimized --disable-profiling --enable-pic \
                        --disable-debug-symbols --disable-debug-runtime \
                        --prefix="${sub_prefix}" --disable-assertions

# need arm target or compiler-rt build fails
configure.args-append   --enable-targets=x86,powerpc,arm

# use the system python27 if present
if {${os.platform} eq "darwin" && ${os.major} >= 11 && ${os.major} < 21} {
	set pythonfullpath   /usr/bin/python2.7
} else {
	set pythonfullpath   ${prefix}/bin/python2.7
	depends_lib-append   port:python27
}

if {${subport} eq "llvm-${llvm_version}"} {
    select.group        llvm
    select.file         ${filespath}/mp-${subport}
} elseif {${subport} eq "clang-${llvm_version}"} {
    select.group        clang
    select.file         ${filespath}/mp-${subport}

    configure.args-append --with-python=${pythonfullpath}
}

# llvm-3.5 and later requires a C++11 runtime
# Xcode 4.3's clang (318.x) fails per https://trac.macports.org/ticket/44161
# Xcode 4.5's clang (421.11.66) fails due to http://llvm.org/bugs/show_bug.cgi?id=20184
# Xcode 4.6.3's clang (425.0.28) fails due to http://trac.macports.org/ticket/46897
compiler.blacklist *gcc* {clang < 500}

# Override the normal compiler fallback list entirely since we have
# such specific requirements.
compiler.fallback   clang

# 3.4 is already needed to bootstrap libcxx, so is a good last resort
# when the system clang is too old.
if {${os.platform} eq "darwin" && ${os.major} < 16} {
    compiler.fallback-append macports-clang-3.4
}

if {${subport} eq "llvm-${llvm_version}" && [vercmp $xcodeversion 4.3] < 0 && [string match "*macports*" ${configure.compiler}]} {
    # 3.2.6's install_name_tool doesn't support load commands we might see with newer clang+ld64
    # 4.3 is just a guess here and should be updated if there are additional reports with other Xcode versions
    depends_build-append port:cctools
    depends_skip_archcheck-append cctools
}

platform darwin {
    # Note that we are forcing this choice.  This means that anything linking
    # against llvm-3.5 needs to also be using libc++.  This is possibly
    # problematic, but luckily there is just a limited set of such dependents.

    configure.cxx_stdlib libc++
    depends_lib-append port:libcxx
    supported_archs i386 x86_64

    pre-fetch {
        if {${os.major} < 11} {
            if {![file exists /usr/lib/libc++.dylib]} {
                ui_error "$name requires a C++11 runtime, which your configuration does not allow"
                error "unsupported configuration"
            }
        }
    }
}

variant universal {
    build.env-append \
        UNIVERSAL=1 \
        UNIVERSAL_ARCH=[get_canonical_archs]
    destroot.env-append \
        UNIVERSAL=1 \
        UNIVERSAL_ARCH=[get_canonical_archs]

    post-extract {
        # workaround a bug in Apple's shipped gcc driver-driver, patched in
        # ours with driverdriver-num_infiles.patch
        if {${configure.compiler} eq "gcc-4.0" ||
            ${configure.compiler} eq "gcc-4.2" ||
            ${configure.compiler} eq "llvm-gcc-4.2"} {
            system "echo \"static int ___ignoreme;\" > ${worksrcpath}/tools/llvm-shlib/ignore.c"
        }
    }
}

variant assertions description "Enable assertions for error detection (has performance impacts, especially on JIT)" {
    configure.args-delete --disable-assertions
    configure.args-append --enable-assertions
}

platform darwin {
    if {${build_arch} eq "i386"} {
        configure.pre_args-append --build=i686-apple-darwin${os.major}
    } elseif {${build_arch} eq "ppc"} {
        configure.pre_args-append --build=powerpc-apple-darwin${os.major}
    } elseif {${build_arch} eq "ppc64"} {
        configure.pre_args-append --build=powerpc64-apple-darwin${os.major}
    } else {
        configure.pre_args-append --build=${build_arch}-apple-darwin${os.major}
    }

    if {[string match "*ppc*" [get_canonical_archs]]} {
        # http://trac.macports.org/ticket/33987
        configure.args-append --with-optimize-option=-Os
        configure.optflags    -Os
    }

    if {${subport} eq "clang-${llvm_version}" && [vercmp $xcodeversion 5.0] < 0} {
        patchfiles-append leopard-no-asan.patch
    }

    if {${subport} eq "clang-${llvm_version}" && ${os.major} <= 9} {
        patchfiles-append leopard-no-blocks.patch
    }

    if {${os.major} < 11} {
        # Proxy for eliminating the dependency on native TLS
        # http://trac.macports.org/ticket/46887
        configure.args-append --disable-backtraces
    }
}

post-extract {
    # Get HTTP proxy arguments if required, assuming we can use the same proxy for all repositories
    set proxy_args [portfetch::svn_proxy_args http://llvm.org/svn/llvm-project/cfe/trunk]
    if {${subport} eq "llvm-${llvm_version}"} {
        if {[variant_isset polly]} {
            if {${worksrcdir} eq "trunk"} {
                system -W ${worksrcpath}/tools "svn ${proxy_args} co -r ${svn.revision} http://llvm.org/svn/llvm-project/polly/trunk polly"
            } elseif {${worksrcdir} eq "release_${llvm_version_no_dot}" } {
                system -W ${worksrcpath}/tools "svn ${proxy_args} co -r ${svn.revision} http://llvm.org/svn/llvm-project/polly/branches/release_${llvm_version_no_dot} polly"
            } else {
                file rename ${workpath}/polly-${version}.src ${worksrcpath}/tools/polly
            }
        }
    } elseif {${subport} eq "clang-${llvm_version}"} {
        if {${worksrcdir} eq "trunk"} {
            system -W ${worksrcpath}/tools "svn ${proxy_args} co -r ${svn.revision} http://llvm.org/svn/llvm-project/cfe/trunk clang"
            system -W ${worksrcpath}/projects "svn ${proxy_args} co -r ${compiler_rt_rev} http://llvm.org/svn/llvm-project/compiler-rt/trunk compiler-rt"
            system -W ${worksrcpath}/projects "svn ${proxy_args} co -r ${libcxx_rev} http://llvm.org/svn/llvm-project/libcxx/trunk libcxx"
            system -W ${worksrcpath}/tools/clang/tools "svn ${proxy_args} co -r ${clang-modernize_rev} http://llvm.org/svn/llvm-project/clang-tools-extra/trunk extra"
        } elseif {${worksrcdir} eq "release_${llvm_version_no_dot}" } {
            system -W ${worksrcpath}/tools "svn ${proxy_args} co -r ${svn.revision} http://llvm.org/svn/llvm-project/cfe/branches/release_${llvm_version_no_dot} clang"
            system -W ${worksrcpath}/projects "svn ${proxy_args} co -r ${compiler_rt_rev} http://llvm.org/svn/llvm-project/compiler-rt/branches/release_${llvm_version_no_dot} compiler-rt"
            system -W ${worksrcpath}/projects "svn ${proxy_args} co -r ${libcxx_rev} http://llvm.org/svn/llvm-project/libcxx/branches/release_${llvm_version_no_dot} libcxx"
            system -W ${worksrcpath}/tools/clang/tools "svn ${proxy_args} co -r ${clang-modernize_rev} http://llvm.org/svn/llvm-project/clang-tools-extra/branches/release_${llvm_version_no_dot} extra"
        } else {
            file rename ${workpath}/cfe-${version}.src ${worksrcpath}/tools/clang
            file rename ${workpath}/compiler-rt-${version}.src ${worksrcpath}/projects/compiler-rt
            file rename ${workpath}/libcxx-${version}.src ${worksrcpath}/projects/libcxx
            file rename ${workpath}/clang-tools-extra-${version}.src ${worksrcpath}/tools/clang/tools/extra
        }
    }
}

post-patch {
    if {${subport} eq "clang-${llvm_version}"} {
        reinplace "s|@@PREFIX@@|${prefix}|g" \
            ${worksrcpath}/projects/compiler-rt/make/platform/clang_darwin.mk \
            ${worksrcpath}/projects/compiler-rt/make/platform/clang_macho_embedded.mk
    }
}

post-destroot {
    file mkdir ${destroot}${prefix}/share/doc
    file rename ${destroot}${sub_prefix}/docs/llvm ${destroot}${prefix}/share/doc/${subport}

    foreach bin [glob ${destroot}${sub_prefix}/bin/*] {
        set bin_filename [string map "${sub_prefix} ${prefix}" ${bin}]-${suffix}
        set exec_path [string map "${destroot}${sub_prefix} ${sub_prefix}" ${bin}]

        xinstall -m 755 "${filespath}/llvm-bin" "${bin_filename}"
        reinplace "s:EXEC_PATH:${exec_path}:" "${bin_filename}"
    }

    if {${subport} eq "llvm-${llvm_version}"} {
        # r156389 (a5d2435409858728970202226d0bbbee508fe408) temporarilary removed llvm man pages
        #foreach man [glob ${destroot}${sub_prefix}/share/man/man1/*.1] {
        #    set basename [string map "${destroot}${sub_prefix}/share/man/man1/ {}" ${man}]
        #    file rename ${man} ${destroot}${prefix}/share/man/man1/[string map ".1 -${suffix}.1" ${basename}]
        #}
    } elseif {${subport} eq "clang-${llvm_version}"} {
        system "ditto ${worksrcpath}/projects/libcxx/include ${destroot}${sub_prefix}/lib/c++/v1"

        # http://trac.macports.org/ticket/33207
        ln -s ${prefix}/libexec/ld64/ld ${destroot}${sub_prefix}/bin/ld
    }
}

if {${subport} eq "llvm-${llvm_version}"} {
    variant polly description {Provide the polly polyhedral optimizer} {}

    # Unless upstream reverts to their old OCaml detection mechanism,
    # this variant will be broken until #46161 is resolved.
    variant ocaml description {Enable generation of OCaml binding} {
        depends_lib-append   port:ocaml

        configure.args-delete --enable-bindings=none
        configure.args-append --enable-bindings=ocaml

        destroot.args-append  OVERRIDE_libdir=${sub_prefix}/lib
    }
} elseif {${subport} eq "clang-${llvm_version}"} {
    if {[variant_isset assertions]} {
        # Need to match llvm +-assertions
        require_active_variants port:llvm-${llvm_version} assertions
    } else {
        # Need to match llvm +-assertions
        require_active_variants port:llvm-${llvm_version} {} assertions
    }

    if {${os.platform} eq "darwin" && ${os.major} >= 11} {
        variant analyzer description {Install clang static analyzer} {
            depends_run-append port:perl5

            post-patch {
                reinplace "s|/usr/bin/env perl|${prefix}/bin/perl5|g" \
                    ${worksrcpath}/tools/clang/tools/scan-build/ccc-analyzer \
                    ${worksrcpath}/tools/clang/tools/scan-build/c++-analyzer \
                    ${worksrcpath}/tools/clang/tools/scan-build/scan-build
                reinplace "s|/usr/bin/env python|${pythonfullpath}|g" \
                    ${worksrcpath}/tools/clang/tools/scan-build/set-xcode-analyzer \
                    ${worksrcpath}/tools/clang/tools/scan-view/scan-view
            }

            post-destroot {
                file mkdir ${destroot}${sub_prefix}/libexec
                file copy ${worksrcpath}/tools/clang/tools/scan-build ${destroot}${sub_prefix}/libexec/scan-build
                file copy ${worksrcpath}/tools/clang/tools/scan-view ${destroot}${sub_prefix}/libexec/scan-view

                file delete -force ${destroot}${sub_prefix}/libexec/scan-build/.svn
                file delete -force ${destroot}${sub_prefix}/libexec/scan-view/.svn
                file delete -force ${destroot}${sub_prefix}/libexec/scan-view/Resources/.svn

                ln -s ${sub_prefix}/libexec/scan-build/scan-build ${destroot}${sub_prefix}/bin/scan-build
                ln -s ${sub_prefix}/libexec/scan-view/scan-view ${destroot}${sub_prefix}/bin/scan-view
                ln -s ${sub_prefix}/bin ${destroot}${sub_prefix}/libexec/scan-build/bin

                xinstall -m 755 "${filespath}/llvm-bin" "${destroot}${prefix}/bin/scan-build-${suffix}"
                reinplace "s:EXEC_PATH:${sub_prefix}/bin/scan-build:" "${destroot}${prefix}/bin/scan-build-${suffix}"

                xinstall -m 755 "${filespath}/llvm-bin" "${destroot}${prefix}/bin/scan-view-${suffix}"
                reinplace "s:EXEC_PATH:${sub_prefix}/bin/scan-view:" "${destroot}${prefix}/bin/scan-view-${suffix}"
            }
        }
    }

    variant openmp description {Use MacPorts' provided libomp with -fopenmp} {
        configure.args-append \
            --with-clang-default-openmp-runtime=libomp
        depends_lib-append      port:libomp
        patchfiles-append       openmp-locations.patch

        post-patch {
            reinplace "s|@@PREFIX@@|${prefix}|" \
                ${worksrcpath}/tools/clang/lib/Driver/Tools.cpp
        }
    }

    post-patch {
        reinplace "s|@CLANG_FORMAT_PATH@|${prefix}/bin/clang-format-${suffix}|g" \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-bbedit.applescript \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-diff.py            \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format-sublime.py         \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format.el                 \
            ${worksrcpath}/tools/clang/tools/clang-format/clang-format.py
    }

    post-destroot {
        file mkdir ${destroot}${sub_prefix}/libexec
        file copy ${worksrcpath}/tools/clang/tools/clang-format ${destroot}${sub_prefix}/libexec/clang-format

        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/.svn
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/Makefile
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/Release+Debug+Asserts
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/CMakeLists.txt
        file delete -force ${destroot}${sub_prefix}/libexec/clang-format/ClangFormat.cpp
    }

    if {${os.platform} eq "darwin" && ${os.major} > 17} {
        depends_build
        depends_lib
        depends_run
        archive_sites
        known_fail yes
        pre-fetch {
            ui_error "${subport} is not supported on macOS Mojave or newer."
            return -code error {unsupported platform}
        }
    }
}

livecheck.type          none
