cc.py 5.27 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17
"""Util to invoke c++ compilers in the system."""
18
# pylint: disable=invalid-name
19 20 21
from __future__ import absolute_import as _abs
import sys
import subprocess
Hu Shiwen committed
22
import os
23 24

from .._ffi.base import py_str
Hu Shiwen committed
25 26 27
from .util import tempdir


28 29 30 31
def create_shared(output,
                  objects,
                  options=None,
                  cc="g++"):
32 33 34 35
    """Create shared library.

    Parameters
    ----------
36
    output : str
37 38 39 40 41
        The target shared library.

    objects : list
        List of object files.

42 43
    options : list
        The list of additional options string.
44

45
    cc : str, optional
46 47
        The compile string.
    """
48
    if sys.platform == "darwin" or sys.platform.startswith("linux"):
Hu Shiwen committed
49 50 51 52 53 54 55
        _linux_shared(output, objects, options, cc)
    elif sys.platform == "win32":
        _windows_shared(output, objects, options)
    else:
        raise ValueError("Unsupported platform")


56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
# assign so as default output format
create_shared.output_format = "so" if sys.platform != "win32" else "dll"


def cross_compiler(cc, options=None, output_format="so"):
    """Create a cross compiler function.

    Parameters
    ----------
    cc :  str
        The cross compiler name.

    options : list, optional
        List of additional optional string.

    output_format : str, optional
        Library output format.

    Returns
    -------
    fcompile : function
        A compilation function that can be passed to export_library.
    """
    def _fcompile(outputs, objects, opts=None):
        opts = opts if opts else []
        if options:
            opts += options
        _linux_shared(outputs, objects, opts, cc=cc)
    _fcompile.output_format = output_format
    return _fcompile


Hu Shiwen committed
88
def _linux_shared(output, objects, options, cc="g++"):
89
    cmd = [cc]
90
    cmd += ["-shared", "-fPIC"]
91 92
    if sys.platform == "darwin":
        cmd += ["-undefined", "dynamic_lookup"]
93 94 95 96 97
    cmd += ["-o", output]
    if isinstance(objects, str):
        cmd += [objects]
    else:
        cmd += objects
98 99 100
    if options:
        cmd += options
    proc = subprocess.Popen(
101
        cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
102
    (out, _) = proc.communicate()
Hu Shiwen committed
103 104
    if proc.returncode != 0:
        msg = "Compilation error:\n"
105
        msg += py_str(out)
Hu Shiwen committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        raise RuntimeError(msg)


def _windows_shared(output, objects, options):
    cl_cmd = ["cl"]
    cl_cmd += ["-c"]
    if isinstance(objects, str):
        objects = [objects]
    cl_cmd += objects
    if options:
        cl_cmd += options

    temp = tempdir()
    dllmain_path = temp.relpath("dllmain.cc")
    with open(dllmain_path, "w") as dllmain_obj:
        dllmain_obj.write('#include <windows.h>\
BOOL APIENTRY DllMain( HMODULE hModule,\
                       DWORD  ul_reason_for_call,\
                       LPVOID lpReserved)\
{return TRUE;}')

    cl_cmd += [dllmain_path]

    temp_path = dllmain_path.replace("dllmain.cc", "")
    cl_cmd += ["-Fo:" + temp_path]
131 132 133 134 135
    try:
        proc = subprocess.Popen(
            cl_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        (out, _) = proc.communicate()
    except FileNotFoundError:
Martin Boos committed
136
        raise RuntimeError("Can not find cl.exe,"
137
                           "please run this in Vistual Studio Command Prompt.")
Hu Shiwen committed
138 139
    if proc.returncode != 0:
        msg = "Compilation error:\n"
140
        msg += py_str(out)
Hu Shiwen committed
141
        raise RuntimeError(msg)
Martin Boos committed
142
    link_cmd = ["lld-link"]
Hu Shiwen committed
143 144 145 146 147 148 149 150 151 152 153 154 155
    link_cmd += ["-dll", "-FORCE:MULTIPLE"]

    for obj in objects:
        if obj.endswith(".cc"):
            (_, temp_file_name) = os.path.split(obj)
            (shot_name, _) = os.path.splitext(temp_file_name)
            link_cmd += [os.path.join(temp_path, shot_name + ".obj")]
        if obj.endswith(".o"):
            link_cmd += [obj]

    link_cmd += ["-EXPORT:__tvm_main__"]
    link_cmd += [temp_path + "dllmain.obj"]
    link_cmd += ["-out:" + output]
156

157 158 159 160 161
    try:
        proc = subprocess.Popen(
            link_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        (out, _) = proc.communicate()
    except FileNotFoundError:
Martin Boos committed
162 163 164 165 166
        raise RuntimeError("Can not find the LLVM linker for Windows (lld-link.exe)."
                           "Make sure it's installed"
                           " and the installation directory is in the %PATH% environment "
                           "variable. Prebuilt binaries can be found at: https://llvm.org/"
                           "For building the linker on your own see: https://lld.llvm.org/#build")
167
    if proc.returncode != 0:
168
        msg = "Compilation error:\n"
169
        msg += py_str(out)
Hu Shiwen committed
170

171
        raise RuntimeError(msg)