verilog.py 8.89 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
"""Verilog simulator modules."""
18 19 20 21 22
from __future__ import absolute_import

import subprocess
import sys
import os
23
import ctypes
24 25

from .. import _api_internal
26
from .._ffi.base import string_types
27 28
from .._ffi.node import NodeBase, register_node
from .._ffi.function import register_func
29
from . import util
30 31 32 33 34 35 36 37

@register_node
class VPISession(NodeBase):
    """Verilog session"""
    def __init__(self, handle):
        super(VPISession, self).__init__(handle)
        self.proc = None
        self.execpath = None
38
        self.yield_callbacks = []
39 40 41

    def __del__(self):
        self.proc.kill()
42 43 44 45
        try:
            super(VPISession, self).__del__()
        except AttributeError:
            pass
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

    def arg(self, index):
        """Get handle passed to host session.

        Parameters
        ----------
        index : int
            The index value.

        Returns
        -------
        handle : VPIHandle
            The handle
        """
        return _api_internal._vpi_SessGetArg(self, index)

    def __getitem__(self, name):
        if not isinstance(name, string_types):
            raise ValueError("have to be string types")
        return _api_internal._vpi_SessGetHandleByName(self, name)

    def __getattr__(self, name):
        return _api_internal._vpi_SessGetHandleByName(self, name)

70
    def yield_until_next_cycle(self):
71
        """Yield until next posedge"""
72 73
        for f in self.yield_callbacks:
            f()
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        return _api_internal._vpi_SessYield(self)

    def shutdown(self):
        """Shutdown the simulator"""
        return _api_internal._vpi_SessShutdown(self)


@register_node
class VPIHandle(NodeBase):
    """Handle to a verilog variable."""
    def __init__(self, handle):
        super(VPIHandle, self).__init__(handle)
        self._name = None
        self._size = None

    def get_int(self):
        """Get integer value from handle.

        Returns
        -------
        value : int
        """
        return _api_internal._vpi_HandleGetInt(self)

    def put_int(self, value):
        """Put integer value to handle.

        Parameters
        ----------
        value : int
            The value to put
        """
        return _api_internal._vpi_HandlePutInt(self, value)

    @property
    def name(self):
        if self._name is None:
            self._name = _api_internal._vpi_HandleGetName(self)
        return self._name

    @property
    def size(self):
        if self._size is None:
            self._size = _api_internal._vpi_HandleGetSize(self)
        return self._size

    def __getitem__(self, name):
        if not isinstance(name, string_types):
            raise ValueError("have to be string types")
        return _api_internal._vpi_HandleGetHandleByName(self, name)

    def __getattr__(self, name):
        return _api_internal._vpi_HandleGetHandleByName(self, name)


def _find_vpi_path():
130
    curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))
131 132 133 134 135 136
    api_path = os.path.join(curr_path, '../../../lib/')
    vpi_path = [curr_path, api_path]
    vpi_path = [os.path.join(p, 'tvm_vpi.vpi') for p in vpi_path]
    vpi_found = [p for p in vpi_path if os.path.exists(p) and os.path.isfile(p)]
    if vpi_found:
        return os.path.dirname(vpi_found[0])
137
    raise ValueError("Cannot find tvm_vpi.vpi, make sure you did `make verilog`")
138 139 140

def search_path():
    """Get the search directory."""
141
    curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))
142
    ver_path = [os.path.join(curr_path, '../../../verilog/')]
143 144
    ver_path += [os.path.join(curr_path, '../../../tests/verilog/unittest/')]
    ver_path += [os.path.join(curr_path, '../../../tests/verilog/integration/')]
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    return ver_path


def find_file(file_name):
    """Find file in the search directories.

    Parameters
    ----------
    file_name : str
        The file name

    Return
    ------
    file_name : str
        The absolute path to the file, raise Error if cannot find it.
    """
    ver_path = search_path()
    flist = [os.path.join(p, file_name) for p in ver_path]
    found = [p for p in flist if os.path.exists(p) and os.path.isfile(p)]
164
    if not found:
165
        raise ValueError("Cannot find %s in %s" % (file_name, flist))
166
    return found[0]
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200


def compile_file(file_name, file_target, options=None):
    """Compile verilog via iverilog

    Parameters
    ----------
    file_name : str or list of str
        The cuda code.

    file_target : str
        The target file.
    """
    cmd = ["iverilog"]
    for path in search_path():
        cmd += ["-I%s" % path]

    cmd += ["-o", file_target]
    if options:
        cmd += options

    if isinstance(file_name, string_types):
        file_name = [file_name]
    cmd += file_name
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)
    (out, _) = proc.communicate()

    if proc.returncode != 0:
        raise ValueError("Compilation error:\n%s" % out)


201
def session(file_names, codes=None):
202 203 204 205
    """Create a new iverilog session by compile the file.

    Parameters
    ----------
206
    file_names : str or list of str
207 208
        The name of the file

209 210 211
    codes : str or list of str
        The code in str.

212 213 214 215 216
    Returns
    -------
    sess : VPISession
        The created session.
    """
217 218
    if isinstance(file_names, string_types):
        file_names = [file_names]
219
    path = util.tempdir()
220 221 222 223 224 225 226 227 228 229

    if codes:
        if isinstance(codes, (list, tuple)):
            codes = '\n'.join(codes)
        fcode = path.relpath("temp_code.v")
        with open(fcode, "w") as out_file:
            out_file.write(codes)
        file_names.append(fcode)

    for name in file_names:
230 231 232
        if not os.path.exists(name):
            raise ValueError("Cannot find file %s" % name)

233 234
    target = path.relpath(os.path.basename(file_names[0].rsplit(".", 1)[0]))
    compile_file(file_names, target)
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    vpi_path = _find_vpi_path()

    cmd = ["vvp"]
    cmd += ["-M", vpi_path]
    cmd += ["-m", "tvm_vpi"]
    cmd += [target]
    env = os.environ.copy()

    read_device, write_host = os.pipe()
    read_host, write_device = os.pipe()

    if sys.platform == "win32":
        import msvcrt
        env['TVM_DREAD_PIPE'] = str(msvcrt.get_osfhandle(read_device))
        env['TVM_DWRITE_PIPE'] = str(msvcrt.get_osfhandle(write_device))
        read_host = msvcrt.get_osfhandle(read_host)
        write_host = msvcrt.get_osfhandle(write_host)
    else:
        env['TVM_DREAD_PIPE'] = str(read_device)
        env['TVM_DWRITE_PIPE'] = str(write_device)

    env['TVM_HREAD_PIPE'] = str(read_host)
    env['TVM_HWRITE_PIPE'] = str(write_host)

259 260 261 262 263 264 265 266 267 268
    try:
        # close_fds does not work well for all python3
        # Use pass_fds instead.
        # pylint: disable=unexpected-keyword-arg
        pass_fds = (read_device, write_device, read_host, write_host)
        proc = subprocess.Popen(cmd, pass_fds=pass_fds, env=env)
    except TypeError:
        # This is effective for python2
        proc = subprocess.Popen(cmd, close_fds=False, env=env)

269 270 271 272 273 274 275 276
    # close device side pipe
    os.close(read_device)
    os.close(write_device)

    sess = _api_internal._vpi_SessMake(read_host, write_host)
    sess.proc = proc
    sess.execpath = path
    return sess
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316


@register_func
def tvm_callback_verilog_simulator(code, *args):
    """Callback by TVM runtime to invoke verilog simulator

    Parameters
    ----------
    code : str
        The verilog code to be simulated

    args : list
        Additional arguments to be set.
    """
    libs = [
        find_file("tvm_vpi_mmap.v")
    ]
    sess = session(libs, code)
    for i, value in enumerate(args):
        vpi_h = sess.main["tvm_arg%d" % i]
        if isinstance(value, ctypes.c_void_p):
            int_value = int(value.value)
        elif isinstance(value, int):
            int_value = value
        else:
            raise ValueError(
                "Do not know how to handle value type %s" % type(value))
        vpi_h.put_int(int_value)

    rst = sess.main.rst
    done = sess.main.done
    # start driving
    rst.put_int(1)
    sess.yield_until_next_cycle()
    rst.put_int(0)
    sess.yield_until_next_cycle()
    while not done.get_int():
        sess.yield_until_next_cycle()
    sess.yield_until_next_cycle()
    sess.shutdown()