# llvm-3.4 was the last version to not require C++11, thus it is needed
# to build libc++ in order to support C++11 in order to build newer
# versions of llvm on older platforms.  Bootstrapping is fun...

PortSystem              1.0

set llvm_version        3.4
set llvm_version_no_dot 34
name                    llvm-${llvm_version}
revision                17
subport                 clang-${llvm_version} { revision 19 }
set suffix              mp-${llvm_version}
set sub_prefix          ${prefix}/libexec/llvm-${llvm_version}
dist_subdir             llvm
categories              lang
license                 NCSA
maintainers             {jeremyhu @jeremyhu} {larryv @larryv}

#see https://trac.macports.org/ticket/59677
#see https://trac.macports.org/ticket/58779
if { !${use_xcode} && ![file exists ${configure.developer_dir}/SDKs] } {
    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:libffi port:ncurses port:zlib
    depends_build       port:python27
    depends_run         bin:perl:perl5 port:llvm_select-${llvm_version}
} 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} port:python27
    depends_run         port:clang_select-${llvm_version} port:ld64
    depends_build       port:cctools
    depends_skip_archcheck-append cctools ld64

    depends_lib-append  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
    }
}

set python27 ${prefix}/bin/python2.7

if {${os.platform} eq "darwin" && ${os.major} < 11 && ${cxx_stdlib} eq "libc++"} {
    configure.cxx_stdlib        libstdc++
    # Have to also use bootstrap versions of deps that use libstdc++ in
    # order to be able to build libc++.
    depends_build-replace       port:python27 port:python27-bootstrap
    depends_lib-replace         port:python27 port:python27-bootstrap
    depends_lib-delete          port:ncurses

    set python27 ${prefix}/libexec/python27-bootstrap/bin/python2.7
}

version                 ${llvm_version}.2
epoch                   1
master_sites            https://releases.llvm.org/${version} https://releases.llvm.org/${llvm_version}
extract.suffix          .tar.gz
distfiles               llvm-${version}.src${extract.suffix}
worksrcdir              llvm-${version}.src

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

checksums           llvm-3.4.2.src.tar.gz \
                    rmd160  5fab44850977afccee34b21c6d339bc8dea21fce \
                    sha256  17038d47069ad0700c063caed76f0c7259628b0e79651ce2b540d506f2f1efd7 \
                    cfe-3.4.2.src.tar.gz \
                    rmd160  f6b177408f5f9d3a453d41f1f60534f8e1e2845b \
                    sha256  5ba6f5772f8d00f445209356a7daf83c5bca2da5acd10de517ad2359ae95bc10 \
                    compiler-rt-3.4.src.tar.gz \
                    rmd160  530225a44fa743f80df759e5354a0854eb422306 \
                    sha256  f37c89b1383ce462d47537a0245ac798600887a9be9f63073e16b79ed536ab5c \
                    libcxx-3.4.2.src.tar.gz \
                    rmd160  7984caf2d055ea967544107ae1f948c77556d764 \
                    sha256  826543ee2feb5d3313b0705145255ebb2ed8d52eace878279c2525ccde6e727c \
                    clang-tools-extra-3.4.src.tar.gz \
                    rmd160  8af0af0ead94bd50b1e6cbdcde5c4770bba5de0d \
                    sha256  ba85187551ae97fe1c8ab569903beae5ff0900e21233e5eb5389f6ceab1028b4

patch.pre_args-replace  -p0 -p1

patchfiles \
        0001-MacPorts-Only-Update-install-targets-for-clang-subpo.patch \
        0003-MacPorts-Only-Fix-sample-project-regex-to-work-with-.patch \
        0004-Set-the-Mach-O-CPU-Subtype-to-ppc7400-when-targeting.patch \
        0005-_CS_DARWIN_USER-macros-available-on-darwin-9.-Thanks.patch \
        0006-Fix-dylib-install-name-when-building-on-Tiger.patch \
        0007-Define-EXC_MASK_CRASH-and-MACH_EXCEPTION_CODES-if-th.patch \
        llvm-skip-unittests.patch \
        regex_impl.h.patch \
        patch-macports-flags.diff

if {${subport} eq "clang-${llvm_version}"} {
    patchfiles-append \
        1001-MacPorts-Only-Prepare-clang-format-for-replacement-w.patch \
        1002-MacPorts-Only-Fix-name-of-scan-view-executable-insid.patch \
        1003-MacPorts-Only-Fix-libclang_rt-dylib-ids.patch \
        1004-MacPorts-Only-Relocate-clang-resources-using-llvm-ve.patch \
        1005-Call-powerpc-darwin-external-tools-with-arch-ppc.patch \
        1006-Default-to-ppc7400-for-OSX-10.5.patch \
        1007-reinstate-fno-objc-legacy-dispatch-behavior-when-the.patch \
        1008-Change-__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__.patch \
        1009-Only-call-setpriority-PRIO_DARWIN_THREAD-0-PRIO_DARW.patch \
        1010-Fix-dylib-install-name-when-building-on-Tiger.patch \
        1011-Make-verbose-clang-builds-also-build-compiler_rt-ver.patch \
        1012-Fixup-libstdc-header-search-paths-for-older-versions.patch \
        1234-clang-stop-on-linker-error.patch \
        2001-MacPorts-Only-Comment-out-SL-cctools-workaround.patch \
        2002-On-darwin-build-ppc-slices-of-the-compiler-runtime-i.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

    # Introduces a failure during build (-arch ?? passed to ld), to be investigated:
    patchfiles-delete \
        1005-Call-powerpc-darwin-external-tools-with-arch-ppc.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      --prefix=${sub_prefix}
configure.args          --enable-bindings=none --enable-libffi --enable-shared --enable-jit \
                        --enable-optimized --disable-profiling --enable-pic \
                        --disable-debug-symbols --disable-debug-runtime \
                        --disable-assertions --with-python=${python27}

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

# g++-4.0 fails to build some of the newer C++ for ppc. Intel looks ok, but I prefer using gcc-4.2 for consistency
# Leopard's gcc-4.2 (5577) miscompiles llvm-3.4 for i386.
# Xcode 4.3's clang (318.x) fails per https://trac.macports.org/ticket/44161
compiler.blacklist gcc-4.0 {gcc-4.2 <= 5577} {clang < 421}

# avoid dependency cycles
compiler.blacklist-append   macports-clang-*

platform darwin {
    supported_archs ppc ppc64 i386 x86_64
}

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}" && ${os.major} <= 9} {
        patchfiles-append leopard-no-asan.patch leopard-no-blocks.patch
    }

    # fix build on a G3 #63304 -- absence of Altivec is not automatically detected
    if {${subport} eq "clang-${llvm_version}" && ${os.major} < 9 && ${build_arch} eq "ppc"} {
        if {[catch {sysctl hw.vectorunit} result] || $result == 0} {

            # if this machine is a G3, force a local build so we don't download a buildbot-built
            # version possibly built on a G4+ or cross-compiled from an Intel system
            archive_sites

            patchfiles-append 1013-clang-lib-lex-dont-assume-altivec.diff
        }
    }

    # TODO: The llvm build system sets a 10.1 deployment target on Yosemite
    if {[vercmp ${macosx_deployment_target} 10.10] >= 0} {
        macosx_deployment_target 10.9
    }

    if {${os.major} < 10} {
        post-patch {
            reinplace "/TARGETS_TO_BUILD=/s/R600//" ${worksrcpath}/configure
        }
    }

    if {${os.major} < 9} {
        # Tiger's DevTools make has issues with the nested ifs in compiler-rt
        depends_run-append      port:gmake
        build.cmd               ${prefix}/bin/gmake

        post-configure {
            reinplace "/^RPATH/s/=.*/=/" ${configure.dir}/Makefile.config
        }
    }
}

post-extract {
    if {${subport} eq "clang-${llvm_version}"} {
        file rename ${workpath}/cfe-${version}.src ${worksrcpath}/tools/clang
        file rename ${workpath}/compiler-rt-${llvm_version} ${worksrcpath}/projects/compiler-rt
        file rename ${workpath}/libcxx-${version}.src ${worksrcpath}/projects/libcxx
        file rename ${workpath}/clang-tools-extra-${llvm_version} ${worksrcpath}/tools/clang/tools/extra
    }
}

post-patch {
    if {${subport} eq "llvm-${llvm_version}"} {
        reinplace "s|/usr/bin/env python|${python27}|g" \
            ${worksrcpath}/utils/llvm-build/llvm-build
    } elseif {${subport} eq "clang-${llvm_version}"} {
        # http://trac.macports.org/ticket/33272
        if {![variant_isset arm_runtime]} {
            reinplace {/^SubDirs/ s/arm//} ${worksrcpath}/projects/compiler-rt/lib/Makefile.mk
            reinplace {/^UniversalArchs/ s/arm[^ )]* *//g} ${worksrcpath}/projects/compiler-rt/make/platform/clang_darwin.mk

            reinplace {/cc_kext_ios5/ s/^/#/} ${worksrcpath}/projects/compiler-rt/make/platform/clang_darwin.mk
            reinplace {s/cc_kext_ios5.a//} ${worksrcpath}/tools/clang/runtime/compiler-rt/Makefile
        }

        reinplace {s/VERBOSE := 0/VERBOSE := 1/} ${worksrcpath}/projects/compiler-rt/make/config.mk

        reinplace "s|@@PREFIX@@|${prefix}|g" \
            ${worksrcpath}/projects/compiler-rt/make/platform/clang_darwin.mk \
            ${worksrcpath}/projects/compiler-rt/make/platform/clang_darwin_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 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}"} {
    variant arm_runtime description {Build and install the arm runtime for iOS development (requires iOS SDK)} {}

    # The iOS SDK was shipped with all Xcode releases after 4.0
    if {[info exists xcodeversion] && [vercmp "4.0" ${xcodeversion}] <= 0} {
       default_variants-append +arm_runtime
    }

    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|${python27}|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}"
        }
    }

    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
    }

    platforms {darwin < 16}
}

livecheck.type          none
