python_code
stringlengths 0
4.04M
| repo_name
stringlengths 7
58
| file_path
stringlengths 5
147
|
---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import sys
from io import StringIO
from typing import Iterator
class CapturedOutput:
def __init__(self):
self.stdout = StringIO()
self.stderr = StringIO()
@contextlib.contextmanager
def capture_output() -> Iterator[CapturedOutput]:
"""Context manager to temporarily capture stdout/stderr."""
stdout, stderr = sys.stdout, sys.stderr
try:
captured = CapturedOutput()
sys.stdout, sys.stderr = captured.stdout, captured.stderr
yield captured
finally:
sys.stdout, sys.stderr = stdout, stderr
captured.stdout = captured.stdout.getvalue()
captured.stderr = captured.stderr.getvalue()
|
CompilerGym-development
|
compiler_gym/util/capture_output.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import functools
from typing import Any, Callable
def memoized_property(func: Callable[..., Any]) -> Callable[..., Any]:
"""A property decorator that memoizes the result.
This is used to memoize the results of class properties, to be used when
computing the property value is expensive.
:param func: The function which should be made to a property.
:returns: The decorated property function.
"""
attribute_name = "_memoized_property_" + func.__name__
@property
@functools.wraps(func)
def decorator(self):
if not hasattr(self, attribute_name):
setattr(self, attribute_name, func(self))
return getattr(self, attribute_name)
return decorator
def frozen_class(cls):
"""Prevents setting attributes on a class after construction.
Wrap a class definition to declare it frozen:
@frozen_class class MyClass:
def __init__(self):
self.foo = 0
Any attempt to set an attribute outside of construction will then raise an
error:
>>> c = MyClass()
>>> c.foo = 5
>>> c.bar = 10
TypeError
"""
cls._frozen = False
def frozen_setattr(self, key, value):
if self._frozen and not hasattr(self, key):
raise TypeError(
f"Cannot set attribute {key} on frozen class {cls.__name__}"
)
object.__setattr__(self, key, value)
def init_decorator(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.__frozen = True
return wrapper
cls.__setattr__ = frozen_setattr
cls.__init__ = init_decorator(cls.__init__)
return cls
|
CompilerGym-development
|
compiler_gym/util/decorators.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""A consistent way to interpret a user-specified environment from commandline flags."""
import sys
from contextlib import contextmanager
from pathlib import Path
from typing import Optional, Union
import gym
from absl import app, flags
from compiler_gym.envs import CompilerEnv
from compiler_gym.service import ConnectionOpts
from compiler_gym.service.proto import Benchmark
from compiler_gym.util.registration import COMPILER_GYM_ENVS
flags.DEFINE_string(
"env",
None,
"The name of an environment to use. The environment must be registered with "
"gym.",
)
flags.DEFINE_string(
"service",
None,
"If set, this specifies the hostname and port of a service to connect to, "
"rather than creating a new environment. Use the format <hostname>:<port>. "
"Supersedes --local_service_binary.",
)
flags.DEFINE_string(
"local_service_binary",
None,
"If set, this specifies the path of a local service binary to run to "
"provide the environment service, rather than the default service binary.",
)
flags.DEFINE_string(
"observation",
None,
"The name of a observation space to use. If set, this overrides any "
"default set by the environment.",
)
flags.DEFINE_string(
"reward",
None,
"The name of a reward space to use. If set, this overrides any default "
"set by the environment.",
)
flags.DEFINE_boolean(
"ls_env",
False,
"Print the list of available environments that can be passed to --env and exit.",
)
# Connection settings.
flags.DEFINE_float(
"service_rpc_call_max_seconds",
300,
"Service configuration option. Limits the maximum number of seconds to wait "
"for a service RPC to return a response.",
)
flags.DEFINE_float(
"service_init_max_seconds",
10,
"Service configuration option. Limits the maximum number of seconds to wait "
"to establish a connection to a service.",
)
flags.DEFINE_integer(
"service_init_max_attempts",
5,
"Service configuration option. Limits the maximum number of attempts to "
"initialize a service.",
)
flags.DEFINE_float(
"local_service_port_init_max_seconds",
10,
"Service configuration option. Limits the maximum number of seconds to wait "
"for a local service to write a port.txt file on initialization.",
)
flags.DEFINE_float(
"local_service_exit_max_seconds",
10,
"Service configuration option. Limits the maximum number of seconds to wait "
"for a local service to terminate on close.",
)
flags.DEFINE_float(
"service_rpc_init_max_seconds",
3,
"Service configuration option. Limits the number of seconds to wait for an "
"RPC connection to establish on initialization.",
)
FLAGS = flags.FLAGS
def connection_settings_from_flags(
service_url: str = None, local_service_binary: Path = None
) -> ConnectionOpts:
"""Returns either the name of the benchmark, or a Benchmark message."""
return ConnectionOpts(
rpc_call_max_seconds=FLAGS.service_rpc_call_max_seconds,
init_max_seconds=FLAGS.service_init_max_seconds,
init_max_attempts=FLAGS.service_init_max_attempts,
local_service_port_init_max_seconds=FLAGS.local_service_port_init_max_seconds,
local_service_exit_max_seconds=FLAGS.local_service_exit_max_seconds,
rpc_init_max_seconds=FLAGS.service_rpc_init_max_seconds,
)
def env_from_flags(benchmark: Optional[Union[str, Benchmark]] = None) -> CompilerEnv:
if FLAGS.ls_env:
print("\n".join(sorted(COMPILER_GYM_ENVS)))
sys.exit(0)
connection_settings = connection_settings_from_flags()
if not FLAGS.env:
raise app.UsageError("--env must be set")
init_opts = {
"benchmark": benchmark,
"connection_settings": connection_settings,
}
if FLAGS.local_service_binary:
init_opts["service"] = Path(FLAGS.service)
if FLAGS.service:
init_opts["service"] = FLAGS.service
env = gym.make(FLAGS.env, **init_opts)
if FLAGS.observation:
env.observation_space = FLAGS.observation
if FLAGS.reward:
env.reward_space = FLAGS.reward
return env
@contextmanager
def env_session_from_flags(
benchmark: Optional[Union[str, Benchmark]] = None
) -> CompilerEnv:
with env_from_flags(benchmark=benchmark) as env:
yield env
|
CompilerGym-development
|
compiler_gym/util/flags/env_from_flags.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from absl import flags
flags.DEFINE_integer("episode_length", 5, "The number of steps in each episode.")
|
CompilerGym-development
|
compiler_gym/util/flags/episode_length.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from absl import flags
flags.DEFINE_string(
"output_dir",
None,
"The directory to read and write files to.",
)
|
CompilerGym-development
|
compiler_gym/util/flags/output_dir.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from multiprocessing import cpu_count
from absl import flags
flags.DEFINE_integer("nproc", cpu_count(), "The number of parallel processes to run.")
|
CompilerGym-development
|
compiler_gym/util/flags/nproc.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from absl import flags
flags.DEFINE_float("learning_rate", 0.008, "The learning rate for training.")
|
CompilerGym-development
|
compiler_gym/util/flags/learning_rate.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from absl import flags
flags.DEFINE_integer("seed", 0xCC, "Random state initializer.")
|
CompilerGym-development
|
compiler_gym/util/flags/seed.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""A consistent way to interpret a user-specified benchmark from commandline flags."""
from pathlib import Path
from typing import Optional, Union
from absl import flags
from compiler_gym.datasets import Benchmark
flags.DEFINE_string(
"benchmark",
None,
"The URI of the benchmark to use. Use the benchmark:// scheme to "
"reference named benchmarks, or the file:/// scheme to reference paths "
"to program data. If no scheme is specified, benchmark:// is implied.",
)
FLAGS = flags.FLAGS
def benchmark_from_flags() -> Optional[Union[Benchmark, str]]:
"""Returns either the name of the benchmark, or a Benchmark message."""
if FLAGS.benchmark:
if FLAGS.benchmark.startswith("file:///"):
path = Path(FLAGS.benchmark[len("file:///") :])
uri = f"benchmark://user-v0/{path}"
return Benchmark.from_file(uri=uri, path=path)
else:
return FLAGS.benchmark
else:
# No benchmark was specified.
return None
|
CompilerGym-development
|
compiler_gym/util/flags/benchmark_from_flags.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from absl import flags
flags.DEFINE_integer("episodes", 2000, "The number of episodes to run.")
|
CompilerGym-development
|
compiler_gym/util/flags/episodes.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This program can be used to query and run the CompilerGym services.
Listing available environments
------------------------------
List the environments that are available using:
.. code-block::
$ python -m compiler_gym.bin.service --ls_env
Querying the capabilities of a service
--------------------------------------
Query the capabilities of a service using:
.. code-block::
$ python -m compiler_gym.bin.service --env=<env>
For example:
.. code-block::
$ python -m compiler_gym.bin.service --env=llvm-v0
Datasets
--------
+----------------------------+--------------------------+------------------------------+
| Dataset | Num. Benchmarks [#f1]_ | Description |
+============================+==========================+==============================+
| benchmark://anghabench-v0 | 1,042,976 | Compile-only C/C++ functions |
+----------------------------+--------------------------+------------------------------+
| benchmark://blas-v0 | 300 | Basic linear algebra kernels |
+----------------------------+--------------------------+------------------------------+
...
Observation Spaces
------------------
+--------------------------+----------------------------------------------+
| Observation space | Shape |
+==========================+==============================================+
| Autophase | `Box(0, 9223372036854775807, (56,), int64)` |
+--------------------------+----------------------------------------------+
| AutophaseDict | `Dict(ArgsPhi:int<0,inf>, BB03Phi:int<0,...` |
+--------------------------+----------------------------------------------+
| BitcodeFile | `str_list<>[0,4096.0])` |
+--------------------------+----------------------------------------------+
...
The output is tabular summaries of the environment's datasets, observation
spaces, reward spaces, and action spaces, using reStructuredText syntax
(https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#tables).
To query the capabilities of an unmanaged service, use :code:`--service`. For
example, query a service running the :code:`llvm-v0` environment at
:code:`localhost:8080` using:
.. code-block::
$ python -m compiler_gym.bin.service --env=llvm-v0 --service=localhost:8080
To query the capability of a binary that implements the RPC service interface,
use the :code:`--local_service_binary` flag:
.. code-block::
$ python -m compiler_gym.bin.service --env=llvm-v0 --local_service_binary=/path/to/service/binary
Running a Service
-----------------
This module can also be used to launch a service that can then be connected to
by other environments. Start a service by specifying a port number using:
.. code-block::
$ python -m compiler_gym.bin.service --env=llvm-v0 --run_on_port=7777
Environment can connect to this service by passing the :code:`<hostname>:<port>`
address during environment initialization time. For example, in python:
>>> env = compiler_gym.make("llvm-v0", service="localhost:7777")
Or at the command line:
.. code-block::
$ python -m compiler_gym.bin.random_search --env=llvm-v0 --service=localhost:7777
"""
import signal
import sys
from typing import Iterable
import gym
from absl import app, flags
from compiler_gym.datasets import Dataset
from compiler_gym.envs import CompilerEnv
from compiler_gym.service.connection import ConnectionOpts
from compiler_gym.spaces import Commandline, NamedDiscrete
from compiler_gym.util.flags.env_from_flags import env_from_flags
from compiler_gym.util.tabulate import tabulate
from compiler_gym.util.truncate import truncate
flags.DEFINE_string(
"heading_underline_char",
"-",
"The character to repeat to underline headings.",
)
flags.DEFINE_integer(
"run_on_port",
None,
"Is specified, serve an instance of the service on the requested port. "
"This never terminates.",
)
FLAGS = flags.FLAGS
def header(message: str):
underline = FLAGS.heading_underline_char * (
len(message) // len(FLAGS.heading_underline_char)
)
return f"\n\n{message}\n{underline}\n"
def shape2str(shape, n: int = 80):
string = str(shape)
if len(string) > n:
return f"`{string[:n-4]}` ..."
return f"`{string}`"
def summarize_datasets(datasets: Iterable[Dataset]) -> str:
rows = []
# Override the default iteration order of datasets.
for dataset in sorted(datasets, key=lambda d: d.name):
# Raw numeric values here, formatted below.
description = truncate(dataset.description, max_line_len=60)
links = ", ".join(
f"`{name} <{url}>`__" for name, url in sorted(dataset.references.items())
)
if links:
description = f"{description} [{links}]"
rows.append(
(
dataset.name,
dataset.size,
description,
dataset.validatable,
)
)
rows.append(("Total", sum(r[1] for r in rows), "", ""))
return (
tabulate(
[
(
n,
# A size of zero means infinite.
f"{f:,d}" if f > 0 else "∞",
l,
v,
)
for n, f, l, v in rows
],
headers=(
"Dataset",
"Num. Benchmarks [#f1]_",
"Description",
"Validatable [#f2]_",
),
)
+ f"""
.. [#f1] Values obtained on {sys.platform}. Datasets are platform-specific.
.. [#f2] A **validatable** dataset is one where the behavior of the benchmarks
can be checked by compiling the programs to binaries and executing
them. If the benchmarks crash, or are found to have different behavior,
then validation fails. This type of validation is used to check that
the compiler has not broken the semantics of the program.
See :mod:`compiler_gym.bin.validate`.
"""
)
def print_service_capabilities(env: CompilerEnv):
"""Discover and print the capabilities of a CompilerGym service.
:param env: An environment.
"""
print(header("Datasets"))
print(
summarize_datasets(env.datasets),
)
print(header("Observation Spaces"))
print(
tabulate(
sorted(
[
(space, f"`{truncate(shape.space, max_line_len=80)}`")
for space, shape in env.observation.spaces.items()
]
),
headers=("Observation space", "Shape"),
)
)
print(header("Reward Spaces"))
print(
tabulate(
[
(
name,
space.range,
space.success_threshold,
"Yes" if space.deterministic else "No",
"Yes" if space.platform_dependent else "No",
)
for name, space in sorted(env.reward.spaces.items())
],
headers=(
"Reward space",
"Range",
"Success threshold",
"Deterministic?",
"Platform dependent?",
),
)
)
for action_space in env.action_spaces:
print(header(f"{action_space.name} Action Space"))
# Special handling for commandline action spaces to print additional
# information.
if isinstance(action_space, Commandline):
table = tabulate(
[
(f"`{n}`", d)
for n, d in zip(
action_space.names,
action_space.descriptions,
)
],
headers=("Action", "Description"),
)
print(table)
elif isinstance(action_space, NamedDiscrete):
table = tabulate(
[(a,) for a in sorted(action_space.names)],
headers=("Action",),
)
print(table)
else:
print(f'Action space "{action_space}" is not supported.')
def main(argv):
"""Main entry point."""
assert len(argv) == 1, f"Unrecognized flags: {argv[1:]}"
if FLAGS.run_on_port:
assert FLAGS.env, "Must specify an --env to run"
settings = ConnectionOpts(script_args=["--port", str(FLAGS.run_on_port)])
with gym.make(FLAGS.env, connection_settings=settings) as env:
print(
f"=== Started a service on port {FLAGS.run_on_port}. Use C-c to terminate. ==="
)
signal.pause()
with env_from_flags() as env:
print_service_capabilities(env)
if __name__ == "__main__":
app.run(main)
|
CompilerGym-development
|
compiler_gym/bin/service.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Run a parallelized random search of an environment's action space.
.. code-block::
$ python -m compiler_gym.bin.random_search --env=<env> --benchmark=<name> [--runtime=<sec>]
This program runs a simple random agent on the action space of a single
benchmark. The best reward, and sequence of actions that produced this, are
logged to file.
For example, run a random search of the LLVM instruction count optimization
space on a Dijkstra benchmark for 60 seconds using:
.. code-block::
$ python -m compiler_gym.bin.random_search --env=llvm-ic-v0 --benchmark=cbench-v1/dijkstra --runtime=60
Started 16 worker threads for benchmark benchmark://cbench-v1/dijkstra (410 instructions) using reward IrInstructionCountOz.
=== Running for a minute ===
Runtime: a minute. Num steps: 470,407 (7,780 / sec). Num episodes: 4,616 (76 / sec). Num restarts: 0.
Best reward: 101.59% (96 passes, found after 35 seconds)
Ending jobs ... done
Step [000 / 096]: reward=0.621951
Step [001 / 096]: reward=0.621951, change=0.000000, action=AlwaysInlinerLegacyPass
...
Step [094 / 096]: reward=1.007905, change=0.066946, action=CfgsimplificationPass
Step [095 / 096]: reward=1.007905, change=0.000000, action=LoopVersioningPass
Step [096 / 096]: reward=1.015936, change=0.008031, action=NewGvnpass
Search strategy
---------------
At each step, the agent selects an action randomly and records the
reward. After a number of steps without improving reward (the "patience" of the
agent), the agent terminates, and the environment resets. The number of steps
to take without making progress can be configured using the
:code:`--patience=<num>` flag.
Use :code:`--runtime` to limit the total runtime of the search. If not provided,
the search will run indefinitely. Use :code:`C-c` to cancel an in-progress
search.
Execution strategy
------------------
The results of the search are logged to files. Control the location of these
logs using the :code:`--output_dir=/path` flag.
Multiple agents are run in parallel. By default, the number of agents is equal
to the number of processors on the host machine. Set a different value using
:code:`--nproc`.
"""
import sys
from pathlib import Path
from absl import app, flags
import compiler_gym.util.flags.nproc # noqa Flag definition.
import compiler_gym.util.flags.output_dir # noqa Flag definition.
from compiler_gym.random_search import random_search
from compiler_gym.util.flags.benchmark_from_flags import benchmark_from_flags
from compiler_gym.util.flags.env_from_flags import env_from_flags
flags.DEFINE_boolean("ls_reward", False, "List the available reward spaces and exit.")
flags.DEFINE_integer(
"patience",
0,
"The number of steps that a random agent makes without improvement before terminating. "
"If 0, use the size of the action space for the patience value.",
)
flags.DEFINE_float("runtime", None, "If set, limit the search to this many seconds.")
flags.DEFINE_boolean(
"skip_done",
False,
"If set, don't overwrite existing experimental results.",
)
flags.DEFINE_float(
"fail_threshold",
None,
"If set, define a minimum threshold for reward. The script will exit with return code 1 "
"if this threshold is not reached.",
)
FLAGS = flags.FLAGS
def main(argv):
"""Main entry point."""
argv = FLAGS(argv)
if len(argv) != 1:
raise app.UsageError(f"Unknown command line arguments: {argv[1:]}")
if FLAGS.ls_reward:
with env_from_flags() as env:
print("\n".join(sorted(env.reward.indices.keys())))
return
assert FLAGS.patience >= 0, "--patience must be >= 0"
# Create an environment now to catch a startup time error before we launch
# a bunch of workers.
with env_from_flags() as env:
env.reset(benchmark=benchmark_from_flags())
env = random_search(
make_env=lambda: env_from_flags(benchmark=benchmark_from_flags()),
outdir=Path(FLAGS.output_dir) if FLAGS.output_dir else None,
patience=FLAGS.patience,
total_runtime=FLAGS.runtime,
nproc=FLAGS.nproc,
skip_done=FLAGS.skip_done,
)
try:
# Exit with error if --fail_threshold was set and the best reward does not
# meet this value.
if (
FLAGS.fail_threshold is not None
and env.episode_reward < FLAGS.fail_threshold
):
print(
f"Best reward {env.episode_reward:.3f} below threshold of {FLAGS.fail_threshold}",
file=sys.stderr,
)
sys.exit(1)
finally:
env.close()
if __name__ == "__main__":
app.run(main)
|
CompilerGym-development
|
compiler_gym/bin/random_search.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Validate environment states.
Example usage:
.. code-block::
$ cat << EOF |
benchmark,reward,walltime,commandline
cbench-v1/crc32,0,1.2,opt input.bc -o output.bc
EOF
python -m compiler_gym.bin.validate --env=llvm-ic-v0 -
Use this script to validate environment states. Environment states are read from
stdin as a comma-separated list of benchmark names, walltimes, episode rewards,
and commandlines. Each state is validated by replaying the commandline and
validating that the reward matches the expected value. Further, some benchmarks
allow for validation of program semantics. When available, those additional
checks will be automatically run.
Input Format
------------
The correct format for generating input states can be generated using
:class:`CompilerEnvStateWriter <compiler_gym.CompilerEnvStateWriter>`. For
example:
>>> env = gym.make("llvm-autophase-ic-v0")
>>> env.reset()
>>> env.step(env.action_space.sample())
>>> with CompilerEnvStateWriter(open("results.csv", "wb")) as writer:
... writer.write_state(env.state)
Output Format
-------------
This script prints one line per input state. The order of input states is not
preserved. A successfully validated state has the format:
.. code-block::
✅ <benchmark_name> <reproduced_reward>
Else if validation fails, the output is:
.. code-block::
❌ <benchmark_name> <error_details>
"""
import json
import re
import sys
import numpy as np
from absl import app, flags
import compiler_gym.util.flags.nproc # noqa Flag definition.
from compiler_gym.compiler_env_state import CompilerEnvState, CompilerEnvStateReader
from compiler_gym.util.flags.env_from_flags import env_from_flags
from compiler_gym.util.shell_format import emph, plural
from compiler_gym.util.statistics import arithmetic_mean, geometric_mean, stdev
from compiler_gym.validate import ValidationResult, validate_states
flags.DEFINE_boolean(
"inorder",
False,
"Whether to print results in the order they are provided. "
"The default is to print results as soon as they are available.",
)
flags.DEFINE_string(
"reward_aggregation",
"geomean",
"The aggregation method to use for rewards. Allowed values are 'mean' for "
"arithmetic mean and 'geomean' for geometric mean.",
)
flags.DEFINE_boolean(
"debug_force_valid",
False,
"Debugging flags. Skips the validation and prints output as if all states "
"were succesfully validated.",
)
flags.DEFINE_boolean(
"summary_only",
False,
"Do not print individual validation results, print only the summary at the " "end.",
)
flags.DEFINE_string(
"validation_logfile",
"validation.log.json",
"The path of a file to write a JSON validation log to.",
)
FLAGS = flags.FLAGS
def state_name(state: CompilerEnvState) -> str:
"""Get the string name for a state."""
return re.sub(r"^benchmark://", "", state.benchmark)
def to_string(result: ValidationResult, name_col_width: int) -> str:
"""Format a validation result for printing."""
name = state_name(result.state)
if not result.okay():
msg = ", ".join(result.error_details.strip().split("\n"))
return f"❌ {name} {msg}"
elif result.state.reward is None:
return f"✅ {name}"
else:
return f"✅ {name:<{name_col_width}} {result.state.reward:9.4f}"
def main(argv):
"""Main entry point."""
try:
states = list(CompilerEnvStateReader.read_paths(argv[1:]))
except ValueError as e:
print(e, file=sys.stderr)
sys.exit(1)
if not states:
print(
"No inputs to validate. Pass a CSV file path as an argument, or "
"use - to read from stdin.",
file=sys.stderr,
)
sys.exit(1)
# Send the states off for validation
if FLAGS.debug_force_valid:
validation_results = (
ValidationResult(
state=state,
reward_validated=True,
actions_replay_failed=False,
reward_validation_failed=False,
benchmark_semantics_validated=False,
benchmark_semantics_validation_failed=False,
walltime=0,
)
for state in states
)
else:
validation_results = validate_states(
env_from_flags,
states,
nproc=FLAGS.nproc,
inorder=FLAGS.inorder,
)
# Determine the name of the reward space.
with env_from_flags() as env:
if FLAGS.reward_aggregation == "geomean":
def reward_aggregation(a):
return geometric_mean(np.clip(a, 0, None))
reward_aggregation_name = "Geometric mean"
elif FLAGS.reward_aggregation == "mean":
reward_aggregation = arithmetic_mean
reward_aggregation_name = "Mean"
else:
raise app.UsageError(
f"Unknown aggregation type: '{FLAGS.reward_aggregation}'"
)
if env.reward_space:
reward_name = f"{reward_aggregation_name} {env.reward_space.name}"
else:
reward_name = ""
# Determine the maximum column width required for printing tabular output.
max_state_name_length = max(
len(s)
for s in [state_name(s) for s in states]
+ [
"Mean inference walltime",
reward_name,
]
)
name_col_width = min(max_state_name_length + 2, 78)
error_count = 0
rewards = []
walltimes = []
if FLAGS.summary_only:
def intermediate_print(*args, **kwargs):
del args
del kwargs
else:
intermediate_print = print
def progress_message(i):
intermediate_print(
f"{i} remaining {plural(i, 'state', 'states')} to validate ... ",
end="",
flush=True,
)
progress_message(len(states))
result_dicts = []
def dump_result_dicts_to_json():
with open(FLAGS.validation_logfile, "w") as f:
json.dump(result_dicts, f)
for i, result in enumerate(validation_results, start=1):
intermediate_print("\r\033[K", to_string(result, name_col_width), sep="")
progress_message(len(states) - i)
result_dicts.append(result.dict())
if not result.okay():
error_count += 1
elif result.reward_validated and not result.reward_validation_failed:
rewards.append(result.state.reward)
walltimes.append(result.state.walltime)
if not i % 10:
dump_result_dicts_to_json()
dump_result_dicts_to_json()
# Print a summary footer.
intermediate_print("\r\033[K----", "-" * name_col_width, "-----------", sep="")
print(f"Number of validated results: {emph(len(walltimes))} of {len(states)}")
walltime_mean = f"{arithmetic_mean(walltimes):.3f}s"
walltime_std = f"{stdev(walltimes):.3f}s"
print(
f"Mean walltime per benchmark: {emph(walltime_mean)} "
f"(std: {emph(walltime_std)})"
)
reward = f"{reward_aggregation(rewards):.3f}"
reward_std = f"{stdev(rewards):.3f}"
print(f"{reward_name}: {emph(reward)} (std: {emph(reward_std)})")
if error_count:
sys.exit(1)
if __name__ == "__main__":
app.run(main)
|
CompilerGym-development
|
compiler_gym/bin/validate.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Note that the tutorial is extracted from the doc string with the repeated ^
# signs. So, please keep them as they are.
"""Run a CompilerGym environment with text interface controls.
.. code-block::
$ python -m compiler_gym.bin.manual_env --env=<env> [--benchmark=<name>] [--observation=<space>] [--reward=<space>]
The benchmark to use can be specified using :code:`--benchmark=<name>`.
**************************
CompilerGym Shell Tutorial
**************************
This program gives a basic shell through which many of commands from CompilerGym
can be executed. CompilerGym provides a simple Python interface to various
compiler functions, enabling programs to be compiled in different ways and to
make queries about those programs. The goal is to have a simple system for
machine learning in compilers.
Setting a Benchmark, Reward and Observation
-------------------------------------------
The CompilerGym operates on a program or benchmark. If not set on the command
line, the benchmark can be specified in the shell with:
.. code-block::
compiler_gym:cbench-v1/qsort> set_benchmark <benchmark-name>
When a benchmark is set, the prompt will update with the name of the benchmark.
Supposing that is "bench", then the prompt would be:
.. code-block::
compiler_gym:bench>
The list of available benchmarks can be shown with, though this is limited to
the first 200 benchmarks:
.. code-block::
compiler_gym:bench> list_benchmarks
You can also see what datasets are available with this command:
.. code-block::
compiler_gym:cbench-v1/qsort> list_datasets
The default reward and observation can be similarly set with:
.. code-block::
compiler_gym:bench> set_default_reward <reward-name>
compiler_gym:bench> set_default_observation <observation-name>
And lists of the choices are available with:
.. code-block::
compiler_gym:bench> list_rewards
compiler_gym:bench> list_observations
The default rewards and observations will be reported every time an action is
taken. So, if, for example, you want to see how the instruction count of the
benchmark program is affected by your actions, set the default reward to
"IrInstructionCount". Then the change in instruction count for each action will
be reported.
Additionally, some of the search techniques require the default reward to be
set, since they will try to optimise that reward.
Actions and the Action Stack
----------------------------
In CompilerGym an action corresponds to invoking an compiler operation
(currently an LLVM opt pass) on the intermediate representation of the program.
Each action acts on the result of the previous action and so on.
So, for example, to apply first the 'tail call elimination' pass, then the 'loop
unrolling' pass we call two actions:
.. code-block::
compiler_gym:bench> action -tailcallelim
compiler_gym:bench> action -loop-unroll
Each action will report its default reward. Note that multiple actions can be
placed on a single line, so that the above is equivalent to:
.. code-block::
compiler_gym:bench> action -tailcallelim -loop-unroll
You can choose a random action, by using just a '-' as the action name:
.. code-block::
compiler_gym:bench> action -
Since an empty line on the shell repeats the last action, you can execute many
random actions by typing that line first then holding down return.
The actions are recorded in a stack, with the latest action on the top of the
stack. You can view the action stack with stack command:
.. code-block::
compiler_gym:bench> stack
This will show for each action if it had an effect (as computed by the
underlying compiler), whether this terminated compiler, and what the per action
and cumulative rewards are.
The last action can be undone by:
.. code-block::
compiler_gym:bench> undo
All actions in the stack can be undone at once by:
.. code-block::
compiler_gym:bench> reset
You can find out what the effect of each action would be by calling this
command:
.. code-block::
compiler_gym:bench> try_all_actions
This will show a table with the reward for each action, sorted by best first.
If you have a large stack of actions, many of which are not profitable, you can
simplify the stack with this command:
.. code-block::
compiler_gym:bench> simplify_stack
This will redo the entire stack, keeping only those actions which previously
gave good rewards. (Note this doesn't mean that the simplified stack will only
have positive rewards, some negative actions may be necessary set up for a later
positive reward.)
Current Status
--------------
For the current state of the program - after whatever actions have been called
on it - you can make several queries.
The first is to get a reward. This might not be the same as the current default
reward:
.. code-block::
compiler_gym:bench> reward <reward-name>
You can see various observations with:
.. code-block::
compiler_gym:bench> observation <observation-name>
Finally, you can print the equivalent command line for achieving the same
behaviour as the actions through the standard system shell:
.. code-block::
compiler_gym:bench> commandline
Searching
---------
Some very basic search capabilities are supported, directly in the shell. Each
of them just looks for another action to add.
First, is the random search through this command:
.. code-block::
compiler_gym:bench> action -
Multiple steps can be taken by holding down the return key.
A hill-climbing search tries an action, but will only accept it if it yields a
positive reward:
.. code-block::
compiler_gym:bench> hill_climb <num-steps>
A simple greedy search tries all possible actions and takes the one with the
highest reward, stopping when no action has a positive reward:
.. code-block::
compiler_gym:bench> greedy <num-steps>
Miscellaneous
-------------
One useful command is:
.. code-block::
compiler_gym:bench> breakpoint
Which drops into the python debugger. This is very useful if you want to see
what is going on internally. There is a 'self.env' object that represents the
environment that is definitely worth exploring.
And finally:
.. code-block::
compiler_gym:bench> exit
Drops out of the shell. :code:`Ctrl-D` should have the same effect.
"""
import cmd
import random
import readline
import sys
from itertools import islice
from absl import app, flags
from compiler_gym.envs import CompilerEnv
from compiler_gym.util.flags.benchmark_from_flags import benchmark_from_flags
from compiler_gym.util.flags.env_from_flags import env_from_flags
from compiler_gym.util.shell_format import emph
from compiler_gym.util.tabulate import tabulate
from compiler_gym.util.timer import Timer
FLAGS = flags.FLAGS
# Extract the tutorial from the doc string
tutorial = "**************************".join(
__doc__.split("**************************")[1:]
)
class ActionHistoryElement:
"""The compiler gym shell records a list of actions taken. This class represent those elements."""
def __init__(self, action_name, action_index, observation, reward, done, info):
"""Arguments are the returns from env.step"""
self.action_name = action_name
self.action_index = action_index
self.observation = observation
self.reward = reward
self.done = done
self.info = info
def has_no_effect(self):
"""Determine if the service thinks this action had no effect"""
return self.info.get("action_had_no_effect")
def has_effect(self):
"""Determine if the service thinks this action had an effect"""
return not self.has_no_effect()
class CompilerGymShell(cmd.Cmd):
"""Run an environment manually.
The manual environment allows the user to step through the environment,
selection observations, rewards, and actions to run as they see fit. This is
useful for debugging.
"""
intro = """Welcome to the CompilerGym Shell!
---------------------------------
Type help or ? for more information.
The 'tutorial' command will give a step by step guide."""
def __init__(self, env: CompilerEnv):
"""Initialise with an environment.
:param env: The environment to run.
"""
super().__init__()
self.env = env
# Get the benchmarks
self.benchmarks = []
for dataset in self.env.datasets:
self.benchmarks += islice(dataset.benchmark_uris(), 50)
self.benchmarks.sort()
# Strip default benchmark:// scheme.
for i, benchmark in enumerate(self.benchmarks):
if benchmark.startswith("benchmark://"):
self.benchmarks[i] = benchmark[len("benchmark://") :]
# Get the observations
self.observations = sorted(self.env.observation.spaces.keys())
# Get the rewards
self.rewards = sorted(self.env.reward.spaces.keys())
# Set up the stack.
self.stack = []
self.set_prompt()
def __del__(self):
"""Tidy up in case postloop() is not called."""
if self.env:
self.env.close()
self.env = None
def do_tutorial(self, arg):
"""Print the turorial"""
print(tutorial)
def preloop(self):
self.old_completer_delims = readline.get_completer_delims()
readline.set_completer_delims(" \t\n")
def postloop(self):
readline.set_completer_delims(self.old_completer_delims)
# Clear the stack
self.stack.clear()
self.env.close()
self.env = None
def set_prompt(self):
"""Set the prompt - shows the benchmark name"""
uri = self.env.benchmark.uri
benchmark_name = (
f"{uri.dataset}{uri.path}"
if uri.scheme == "benchmark"
else f"{uri.scheme}://{uri.dataset}{uri.path}"
)
prompt = f"compiler_gym:{benchmark_name}>"
self.prompt = f"\n{emph(prompt)} "
def simple_complete(self, text, options):
"""Return a list of options that match the text prefix"""
if text:
return [opt for opt in options if opt.startswith(text)]
else:
return options
def get_datasets(self):
"""Get the list of datasets"""
return sorted([k.name for k in self.env.datasets.datasets()])
def do_list_datasets(self, arg):
"""List all of the datasets"""
print(", ".join(self.get_datasets()))
def do_list_benchmarks(self, arg):
"""List the benchmarks"""
print(", ".join(self.benchmarks))
def complete_set_benchmark(self, text, line, begidx, endidx):
"""Complete the set_benchmark argument"""
return self.simple_complete(text, self.benchmarks)
def do_set_benchmark(self, arg):
"""Set the current benchmark.
set_benchmark <name> - set the benchmark
The name should come from the list of benchmarks printed by the command list_benchmarks.
Tab completion will be used if available.
This command will delete the action history.
Use '-' for a random benchmark.
"""
if arg == "-":
arg = self.env.datasets.random_benchmark().uri
print(f"set_benchmark {arg}")
try:
benchmark = self.env.datasets.benchmark(arg)
self.stack.clear()
# Set the current benchmark
with Timer() as timer:
observation = self.env.reset(benchmark=benchmark)
print(f"Reset {self.env.benchmark} environment in {timer}")
if self.env.observation_space and observation is not None:
print(
f"Observation: {self.env.observation_space_spec.to_string(observation)}"
)
self.set_prompt()
except LookupError:
print("Unknown benchmark, '" + arg + "'")
print("Benchmarks are listed with command, list_benchmarks")
def get_actions(self):
"""Get the list of actions"""
return self.env.action_space.names
def do_list_actions(self, arg):
"""List all of the available actions"""
actions = self.get_actions()
print(", ".join(actions))
def complete_action(self, text, line, begidx, endidx):
"""Complete the action argument"""
return self.simple_complete(text, self.get_actions())
def do_action(self, arg):
"""Take a single action step.
action <name> - take the named action
The name should come from the list of actions printed by the command list_actions.
Tab completion will be used if available.
Use '-' for a random action.
"""
if self.stack and self.stack[-1].done:
print(
"No action possible, last action ended by the environment with error:",
self.stack[-1].info["error_details"],
)
print("Consider commands, back or reset")
return
# Determine which action to apply
actions = self.get_actions()
# Allow for multiple actions at once
args = arg.split()
if not args:
print("No action given")
print("Actions are listed with command, list_actions")
print("Use '-' for a random action")
return
# Check each action before executing
for arg in args:
if arg != "-" and actions.count(arg) == 0:
print("Unknown action, '" + arg + "'")
print("Actions are listed with command, list_actions")
print("Use '-' for a random action")
return
# Replace random actions
for i in range(len(args)):
if args[i] == "-":
args[i] = actions[random.randrange(self.env.action_space.n)]
# Now do the actions
cum_reward = 0
actions_taken = []
with Timer() as timer:
for a in args:
print(f"Action {a}")
index = actions.index(a)
observation, reward, done, info = self.env.step(index)
# Print the observation, if available.
if self.env.observation_space and observation is not None:
print(
f"Observation: {self.env.observation_space_spec.to_string(observation)}"
)
# Print the reward, if available.
if self.env.reward_space and reward is not None:
print(f"Reward: {reward:.6f}")
cum_reward += reward
# Append the history element
hist = ActionHistoryElement(
self.env.action_space.names[index],
index,
observation,
reward,
done,
info,
)
self.stack.append(hist)
if hist.has_no_effect():
print("No effect")
actions_taken.append(a)
if hist.done:
print("Episode ended by environment: ", info["error_details"])
print("No further actions will be possible")
break
print(
f"Actions {' '.join(actions_taken)} in {timer} with reward {cum_reward}.",
flush=True,
)
def rerun_stack(self, check_rewards=True):
"""Rerun all the actions on the stack."""
self.env.reset()
old_stack = self.stack
self.stack = []
for i, old_hist in enumerate(old_stack):
observation, reward, done, info = self.env.step(old_hist.action_index)
hist = ActionHistoryElement(
old_hist.action_name,
old_hist.action_index,
observation,
reward,
done,
info,
)
self.stack.append(hist)
if check_rewards and reward != old_hist.reward:
print(
f"Warning previous reward at {i}: {hist.action_name} was {hist.reward:.6f} now {reward:.6f}"
)
def do_hill_climb(self, arg):
"""Do some steps of hill climbing.
A random action is taken, but only accepted if it has a positive reward.
An argument, if given, should be the number of steps to take.
The search will try to improve the default reward. Please call set_default_reward if needed.
"""
if not self.env.reward_space:
print("No default reward set. Call set_default_reward")
return
try:
num_steps = max(1, int(arg))
except ValueError:
num_steps = 1
num_accepted = 0
cum_reward = 0
with Timer() as timer:
for i in range(num_steps):
index = random.randrange(self.env.action_space.n)
action = self.env.action_space.names[index]
observation, reward, done, info = self.env.step(index)
accept = not done and (reward is not None) and (reward > 0)
if accept:
# Append the history element
hist = ActionHistoryElement(
action, index, observation, reward, done, info
)
self.stack.append(hist)
num_accepted += 1
cum_reward += reward
else:
# Basically undo
self.rerun_stack()
print(
f"Step: {i+1} Action: {action} Reward: {reward:.6f} Accept: {accept}"
)
if done:
print("Episode ended by environment: ", info["error_details"])
print(
f"Hill climb complete in {timer}. Accepted {num_accepted} of {num_steps} steps for total reward of {cum_reward}."
)
def get_action_rewards(self):
"""Get all the rewards for the possible actions at this point"""
items = []
for index, action in enumerate(self.env.action_space.names):
self.rerun_stack()
observation, reward, done, info = self.env.step(index)
hist = ActionHistoryElement(action, index, observation, reward, done, info)
items.append(hist)
print(f"Action: {action} Reward: {reward:.6f}")
self.rerun_stack()
items.sort(key=lambda h: h.reward, reverse=True)
return items
def do_try_all_actions(self, args):
"""Tries all actions from this position and reports the results in sorted order by reward"""
if not self.env.reward_space:
print("No default reward set. Call set_default_reward")
return
with Timer("Got actions"):
items = self.get_action_rewards()
def row(item):
return (
item.action_name,
item.has_effect(),
item.done,
f"{item.reward:.6f}",
)
rows = [row(item) for item in items]
headers = ["Action", "Effect", "Done", "Reward"]
print(tabulate(rows, headers=headers, tablefmt="presto"))
def do_greedy(self, arg):
"""Do some greedy steps.
All actions are tried and the one with the biggest positive reward is accepted.
An argument, if given, should be the number of steps to take.
The search will try to improve the default reward. Please call set_default_reward if needed.
"""
if not self.env.reward_space:
print("No default reward set. Call set_default_reward")
return
try:
num_steps = max(1, int(arg))
except ValueError:
num_steps = 1
with Timer() as timer:
for i in range(num_steps):
best = self.get_action_rewards()[0]
if (not best.done) and (best.reward is not None) and (best.reward > 0):
self.env.step(best.action_index)
self.stack.append(best)
print(
f"Step: {i+1} Selected action: {best.action_name} Reward: {best.reward:.6f}"
)
else:
print(f"Step: {i+1} Selected no action.")
if i + 1 < num_steps:
print("Greedy search stopping early.")
break
print(f"Greedy {i+1} steps in {timer}")
def do_list_observations(self, arg):
"""List the available observations"""
print(", ".join(self.observations))
def complete_observation(self, text, line, begidx, endidx):
"""Complete the observation argument"""
return self.simple_complete(text, self.observations)
def do_observation(self, arg):
"""Show an observation value
observation <name> - show the named observation
The name should come from the list of observations printed by the command list_observations.
Tab completion will be used if available.
"""
if arg == "" and self.env.observation_space:
arg = self.env.observation_space_spec.id
if self.observations.count(arg):
with Timer() as timer:
value = self.env.observation[arg]
print(self.env.observation.spaces[arg].to_string(value))
print(f"Observation {arg} in {timer}")
else:
print("Unknown observation, '" + arg + "'")
print("Observations are listed with command, list_observations")
def complete_set_default_observation(self, text, line, begidx, endidx):
"""Complete the set_default_observation argument"""
return self.simple_complete(text, self.observations)
def do_set_default_observation(self, arg):
"""Set the default observation space
set_default_observation <name> - set the named observation
The name should come from the list of observations printed by the command list_observations.
Tab completion will be used if available.
With no argument it will set to None.
This command will rerun the actions on the stack.
"""
arg = arg.strip()
if not arg or self.observations.count(arg):
with Timer() as timer:
self.env.observation_space = arg if arg else None
self.rerun_stack(check_rewards=False)
print(f"Observation {arg} in {timer}")
else:
print("Unknown observation, '" + (arg if arg else "None") + "'")
print("Observations are listed with command, list_observations")
def do_list_rewards(self, arg):
"""List the available rewards"""
print(", ".join(self.rewards))
def complete_reward(self, text, line, begidx, endidx):
"""Complete the reward argument"""
return self.simple_complete(text, self.rewards)
def do_reward(self, arg):
"""Show an reward value
reward <name> - show the named reward
The name should come from the list of rewards printed by the command list_rewards.
Tab completion will be used if available.
"""
if arg == "" and self.env.reward_space:
arg = self.env.reward_space.name
if self.rewards.count(arg):
with Timer(f"Reward {arg}"):
print(f"{self.env.reward[arg]:.6f}")
else:
print(f"Unknown reward, '{arg}'")
print("Rewards are listed with command, list_rewards")
def complete_set_default_reward(self, text, line, begidx, endidx):
"""Complete the set_default_reward argument"""
return self.simple_complete(text, self.rewards)
def do_set_default_reward(self, arg):
"""Set the default reward space
set_default_reward <name> - set the named reward
The name should come from the list of rewards printed by the command list_rewards.
Tab completion will be used if available.
With no argument it will set to None.
This command will rerun the actions on the stack.
"""
arg = arg.strip()
if not arg or self.rewards.count(arg):
with Timer(f"Reward {arg}"):
self.env.reward_space = arg if arg else None
self.rerun_stack(check_rewards=False)
else:
print("Unknown reward, '" + (arg if arg else "None") + "'")
print("Rewards are listed with command, list_rewards")
def do_commandline(self, arg):
"""Show the command line equivalent of the actions taken so far"""
print("$", self.env.action_space.to_string(self.env.actions), flush=True)
def do_stack(self, arg):
"""Show the environments on the stack. The current environment is the first shown."""
rows = []
total = 0
for i, hist in enumerate(self.stack):
name = hist.action_name
effect = hist.has_effect()
done = hist.done
reward = f"{hist.reward:.6f}" if hist.reward is not None else "-"
total += hist.reward or 0
row = (i + 1, name, effect, done, reward, f"{total:.6f}")
rows.append(row)
rows.reverse()
rows.append((0, "<init>", False, False, 0, 0))
headers = ["Depth", "Action", "Effect", "Done", "Reward", "Cumulative Reward"]
print(tabulate(rows, headers=headers, tablefmt="presto"))
def do_simplify_stack(self, arg):
"""Simplify the stack
There may be many actions on the stack which have no effect or created a negative reward.
This command makes a basic attempt to remove them. It reruns the stack, using only the
commands which appeared to have a effect and positive reward. If the reward is None
e.g. if there was no default reward set, then it will only check if there was some effect.
Note that the new rewards are not checked, so there may be odd effects caused by an action
being removed that previously had a negative reward being necessary for a later action to
have a positive reward. This means you might see non-positive rewards on the stack afterwards.
"""
self.env.reset()
old_stack = self.stack
self.stack = []
for i, old_hist in enumerate(old_stack):
if old_hist.has_effect() and (
old_hist.reward is None or old_hist.reward > 0
):
observation, reward, done, info = self.env.step(old_hist.action_index)
hist = ActionHistoryElement(
old_hist.action_name,
old_hist.action_index,
observation,
reward,
done,
info,
)
self.stack.append(hist)
if reward != old_hist.reward:
print(
f"Warning previous reward at {i}: {hist.action_name} was {old_hist.reward:.6f} now {reward:.6f}"
)
def do_reset(self, arg):
"""Clear the stack of any actions and reset"""
self.stack.clear()
with Timer("Reset"):
self.env.reset()
self.set_prompt()
def do_back(self, arg):
"""Undo the last action, if any"""
if self.stack:
top = self.stack.pop()
with Timer(f"Undid {top.action_name}"):
self.rerun_stack()
else:
print("No actions to undo")
def do_exit(self, arg):
"""Exit"""
print("Exiting")
return True
def do_breakpoint(self, arg):
"""Enter the debugger.
If you suddenly want to do something funky with self.env, or the self.stack, this is your way in!
"""
breakpoint()
def default(self, line):
"""Override default to quit on end of file"""
if line == "EOF":
return self.do_exit(line)
return super().default(line)
def main(argv):
"""Main entry point."""
argv = FLAGS(argv)
if len(argv) != 1:
raise app.UsageError(f"Unknown command line arguments: {argv[1:]}")
with Timer("Initialized environment"):
benchmark = benchmark_from_flags()
env = env_from_flags(benchmark)
shell = CompilerGymShell(env)
shell.cmdloop()
if __name__ == "__main__":
try:
main(sys.argv)
except app.UsageError as err:
print("Usage Error: " + str(err))
|
CompilerGym-development
|
compiler_gym/bin/manual_env.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Replay the best solution found from a random search.
.. code-block::
$ python -m compiler_gym.bin.random_replay --env=llvm-ic-v0 --output_dir=/path/to/logs
Given a set of :mod:`compiler_gym.bin.random_search` logs generated from a
prior search, replay the best sequence of actions found and record the
incremental reward of each action.
"""
from pathlib import Path
from absl import app, flags
import compiler_gym.util.flags.output_dir # noqa Flag definition.
from compiler_gym.random_search import replay_actions_from_logs
from compiler_gym.util.flags.benchmark_from_flags import benchmark_from_flags
from compiler_gym.util.flags.env_from_flags import env_from_flags
FLAGS = flags.FLAGS
def main(argv):
"""Main entry point."""
argv = FLAGS(argv)
if len(argv) != 1:
raise app.UsageError(f"Unknown command line arguments: {argv[1:]}")
output_dir = Path(FLAGS.output_dir).expanduser().resolve().absolute()
assert (
output_dir / "random_search.json"
).is_file(), f"Invalid --output_dir: {output_dir}"
with env_from_flags() as env:
benchmark = benchmark_from_flags()
replay_actions_from_logs(env, output_dir, benchmark=benchmark)
if __name__ == "__main__":
app.run(main)
|
CompilerGym-development
|
compiler_gym/bin/random_replay.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Evaluate the logs of a random run."""
import json
from pathlib import Path
import humanize
import numpy as np
from absl import app, flags
import compiler_gym.util.flags.output_dir # noqa Flag definition.
from compiler_gym.random_search import RandomSearchProgressLogEntry
from compiler_gym.util.statistics import geometric_mean
from compiler_gym.util.tabulate import tabulate
FLAGS = flags.FLAGS
def eval_logs(outdir: Path) -> None:
rows = []
totals = {
"instructions": 0,
"init_reward": [],
"max_reward": [],
"attempts": 0,
"time": 0,
"actions": 0,
}
for results_dir in sorted(outdir.iterdir()):
benchmark = results_dir.name
progress_path = results_dir / "random_search_progress.csv"
meta_path = results_dir / "random_search.json"
if (
not results_dir.is_dir()
or not progress_path.is_file()
or not meta_path.is_file()
):
continue
with open(meta_path, "rb") as f:
meta = json.load(f)
with open(str(progress_path)) as f:
final_line = f.readlines()[-1]
best = RandomSearchProgressLogEntry.from_csv(final_line)
totals["instructions"] += meta["num_instructions"]
totals["init_reward"].append(meta["init_reward"])
totals["max_reward"].append(best.reward)
totals["attempts"] += best.total_episode_count
totals["time"] += best.runtime_seconds
totals["actions"] += best.num_passes
rows.append(
(
benchmark,
humanize.intcomma(meta["num_instructions"]),
f"{meta['init_reward']:.4f}",
f"{best.reward:.4f}",
(
f"{humanize.intcomma(best.total_episode_count)} attempts "
f"in {humanize.naturaldelta(best.runtime_seconds)}"
),
humanize.intcomma(best.num_passes),
)
)
row_count = len(totals["init_reward"])
rows.append(
(
"Geomean",
"",
f"{geometric_mean(totals['init_reward']):.4f}",
f"{geometric_mean(totals['max_reward']):.4f}",
"",
"",
)
)
rows.append(
(
"Average",
humanize.intcomma(int(totals["instructions"] / row_count)),
f"{np.array(totals['init_reward']).mean():.4f}",
f"{np.array(totals['max_reward']).mean():.4f}",
(
f"{humanize.intcomma(int(totals['attempts'] / row_count))} attempts "
f"in {humanize.naturaldelta(totals['time'] / row_count)}"
),
humanize.intcomma(int(totals["actions"] / row_count)),
)
)
print(
tabulate(
rows,
headers=(
"Benchmark",
"#. instructions",
"Init Reward",
"Max Reward",
"Found after",
"#. actions",
),
)
)
def main(argv):
"""Main entry point."""
argv = FLAGS(argv)
if len(argv) != 1:
raise app.UsageError(f"Unknown command line arguments: {argv[1:]}")
output_dir = Path(FLAGS.output_dir).expanduser().resolve().absolute()
assert output_dir.is_dir(), f"Directory not found: {output_dir}"
eval_logs(output_dir)
if __name__ == "__main__":
app.run(main)
|
CompilerGym-development
|
compiler_gym/bin/random_eval.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from concurrent.futures import as_completed
from pathlib import Path
from typing import Callable, Iterable, List, NamedTuple, Optional, Union
import compiler_gym.errors
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.errors import ValidationError
from compiler_gym.service.proto import Benchmark as BenchmarkProto
from compiler_gym.service.proto import File
from compiler_gym.util import thread_pool
from compiler_gym.util.decorators import frozen_class, memoized_property
# A validation callback is a function that takes a single CompilerEnv instance
# as its argument and returns an iterable sequence of zero or more
# ValidationError tuples.
ValidationCallback = Callable[["CompilerEnv"], Iterable[ValidationError]] # noqa: F821
class BenchmarkSource(NamedTuple):
"""A source file that is used to generate a benchmark. A benchmark may
comprise many source files.
.. warning::
The :class:`BenchmarkSource <compiler_gym.datasets.BenchmarkSource>`
class is new and is likely to change in the future.
"""
filename: str
"""The name of the file."""
contents: bytes
"""The contents of the file as a byte array."""
def __repr__(self) -> str:
return str(self.filename)
@frozen_class
class Benchmark:
"""A benchmark represents a particular program that is being compiled.
A benchmark is a program that can be used by a :class:`CompilerEnv
<compiler_gym.envs.CompilerEnv>` as a program to optimize. A benchmark
comprises the data that is fed into the compiler, identified by a URI.
Benchmarks are not normally instantiated directly. Instead, benchmarks are
instantiated using :meth:`env.datasets.benchmark(uri)
<compiler_gym.datasets.Datasets.benchmark>`:
>>> env.datasets.benchmark("benchmark://npb-v0/20")
benchmark://npb-v0/20
The available benchmark URIs can be queried using
:meth:`env.datasets.benchmark_uris()
<compiler_gym.datasets.Datasets.benchmark_uris>`.
>>> next(env.datasets.benchmark_uris())
'benchmark://cbench-v1/adpcm'
Compiler environments may provide additional helper functions for generating
benchmarks, such as :meth:`env.make_benchmark()
<compiler_gym.envs.LlvmEnv.make_benchmark>` for LLVM.
A Benchmark instance wraps an instance of the :code:`Benchmark` protocol
buffer from the `RPC interface
<https://github.com/facebookresearch/CompilerGym/blob/development/compiler_gym/service/proto/compiler_gym_service.proto>`_
with additional functionality. The data underlying benchmarks should be
considered immutable. New attributes cannot be assigned to Benchmark
instances.
The benchmark for an environment can be set during :meth:`env.reset()
<compiler_gym.envs.CompilerEnv.reset>`. The currently active benchmark can
be queried using :attr:`env.benchmark
<compiler_gym.envs.CompilerEnv.benchmark>`:
>>> env = gym.make("llvm-v0")
>>> env.reset(benchmark="benchmark://cbench-v1/crc32")
>>> env.benchmark
benchmark://cbench-v1/crc32
"""
def __init__(
self,
proto: BenchmarkProto,
validation_callbacks: Optional[List[ValidationCallback]] = None,
sources: Optional[List[BenchmarkSource]] = None,
):
self._proto = proto
self._validation_callbacks = validation_callbacks or []
self._sources = list(sources or [])
def __repr__(self) -> str:
return str(self.uri)
def __hash__(self) -> int:
return hash(self.uri)
@property
def uri(self) -> BenchmarkUri:
"""The URI of the benchmark.
Benchmark URIs should be unique, that is, that two URIs with the same
value should resolve to the same benchmark. However, URIs do not have
uniquely describe a benchmark. That is, multiple identical benchmarks
could have different URIs.
:return: A URI string. :type: string
"""
return BenchmarkUri.from_string(self._proto.uri)
@property
def proto(self) -> BenchmarkProto:
"""The protocol buffer representing the benchmark.
:return: A Benchmark message.
:type: :code:`Benchmark`
"""
return self._proto
@property
def sources(self) -> Iterable[BenchmarkSource]:
"""The original source code used to produce this benchmark, as a list of
:class:`BenchmarkSource <compiler_gym.datasets.BenchmarkSource>`
instances.
:return: A sequence of source files.
:type: :code:`Iterable[BenchmarkSource]`
.. warning::
The :meth:`Benchmark.sources
<compiler_gym.datasets.Benchmark.sources>` property is new and is
likely to change in the future.
"""
return (BenchmarkSource(*x) for x in self._sources)
def is_validatable(self) -> bool:
"""Whether the benchmark has any validation callbacks registered.
:return: :code:`True` if the benchmark has at least one validation
callback.
"""
return self._validation_callbacks != []
def validate(self, env: "CompilerEnv") -> List[ValidationError]: # noqa: F821
"""Run the validation callbacks and return any errors.
If no errors are returned, validation has succeeded:
>>> benchmark.validate(env)
[]
If an error occurs, a :class:`ValidationError
<compiler_gym.ValidationError>` tuple will describe the type of the
error, and optionally contain other data:
>>> benchmark.validate(env)
[ValidationError(type="RuntimeError")]
Multiple :class:`ValidationError <compiler_gym.ValidationError>` errors
may be returned to indicate multiple errors.
This is a synchronous version of :meth:`ivalidate()
<compiler_gym.datasets.Benchmark.ivalidate>` that blocks until all
results are ready:
>>> benchmark.validate(env) == list(benchmark.ivalidate(env))
True
:param env: The :class:`CompilerEnv <compiler_gym.envs.CompilerEnv>`
instance that is being validated.
:return: A list of zero or more :class:`ValidationError
<compiler_gym.ValidationError>` tuples that occurred during
validation.
"""
return list(self.ivalidate(env))
def ivalidate(self, env: "CompilerEnv") -> Iterable[ValidationError]: # noqa: F821
"""Run the validation callbacks and return a generator of errors.
This is an asynchronous version of :meth:`validate()
<compiler_gym.datasets.Benchmark.validate>` that returns immediately.
:parameter env: A :class:`CompilerEnv <compiler_gym.envs.CompilerEnv>`
instance to validate.
:return: A generator of :class:`ValidationError
<compiler_gym.ValidationError>` tuples that occur during validation.
"""
executor = thread_pool.get_thread_pool_executor()
futures = (
executor.submit(validator, env) for validator in self.validation_callbacks()
)
for future in as_completed(futures):
result: Iterable[ValidationError] = future.result()
if result:
yield from result
def validation_callbacks(
self,
) -> List[ValidationCallback]:
"""Return the list of registered validation callbacks.
:return: A list of callables. See :meth:`add_validation_callback()
<compiler_gym.datasets.Benchmark.add_validation_callback>`.
"""
return self._validation_callbacks
def add_source(self, source: BenchmarkSource) -> None:
"""Register a new source file for this benchmark.
:param source: The :class:`BenchmarkSource
<compiler_gym.datasets.BenchmarkSource>` to register.
"""
self._sources.append(source)
def add_validation_callback(
self,
validation_callback: ValidationCallback,
) -> None:
"""Register a new validation callback that will be executed on
:meth:`validate() <compiler_gym.datasets.Benchmark.validate>`.
:param validation_callback: A callback that accepts a single
:class:`CompilerEnv <compiler_gym.envs.CompilerEnv>` argument and
returns an iterable sequence of zero or more :class:`ValidationError
<compiler_gym.ValidationError>` tuples. Validation callbacks must be
thread safe and must not modify the environment.
"""
self._validation_callbacks.append(validation_callback)
def write_sources_to_directory(self, directory: Path) -> int:
"""Write the source files for this benchmark to the given directory.
This writes each of the :attr:`benchmark.sources
<compiler_gym.datasets.Benchmark.sources>` files to disk.
If the benchmark has no sources, no files are written.
:param directory: The directory to write results to. If it does not
exist, it is created.
:return: The number of files written.
"""
directory = Path(directory)
directory.mkdir(exist_ok=True, parents=True)
uniq_paths = set()
for filename, contents in self.sources:
path = directory / filename
uniq_paths.add(path)
path.parent.mkdir(exist_ok=True, parents=True)
with open(path, "wb") as f:
f.write(contents)
return len(uniq_paths)
@classmethod
def from_file(cls, uri: Union[str, BenchmarkUri], path: Path):
"""Construct a benchmark from a file.
:param uri: The URI of the benchmark.
:param path: A filesystem path.
:raise FileNotFoundError: If the path does not exist.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
"""
path = Path(path)
if not path.is_file():
raise FileNotFoundError(path)
# Read the file data into memory and embed it inside the File protocol
# buffer. An alternative would be to simply embed the file path in the
# File.uri field, but this won't work for distributed services which
# don't share a filesystem.
with open(path, "rb") as f:
contents = f.read()
return cls(proto=BenchmarkProto(uri=str(uri), program=File(contents=contents)))
@classmethod
def from_file_contents(cls, uri: Union[str, BenchmarkUri], data: bytes):
"""Construct a benchmark from raw data.
:param uri: The URI of the benchmark.
:param data: An array of bytes that will be passed to the compiler
service.
"""
return cls(proto=BenchmarkProto(uri=str(uri), program=File(contents=data)))
def __eq__(self, other: Union[str, "Benchmark"]):
if isinstance(other, Benchmark):
return self.uri == other.uri
return self.uri == other
def __lt__(self, other: Union[str, "Benchmark"]):
if isinstance(other, Benchmark):
return self.uri < other.uri
return self.uri < other
def __le__(self, other: Union[str, "Benchmark"]):
return self < other or self == other
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
BenchmarkInitError = compiler_gym.errors.BenchmarkInitError
class BenchmarkWithSource(Benchmark):
"""A benchmark which has a single source file."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._src_name = None
self._src_path = None
@classmethod
def create(
cls, uri: str, input_path: Path, src_name: str, src_path: Path
) -> Benchmark:
"""Create a benchmark from paths."""
benchmark = cls.from_file(uri, input_path)
benchmark._src_name = src_name # pylint: disable=protected-access
benchmark._src_path = src_path # pylint: disable=protected-access
return benchmark
@memoized_property
def sources( # pylint: disable=invalid-overridden-method
self,
) -> Iterable[BenchmarkSource]:
with open(self._src_path, "rb") as f:
return [
BenchmarkSource(filename=self._src_name, contents=f.read()),
]
@property
def source(self) -> str:
"""Return the single source file contents as a string."""
return list(self.sources)[0].contents.decode("utf-8")
|
CompilerGym-development
|
compiler_gym/datasets/benchmark.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import bz2
import gzip
import io
import logging
import shutil
import tarfile
from threading import Lock
from typing import Iterable, List, Optional
from fasteners import InterProcessLock
from compiler_gym.datasets.files_dataset import FilesDataset
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.download import download
from compiler_gym.util.filesystem import atomic_file_write
logger = logging.getLogger(__name__)
# Module-level locks that ensures exclusive access to install routines across
# threads. Note that these lock are shared across all TarDataset instances. We
# don't use per-dataset locks as locks cannot be pickled.
_TAR_INSTALL_LOCK = Lock()
_TAR_MANIFEST_INSTALL_LOCK = Lock()
class TarDataset(FilesDataset):
"""A dataset comprising a files tree stored in a tar archive.
This extends the :class:`FilesDataset <compiler_gym.datasets.FilesDataset>`
class by adding support for compressed archives of files. The archive is
downloaded and unpacked on-demand.
"""
def __init__(
self,
tar_urls: List[str],
tar_sha256: Optional[str] = None,
tar_compression: str = "bz2",
strip_prefix: str = "",
**dataset_args,
):
"""Constructor.
:param tar_urls: A list of redundant URLS to download the tar archive from.
:param tar_sha256: The SHA256 checksum of the downloaded tar archive.
:param tar_compression: The tar archive compression type. One of
{"bz2", "gz"}.
:param strip_prefix: An optional path prefix to strip. Only files that
match this path prefix will be used as benchmarks.
:param dataset_args: See :meth:`FilesDataset.__init__()
<compiler_gym.datasets.FilesDataset.__init__>`.
"""
super().__init__(
dataset_root=None, # Set below once site_data_path is resolved.
**dataset_args,
)
self.dataset_root = self.site_data_path / "contents" / strip_prefix
self.tar_urls = tar_urls
self.tar_sha256 = tar_sha256
self.tar_compression = tar_compression
self.strip_prefix = strip_prefix
self._tar_extracted_marker = self.site_data_path / ".extracted"
self._tar_lockfile = self.site_data_path / ".install_lock"
@property
def installed(self) -> bool:
return self._tar_extracted_marker.is_file()
def install(self) -> None:
super().install()
if self.installed:
return
# Thread-level and process-level locks to prevent races.
with _TAR_INSTALL_LOCK, InterProcessLock(self._tar_lockfile):
# Repeat the check to see if we have already installed the
# dataset now that we have acquired the lock.
if self.installed:
return
# Remove any partially-completed prior extraction.
shutil.rmtree(self.site_data_path / "contents", ignore_errors=True)
logger.warning(
"Installing the %s dataset. This may take a few moments ...", self.name
)
tar_data = io.BytesIO(download(self.tar_urls, self.tar_sha256))
logger.info("Unpacking %s dataset to %s", self.name, self.site_data_path)
with tarfile.open(
fileobj=tar_data, mode=f"r:{self.tar_compression}"
) as arc:
arc.extractall(str(self.site_data_path / "contents"))
# We're done. The last thing we do is create the marker file to
# signal to any other install() invocations that the dataset is
# ready.
self._tar_extracted_marker.touch()
if self.strip_prefix and not self.dataset_root.is_dir():
raise FileNotFoundError(
f"Directory prefix '{self.strip_prefix}' not found in dataset '{self.name}'"
)
class TarDatasetWithManifest(TarDataset):
"""A tarball-based dataset that reads the benchmark URIs from a separate
manifest file.
A manifest file is a plain text file containing a list of benchmark names,
one per line, and is shipped separately from the tar file. The idea is to
allow the list of benchmark URIs to be enumerated in a more lightweight
manner than downloading and unpacking the entire dataset. It does this by
downloading and unpacking only the manifest to iterate over the URIs.
The manifest file is assumed to be correct and is not validated.
"""
def __init__(
self,
manifest_urls: List[str],
manifest_sha256: str,
manifest_compression: str = "bz2",
**dataset_args,
):
"""Constructor.
:param manifest_urls: A list of redundant URLS to download the
compressed text file containing a list of benchmark URI suffixes,
one per line.
:param manifest_sha256: The sha256 checksum of the compressed manifest
file.
:param manifest_compression: The manifest compression type. One of
{"bz2", "gz"}.
:param dataset_args: See :meth:`TarDataset.__init__()
<compiler_gym.datasets.TarDataset.__init__>`.
"""
super().__init__(**dataset_args)
self.manifest_urls = manifest_urls
self.manifest_sha256 = manifest_sha256
self.manifest_compression = manifest_compression
self._manifest_path = self.site_data_path / f"manifest-{manifest_sha256}.txt"
self._manifest_lockfile = self.site_data_path / ".manifest_lock"
def _read_manifest(self, manifest_data: str) -> List[str]:
"""Read the manifest data into a list of URIs. Does not validate the
manifest contents.
"""
lines = manifest_data.rstrip().split("\n")
return [f"{self.name}/{line}" for line in lines]
def _read_manifest_file(self) -> List[str]:
"""Read the benchmark URIs from an on-disk manifest file.
Does not check that the manifest file exists.
"""
with open(self._manifest_path, encoding="utf-8") as f:
uris = self._read_manifest(f.read())
logger.debug("Read %s manifest, %d entries", self.name, len(uris))
return uris
@memoized_property
def _benchmark_uris(self) -> List[str]:
"""Fetch or download the URI list."""
if self._manifest_path.is_file():
return self._read_manifest_file()
# Thread-level and process-level locks to prevent races.
with _TAR_MANIFEST_INSTALL_LOCK, InterProcessLock(self._manifest_lockfile):
# Now that we have acquired the lock, repeat the check, since
# another thread may have downloaded the manifest.
if self._manifest_path.is_file():
return self._read_manifest_file()
# Determine how to decompress the manifest data.
decompressor = {
"bz2": lambda compressed_data: bz2.BZ2File(compressed_data),
"gz": lambda compressed_data: gzip.GzipFile(compressed_data),
}.get(self.manifest_compression, None)
if not decompressor:
raise TypeError(
f"Unknown manifest compression: {self.manifest_compression}"
)
# Decompress the manifest data.
logger.debug("Downloading %s manifest", self.name)
manifest_data = io.BytesIO(
download(self.manifest_urls, self.manifest_sha256)
)
with decompressor(manifest_data) as f:
manifest_data = f.read()
# Although we have exclusive-execution locks, we still need to
# create the manifest atomically to prevent calls to _benchmark_uris
# racing to read an incompletely written manifest.
with atomic_file_write(self._manifest_path, fileobj=True) as f:
f.write(manifest_data)
uris = self._read_manifest(manifest_data.decode("utf-8"))
logger.debug("Downloaded %s manifest, %d entries", self.name, len(uris))
return uris
@memoized_property
def size(self) -> int:
return len(self._benchmark_uris)
def benchmark_uris(self) -> Iterable[str]:
yield from iter(self._benchmark_uris)
|
CompilerGym-development
|
compiler_gym/datasets/tar_dataset.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from collections import deque
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set, TypeVar
import numpy as np
from compiler_gym.datasets.benchmark import Benchmark
from compiler_gym.datasets.dataset import Dataset
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.service.proto import Benchmark as BenchmarkProto
T = TypeVar("T")
def round_robin_iterables(iters: Iterable[Iterable[T]]) -> Iterable[T]:
"""Yield from the given iterators in round robin order."""
# Use a queue of iterators to iterate over. Repeatedly pop an iterator from
# the queue, yield the next value from it, then put it at the back of the
# queue. The iterator is discarded once exhausted.
iters = deque(iters)
while len(iters) > 1:
it = iters.popleft()
try:
yield next(it)
iters.append(it)
except StopIteration:
pass
# Once we have only a single iterator left, return it directly rather
# continuing with the round robin.
if len(iters) == 1:
yield from iters.popleft()
class Datasets:
"""A collection of datasets.
This class provides a dictionary-like interface for indexing and iterating
over multiple :class:`Dataset <compiler_gym.datasets.Dataset>` objects.
Select a dataset by URI using:
>>> env.datasets["benchmark://cbench-v1"]
Check whether a dataset exists using:
>>> "benchmark://cbench-v1" in env.datasets
True
Or iterate over the datasets using:
>>> for dataset in env.datasets:
... print(dataset.name)
benchmark://cbench-v1
benchmark://github-v0
benchmark://npb-v0
To select a benchmark from the datasets, use :meth:`benchmark()`:
>>> env.datasets.benchmark("benchmark://a-v0/a")
Use the :meth:`benchmarks()` method to iterate over every benchmark in the
datasets in a stable round robin order:
>>> for benchmark in env.datasets.benchmarks():
... print(benchmark)
benchmark://cbench-v1/1
benchmark://github-v0/1
benchmark://npb-v0/1
benchmark://cbench-v1/2
...
If you want to exclude a dataset, delete it:
>>> del env.datasets["benchmark://b-v0"]
"""
def __init__(
self,
datasets: Iterable[Dataset],
):
self._datasets: Dict[str, Dataset] = {d.name: d for d in datasets}
self._visible_datasets: Set[str] = set(
name for name, dataset in self._datasets.items() if not dataset.deprecated
)
def datasets(self, with_deprecated: bool = False) -> Iterable[Dataset]:
"""Enumerate the datasets.
Dataset order is consistent across runs.
:param with_deprecated: If :code:`True`, include datasets that have been
marked as deprecated.
:return: An iterable sequence of :meth:`Dataset
<compiler_gym.datasets.Dataset>` instances.
"""
datasets = self._datasets.values()
if not with_deprecated:
datasets = (d for d in datasets if not d.deprecated)
yield from sorted(datasets, key=lambda d: (d.sort_order, d.name))
def __iter__(self) -> Iterable[Dataset]:
"""Iterate over the datasets.
Dataset order is consistent across runs.
Equivalent to :meth:`datasets.datasets()
<compiler_gym.datasets.Dataset.datasets>`, but without the ability to
iterate over the deprecated datasets.
If the number of benchmarks in any of the datasets is infinite
(:code:`len(dataset) == math.inf`), the iterable returned by this method
will continue indefinitely.
:return: An iterable sequence of :meth:`Dataset
<compiler_gym.datasets.Dataset>` instances.
"""
return self.datasets()
def dataset(self, dataset: str) -> Dataset:
"""Get a dataset.
Return the corresponding :meth:`Dataset
<compiler_gym.datasets.Dataset>`. Name lookup will succeed whether or
not the dataset is deprecated.
:param dataset: A dataset name.
:return: A :meth:`Dataset <compiler_gym.datasets.Dataset>` instance.
:raises LookupError: If :code:`dataset` is not found.
"""
return self.dataset_from_parsed_uri(BenchmarkUri.from_string(dataset))
def dataset_from_parsed_uri(self, uri: BenchmarkUri) -> Dataset:
"""Get a dataset.
Return the corresponding :meth:`Dataset
<compiler_gym.datasets.Dataset>`. Name lookup will succeed whether or
not the dataset is deprecated.
:param uri: A parsed URI.
:return: A :meth:`Dataset <compiler_gym.datasets.Dataset>` instance.
:raises LookupError: If :code:`dataset` is not found.
"""
key = self._dataset_key_from_uri(uri)
if key not in self._datasets:
raise LookupError(f"Dataset not found: {key}")
return self._datasets[key]
@staticmethod
def _dataset_key_from_uri(uri: BenchmarkUri) -> str:
if not (uri.scheme and uri.dataset):
raise LookupError(f"Invalid benchmark URI: '{uri}'")
return f"{uri.scheme}://{uri.dataset}"
def __getitem__(self, dataset: str) -> Dataset:
"""Lookup a dataset.
:param dataset: A dataset name.
:return: A :meth:`Dataset <compiler_gym.datasets.Dataset>` instance.
:raises LookupError: If :code:`dataset` is not found.
"""
return self.dataset(dataset)
def __setitem__(self, key: str, dataset: Dataset):
"""Add a dataset to the collection.
:param key: The name of the dataset.
:param dataset: The dataset to add.
"""
key = self._dataset_key_from_uri(BenchmarkUri.from_string(key))
self._datasets[key] = dataset
if not dataset.deprecated:
self._visible_datasets.add(key)
def __delitem__(self, dataset: str):
"""Remove a dataset from the collection.
This does not affect any underlying storage used by dataset. See
:meth:`uninstall() <compiler_gym.datasets.Datasets.uninstall>` to clean
up.
:param dataset: The name of a dataset.
:return: :code:`True` if the dataset was removed, :code:`False` if it
was already removed.
"""
key = self._dataset_key_from_uri(BenchmarkUri.from_string(dataset))
if key in self._visible_datasets:
self._visible_datasets.remove(key)
del self._datasets[key]
def __contains__(self, dataset: str) -> bool:
"""Returns whether the dataset is contained."""
try:
self.dataset(dataset)
return True
except LookupError:
return False
def benchmarks(self, with_deprecated: bool = False) -> Iterable[Benchmark]:
"""Enumerate the (possibly infinite) benchmarks lazily.
Benchmarks order is consistent across runs. One benchmark from each
dataset is returned in round robin order until all datasets have been
fully enumerated. The order of :meth:`benchmarks()
<compiler_gym.datasets.Datasets.benchmarks>` and :meth:`benchmark_uris()
<compiler_gym.datasets.Datasets.benchmark_uris>` is the same.
If the number of benchmarks in any of the datasets is infinite
(:code:`len(dataset) == math.inf`), the iterable returned by this method
will continue indefinitely.
:param with_deprecated: If :code:`True`, include benchmarks from
datasets that have been marked deprecated.
:return: An iterable sequence of :class:`Benchmark
<compiler_gym.datasets.Benchmark>` instances.
"""
return round_robin_iterables(
(d.benchmarks() for d in self.datasets(with_deprecated=with_deprecated))
)
def benchmark_uris(self, with_deprecated: bool = False) -> Iterable[str]:
"""Enumerate the (possibly infinite) benchmark URIs.
Benchmark URI order is consistent across runs. URIs from datasets are
returned in round robin order. The order of :meth:`benchmarks()
<compiler_gym.datasets.Datasets.benchmarks>` and :meth:`benchmark_uris()
<compiler_gym.datasets.Datasets.benchmark_uris>` is the same.
If the number of benchmarks in any of the datasets is infinite
(:code:`len(dataset) == math.inf`), the iterable returned by this method
will continue indefinitely.
:param with_deprecated: If :code:`True`, include benchmarks from
datasets that have been marked deprecated.
:return: An iterable sequence of benchmark URI strings.
"""
return round_robin_iterables(
(d.benchmark_uris() for d in self.datasets(with_deprecated=with_deprecated))
)
def benchmark(self, uri: str) -> Benchmark:
"""Select a benchmark.
Returns the corresponding :class:`Benchmark
<compiler_gym.datasets.Benchmark>`, regardless of whether the containing
dataset is installed or deprecated.
:param uri: The URI of the benchmark to return.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
"""
return self.benchmark_from_parsed_uri(BenchmarkUri.from_string(uri))
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
"""Select a benchmark.
Returns the corresponding :class:`Benchmark
<compiler_gym.datasets.Benchmark>`, regardless of whether the containing
dataset is installed or deprecated.
:param uri: The parsed URI of the benchmark to return.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
"""
if uri.scheme == "proto":
path = Path(os.path.normpath(f"{uri.dataset}/{uri.path}"))
if not path.is_file():
raise FileNotFoundError(str(path))
proto = BenchmarkProto()
with open(path, "rb") as f:
proto.ParseFromString(f.read())
return Benchmark(proto=proto)
if uri.scheme == "file":
path = Path(os.path.normpath(f"{uri.dataset}/{uri.path}"))
if not path.is_file():
raise FileNotFoundError(str(path))
return Benchmark.from_file(uri=uri, path=path)
dataset = self.dataset_from_parsed_uri(uri)
return dataset.benchmark_from_parsed_uri(uri)
def random_benchmark(
self,
random_state: Optional[np.random.Generator] = None,
weighted: bool = False,
weights: Optional[Dict[str, float]] = None,
) -> Benchmark:
"""Select a benchmark randomly.
First, a dataset is selected randomly using
:code:`random_state.choice(list(datasets))`. Then the
:meth:`random_benchmark()
<compiler_gym.datasets.Dataset.random_benchmark>` method of the chosen
dataset is called to select a benchmark.
By default datasets are selected uniformly randomly. This means that
datasets with a small number of benchmarks will be overrepresented
compared to datasets with many benchmarks. To correct for this bias pass
the argument :code:`weighted=True`, which weights the dataset choice by
the number of benchmarks in each dataset, equivalent to:
>>> random.choices(datasets, weights=[len(p) for p in datasets])
Weighting the choice of datasets by their size means that datasets with
infinite sizes (such as random program generators) will be excluded from
sampling as their size is :code:`0`. To override the weights of datasets
pass a :code:`weights` mapping:
>>> env.datasets.random_benchmark(weighted=True, weights={
"benchmark://dataset-v0": 10,
"benchmark://another-dataset-v0": 555,
})
:param random_state: A random number generator. If not provided, a
default :code:`np.random.default_rng()` is used.
:param weighted: If set, weight the choice of dataset by the number of
benchmarks in each dataset, or the value specified in the
:code:`weights` mapping.
:param weights: An optional mapping from dataset URI to the weight to
use when :code:`weighted=True`. This overrides the default value of
using the dataset size.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
"""
random_state = random_state or np.random.default_rng()
datasets: List[str] = list(self._visible_datasets)
# Assume weighted=True if weights dictionary is specified.
weighted = weighted or weights
if weighted:
weights: Dict[str, float] = weights or {}
w: List[float] = np.array(
[weights.get(d, self[d].size) for d in datasets], dtype=float
)
dataset = random_state.choice(datasets, p=w / w.sum())
else:
dataset = random_state.choice(datasets)
return self[dataset].random_benchmark(random_state=random_state)
@property
def size(self) -> int:
return len(self._visible_datasets)
def __len__(self) -> int:
"""The number of datasets in the collection."""
return self.size
|
CompilerGym-development
|
compiler_gym/datasets/datasets.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Manage datasets of benchmarks."""
from compiler_gym.datasets.benchmark import (
Benchmark,
BenchmarkInitError,
BenchmarkSource,
)
from compiler_gym.datasets.dataset import (
Dataset,
DatasetInitError,
activate,
deactivate,
delete,
require,
)
from compiler_gym.datasets.datasets import Datasets
from compiler_gym.datasets.files_dataset import FilesDataset
from compiler_gym.datasets.tar_dataset import TarDataset, TarDatasetWithManifest
from compiler_gym.datasets.uri import BenchmarkUri
__all__ = [
"activate",
"Benchmark",
"BenchmarkInitError",
"BenchmarkSource",
"BenchmarkUri",
"Dataset",
"DatasetInitError",
"Datasets",
"deactivate",
"delete",
"FilesDataset",
"require",
"TarDataset",
"TarDatasetWithManifest",
]
|
CompilerGym-development
|
compiler_gym/datasets/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import re
import shutil
import warnings
from pathlib import Path
from typing import Dict, Iterable, Optional, Union
import numpy as np
# The "deprecated" name is used as a constructor argument to Dataset, so rename
# this import to prevent shadowing.
from deprecated.sphinx import deprecated as mark_deprecated
import compiler_gym.errors
from compiler_gym.datasets.benchmark import Benchmark
from compiler_gym.datasets.uri import BenchmarkUri
logger = logging.getLogger(__name__)
_DATASET_VERSION_PATTERN = r"[a-zA-z0-9-_]+-v(?P<version>[0-9]+)"
_DATASET_VERSION_RE = re.compile(_DATASET_VERSION_PATTERN)
class Dataset:
"""A dataset is a collection of benchmarks.
The Dataset class has methods for installing and managing groups of
benchmarks, for listing the available benchmark URIs, and for instantiating
:class:`Benchmark <compiler_gym.datasets.Benchmark>` objects.
The Dataset class is an abstract base for implementing datasets. At a
minimum, subclasses must implement the :meth:`benchmark()
<compiler_gym.datasets.Dataset.benchmark>` and :meth:`benchmark_uris()
<compiler_gym.datasets.Dataset.benchmark_uris>` methods, and :meth:`size
<compiler_gym.datasets.Dataset.size>`. Other methods such as
:meth:`install() <compiler_gym.datasets.Dataset.install>` may be used where
helpful.
"""
def __init__(
self,
name: str,
description: str,
license: str, # pylint: disable=redefined-builtin
site_data_base: Optional[Path] = None,
benchmark_class=Benchmark,
references: Optional[Dict[str, str]] = None,
deprecated: Optional[str] = None,
sort_order: int = 0,
validatable: str = "No",
):
"""Constructor.
:param name: The name of the dataset, in the format:
:code:`scheme://name`.
:param description: A short human-readable description of the dataset.
:param license: The name of the dataset's license.
:param site_data_base: An optional directory that can be used by the
dataset to house the "site data", i.e. persistent files on disk. The
site data directory is a subdirectory of this :code:`site_data_base`
path, which can be shared by multiple datasets. If not provided, the
:attr:`dataset.site_data_path
<compiler_gym.datasets.Dataset.site_data_path>` attribute will raise
an error. Use :attr:`dataset.has_site_data
<compiler_gym.datasets.Dataset.has_site_data>` to check if a site
data path was set.
:param benchmark_class: The class to use when instantiating benchmarks.
It must have the same constructor signature as :class:`Benchmark
<compiler_gym.datasets.Benchmark>`.
:param references: A dictionary of useful named URLs for this dataset
containing extra information, download links, papers, etc.
:param deprecated: Mark the dataset as deprecated and issue a warning
when :meth:`install() <compiler_gym.datasets.Dataset.install>`,
including the given method. Deprecated datasets are excluded from
the :meth:`datasets() <compiler_gym.datasets.Datasets.dataset>`
iterator by default.
:param sort_order: An optional numeric value that should be used to
order this dataset relative to others. Lowest value sorts first.
:param validatable: Whether the dataset is validatable. A validatable
dataset is one where the behavior of the benchmarks can be checked
by compiling the programs to binaries and executing them. If the
benchmarks crash, or are found to have different behavior, then
validation fails. This type of validation is used to check that the
compiler has not broken the semantics of the program. This value
takes a string and is used for documentation purposes only.
Suggested values are "Yes", "No", or "Partial".
:raises ValueError: If :code:`name` does not match the expected type.
"""
self._name = name
uri = BenchmarkUri.from_string(name)
self._description = description
self._license = license
self._scheme = uri.scheme
match = _DATASET_VERSION_RE.match(uri.dataset)
self._version = int(match.group("version") if match else 0)
self._references = references or {}
self._deprecation_message = deprecated
self._validatable = validatable
self.sort_order = sort_order
self.benchmark_class = benchmark_class
# Set up the site data name.
if site_data_base:
self._site_data_path = (
Path(site_data_base).resolve() / uri.scheme / uri.dataset
)
def __repr__(self):
return self.name
@property
def name(self) -> str:
"""The name of the dataset.
:type: str
"""
return self._name
@property
def description(self) -> str:
"""A short human-readable description of the dataset.
:type: str
"""
return self._description
@property
def license(self) -> str:
"""The name of the license of the dataset.
:type: str
"""
return self._license
@property
@mark_deprecated(
version="0.2.2", reason="The `protocol` attribute has been renamed `scheme`"
)
def protocol(self) -> str:
"""The URI scheme that is used to identify benchmarks in this dataset.
:type: str
"""
return self.scheme
@property
def scheme(self) -> str:
"""The URI scheme that is used to identify benchmarks in this dataset.
:type: str
"""
return self._scheme
@property
def version(self) -> int:
"""The version tag for this dataset. Defaults to zero.
:type: int
"""
return self._version
@property
def references(self) -> Dict[str, str]:
"""A dictionary of useful named URLs for this dataset containing extra
information, download links, papers, etc.
For example:
>>> dataset.references
{'Paper': 'https://arxiv.org/pdf/1407.3487.pdf',
'Homepage': 'https://ctuning.org/wiki/index.php/CTools:CBench'}
:type: Dict[str, str]
"""
return self._references
@property
def deprecated(self) -> bool:
"""Whether the dataset is included in the iterable sequence of datasets
of a containing :class:`Datasets <compiler_gym.datasets.Datasets>`
collection.
:type: bool
"""
return self._deprecation_message is not None
@property
def validatable(self) -> str:
"""Whether the dataset is validatable. A validatable dataset is one
where the behavior of the benchmarks can be checked by compiling the
programs to binaries and executing them. If the benchmarks crash, or are
found to have different behavior, then validation fails. This type of
validation is used to check that the compiler has not broken the
semantics of the program.
This property takes a string and is used for documentation purposes
only. Suggested values are "Yes", "No", or "Partial".
:type: str
"""
return self._validatable
@property
def has_site_data(self) -> bool:
"""Return whether the dataset has a site data directory.
:type: bool
"""
return hasattr(self, "_site_data_path")
@property
def site_data_path(self) -> Path:
"""The filesystem path used to store persistent dataset files.
This directory may not exist.
:type: Path
:raises ValueError: If no site data path was specified at constructor
time.
"""
if not self.has_site_data:
raise ValueError(f"Dataset has no site data path: {self.name}")
return self._site_data_path
@property
def site_data_size_in_bytes(self) -> int:
"""The total size of the on-disk data used by this dataset.
:type: int
"""
if not self.has_site_data:
return 0
if not self.site_data_path.is_dir():
return 0
total_size = 0
for dirname, _, filenames in os.walk(self.site_data_path):
total_size += sum(
os.path.getsize(os.path.join(dirname, f)) for f in filenames
)
return total_size
@property
def size(self) -> int:
"""The number of benchmarks in the dataset.
If the number of benchmarks is unknown or unbounded, for example because
the dataset represents a program generator that can produce an infinite
number of programs, the value is 0.
:type: int
"""
return 0
def __len__(self) -> int:
"""The number of benchmarks in the dataset.
This is the same as :meth:`Dataset.size
<compiler_gym.datasets.Dataset.size>`:
>>> len(dataset) == dataset.size
True
If the number of benchmarks is unknown or unbounded, for example because
the dataset represents a program generator that can produce an infinite
number of programs, the value is 0.
:return: An integer.
"""
return self.size
def __eq__(self, other: Union["Dataset", str]) -> bool:
if isinstance(other, Dataset):
return self.name == other.name
return self.name == other
def __lt__(self, other: Union["Dataset", str]) -> bool:
if isinstance(other, Dataset):
return self.name < other.name
return self.name < other
def __le__(self, other: Union["Dataset", str]) -> bool:
return self < other or self == other
@property
def installed(self) -> bool:
"""Whether the dataset is installed locally. Installation occurs
automatically on first use, or by calling :meth:`install()
<compiler_gym.datasets.Dataset.install>`.
:type: bool
"""
return True
def install(self) -> None:
"""Install this dataset locally.
Implementing this method is optional. If implementing this method, you
must call :code:`super().install()` first.
This method should not perform redundant work. This method should first
detect whether any work needs to be done so that repeated calls to
:code:`install()` will complete quickly.
"""
if self.deprecated:
warnings.warn(
f"Dataset '{self.name}' is marked as deprecated. {self._deprecation_message}",
category=DeprecationWarning,
stacklevel=2,
)
def uninstall(self) -> None:
"""Remove any local data for this benchmark.
This method undoes the work of :meth:`install()
<compiler_gym.datasets.Dataset.install>`. The dataset can still be used
after calling this method.
"""
if self.has_site_data() and self.site_data_path.is_dir():
shutil.rmtree(self.site_data_path)
def benchmarks(self) -> Iterable[Benchmark]:
"""Enumerate the (possibly infinite) benchmarks lazily.
Iteration order is consistent across runs. The order of
:meth:`benchmarks() <compiler_gym.datasets.Dataset.benchmarks>` and
:meth:`benchmark_uris() <compiler_gym.datasets.Dataset.benchmark_uris>`
is the same.
If the number of benchmarks in the dataset is infinite
(:code:`len(dataset) == math.inf`), the iterable returned by this method
will continue indefinitely.
:return: An iterable sequence of :class:`Benchmark
<compiler_gym.datasets.Benchmark>` instances.
"""
# Default implementation. Subclasses may wish to provide an alternative
# implementation that is optimized to specific use cases.
yield from (self.benchmark(uri) for uri in self.benchmark_uris())
def __iter__(self) -> Iterable[Benchmark]:
"""Enumerate the (possibly infinite) benchmarks lazily.
This is the same as :meth:`Dataset.benchmarks()
<compiler_gym.datasets.Dataset.benchmarks>`:
>>> from itertools import islice
>>> list(islice(dataset, 100)) == list(islice(datset.benchmarks(), 100))
True
:return: An iterable sequence of :meth:`Benchmark
<compiler_gym.datasets.Benchmark>` instances.
"""
yield from self.benchmarks()
def benchmark_uris(self) -> Iterable[str]:
"""Enumerate the (possibly infinite) benchmark URIs.
Iteration order is consistent across runs. The order of
:meth:`benchmarks() <compiler_gym.datasets.Dataset.benchmarks>` and
:meth:`benchmark_uris() <compiler_gym.datasets.Dataset.benchmark_uris>`
is the same.
If the number of benchmarks in the dataset is infinite
(:code:`len(dataset) == math.inf`), the iterable returned by this method
will continue indefinitely.
:return: An iterable sequence of benchmark URI strings.
"""
raise NotImplementedError("abstract class")
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
"""Select a benchmark.
Subclasses must implement this method. Implementors may assume that the
URI is well formed and that the :code:`scheme` and :code:`dataset`
components are correct.
:param uri: The parsed URI of the benchmark to return.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
:raise LookupError: If :code:`uri` is not found.
:raise ValueError: If the URI is invalid.
"""
raise NotImplementedError("abstract class")
def benchmark(self, uri: str) -> Benchmark:
"""Select a benchmark.
:param uri: The URI of the benchmark to return.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
:raise LookupError: If :code:`uri` is not found.
:raise ValueError: If the URI is invalid.
"""
return self.benchmark_from_parsed_uri(BenchmarkUri.from_string(uri))
def random_benchmark(
self, random_state: Optional[np.random.Generator] = None
) -> Benchmark:
"""Select a benchmark randomly.
:param random_state: A random number generator. If not provided, a
default :code:`np.random.default_rng()` is used.
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
"""
random_state = random_state or np.random.default_rng()
return self._random_benchmark(random_state)
def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark:
"""Private implementation of the random benchmark getter.
Subclasses must implement this method so that it selects a benchmark
from the available benchmarks with uniform probability, using only
:code:`random_state` as a source of randomness.
"""
raise NotImplementedError("abstract class")
def __getitem__(self, uri: str) -> Benchmark:
"""Select a benchmark by URI.
This is the same as :meth:`Dataset.benchmark(uri)
<compiler_gym.datasets.Dataset.benchmark>`:
>>> dataset["benchmark://cbench-v1/crc32"] == dataset.benchmark("benchmark://cbench-v1/crc32")
True
:return: A :class:`Benchmark <compiler_gym.datasets.Benchmark>`
instance.
:raise LookupError: If :code:`uri` does not exist.
"""
return self.benchmark(uri)
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
DatasetInitError = compiler_gym.errors.DatasetInitError
@mark_deprecated(
version="0.1.4",
reason=(
"Datasets are now automatically activated. "
"`More information <https://github.com/facebookresearch/CompilerGym/issues/45>`_."
),
)
def activate(env, dataset: Union[str, Dataset]) -> bool:
"""Deprecated function for managing datasets.
:param dataset: The name of the dataset to download, or a :class:`Dataset
<compiler_gym.datasets.Dataset>` instance.
:return: :code:`True` if the dataset was activated, else :code:`False` if
already active.
:raises ValueError: If there is no dataset with that name.
"""
return False
@mark_deprecated(
version="0.1.4",
reason=(
"Please use :meth:`del env.datasets[dataset] <compiler_gym.datasets.Datasets.__delitem__>`. "
"`More information <https://github.com/facebookresearch/CompilerGym/issues/45>`_."
),
)
def delete(env, dataset: Union[str, Dataset]) -> bool:
"""Deprecated function for managing datasets.
Please use :meth:`del env.datasets[dataset]
<compiler_gym.datasets.Datasets.__delitem__>`.
:param dataset: The name of the dataset to download, or a :class:`Dataset
<compiler_gym.datasets.Dataset>` instance.
:return: :code:`True` if the dataset was deleted, else :code:`False` if
already deleted.
"""
del env.datasets[dataset]
return False
@mark_deprecated(
version="0.1.4",
reason=(
"Please use :meth:`env.datasets.deactivate() <compiler_gym.datasets.Datasets.deactivate>`. "
"`More information <https://github.com/facebookresearch/CompilerGym/issues/45>`_."
),
)
def deactivate(env, dataset: Union[str, Dataset]) -> bool:
"""Deprecated function for managing datasets.
Please use :meth:`del env.datasets[dataset]
<compiler_gym.datasets.Datasets.__delitem__>`.
:param dataset: The name of the dataset to download, or a :class:`Dataset
<compiler_gym.datasets.Dataset>` instance.
:return: :code:`True` if the dataset was deactivated, else :code:`False` if
already inactive.
"""
del env.datasets[dataset]
return False
@mark_deprecated(
version="0.1.7",
reason=(
"Datasets are now installed automatically, there is no need to call :code:`require()`. "
"`More information <https://github.com/facebookresearch/CompilerGym/issues/45>`_."
),
)
def require(env, dataset: Union[str, Dataset]) -> bool:
"""Deprecated function for managing datasets.
Datasets are now installed automatically. See :class:`env.datasets
<compiler_gym.datasets.Datasets>`.
:param env: The environment that this dataset is required for.
:param dataset: The name of the dataset to download, or a :class:`Dataset
<compiler_gym.datasets.Dataset>` instance.
:return: :code:`True` if the dataset was downloaded, or :code:`False` if the
dataset was already available.
"""
return False
|
CompilerGym-development
|
compiler_gym/datasets/dataset.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains utility code for working with URIs."""
from typing import Dict, List, Union
from urllib.parse import ParseResult, parse_qs, urlencode, urlparse, urlunparse
from pydantic import BaseModel
class BenchmarkUri(BaseModel):
"""A URI used to identify a benchmark, and optionally a set of parameters
for the benchmark.
A URI has the following format:
.. code-block::
scheme://dataset/path?params#fragment
where:
* :code:`scheme` (optional, default :code:`benchmark`): An arbitrary string
used to group datasets, for example :code:`generator` if the dataset is a
benchmark generator.
* :code:`dataset`: The name of a dataset, optionally with a version tag, for
example :code:`linux-v0`.
* :code:`path` (optional, default empty string): The path of a benchmark
within a dataset.
* :code:`params` (optional, default empty dictionary): A set of query
parameters for the benchmark. This is parsed a dictionary of string keys
to a list of string values. For example :code:`dataset=1&debug=true` which
will be parsed as :code:`{"dataset": ["1"], "debug": ["true"]}`.
* :code:`fragment` (optional, default empty string): An optional fragment
within the benchmark.
The :code:`scheme` and :code:`dataset` components are used to resolve a
:class:`Dataset <compiler_gym.datasets.Dataset>` class that can serve the
benchmark. The :meth:`Dataset.benchmark_from_parsed_uri()` method is then
used to interpret the remainder of the URI components.
A benchmark URI may resolve to zero or more benchmarks, for example:
* :code:`benchmark://csmith-v0` resolves to any benchmark from the
:code:`benchmark://csmith-v0` dataset.
* :code:`cbench-v0/qsort` resolves to the path :code:`/qsort`
within the dataset :code:`benchmark://cbench-v0` using the default scheme.
* :code:`benchmark://cbench-v0/qsort?debug=true` also resolves to the path
:code:`/qsort` within the dataset :code:`benchmark://cbench-v0`, but with
an additional parameter :code:`debug=true`.
"""
scheme: str
"""The benchmark scheme. Defaults to :code:`benchmark`."""
dataset: str
"""The name of the dataset."""
path: str
"""The path of the benchmark. Empty string if not set."""
params: Dict[str, List[str]] = {}
"""A dictionary of query parameters. Empty dictionary if not set."""
fragment: str = ""
"""The URL fragment. Empty string if not set."""
@staticmethod
def canonicalize(uri: str):
return str(BenchmarkUri.from_string(uri))
@classmethod
def from_string(cls, uri: str) -> "BenchmarkUri":
components = urlparse(uri)
# Add the default "benchmark://" scheme if required.
if not components.scheme and not components.netloc:
components = urlparse(f"benchmark://{uri}")
return cls(
scheme=components.scheme,
dataset=components.netloc,
path=components.path,
params=parse_qs(components.query),
fragment=components.fragment,
)
def startswith(self, *args):
return str(self).startswith(*args)
def endswith(self, *args):
return str(self).endswith(*args)
def __repr__(self):
return urlunparse(
ParseResult(
scheme=self.scheme,
netloc=self.dataset,
path=self.path,
query=urlencode(self.params, doseq=True),
fragment=self.fragment,
params="", # Field not used.
)
)
def __str__(self) -> str:
return repr(self)
def __hash__(self) -> int:
return hash(str(self))
def __eq__(self, other: Union["BenchmarkUri", str]) -> bool:
return str(self) == str(other)
def __lt__(self, other: Union["BenchmarkUri", str]) -> bool:
return str(self) < str(other)
|
CompilerGym-development
|
compiler_gym/datasets/uri.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from pathlib import Path
from typing import Iterable, List
import numpy as np
from compiler_gym.datasets.dataset import Benchmark, Dataset
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.util.decorators import memoized_property
class FilesDataset(Dataset):
"""A dataset comprising a directory tree of files.
A FilesDataset is a root directory that contains (a possibly nested tree of)
files, where each file represents a benchmark. The directory contents can be
filtered by specifying a filename suffix that files must match.
The URI of benchmarks is the relative path of each file, stripped of a
required filename suffix, if specified. For example, given the following
file tree:
.. code-block::
/tmp/dataset/a.txt
/tmp/dataset/LICENSE
/tmp/dataset/subdir/subdir/b.txt
/tmp/dataset/subdir/subdir/c.txt
a FilesDataset :code:`benchmark://ds-v0` rooted at :code:`/tmp/dataset` with
filename suffix :code:`.txt` will contain the following URIs:
>>> list(dataset.benchmark_uris())
[
"benchmark://ds-v0/a",
"benchmark://ds-v0/subdir/subdir/b",
"benchmark://ds-v0/subdir/subdir/c",
]
"""
def __init__(
self,
dataset_root: Path,
benchmark_file_suffix: str = "",
memoize_uris: bool = True,
**dataset_args,
):
"""Constructor.
:param dataset_root: The root directory to look for benchmark files.
:param benchmark_file_suffix: A file extension that must be matched for
a file to be used as a benchmark.
:param memoize_uris: Whether to memoize the list of URIs contained in
the dataset. Memoizing the URIs enables faster repeated iteration
over :meth:`dataset.benchmark_uris()
<compiler_gym.datasets.Dataset.benchmark_uris>` at the expense of
increased memory overhead as the file list must be kept in memory.
:param dataset_args: See :meth:`Dataset.__init__()
<compiler_gym.datasets.Dataset.__init__>`.
"""
super().__init__(**dataset_args)
self.dataset_root = dataset_root
self.benchmark_file_suffix = benchmark_file_suffix
self.memoize_uris = memoize_uris
self._memoized_uris = None
@memoized_property
def size(self) -> int: # pylint: disable=invalid-overriden-method
self.install()
return sum(
sum(1 for f in files if f.endswith(self.benchmark_file_suffix))
for (_, _, files) in os.walk(self.dataset_root)
)
@property
def _benchmark_uris_iter(self) -> Iterable[str]:
"""Return an iterator over benchmark URIs that is consistent across runs."""
self.install()
for root, dirs, files in os.walk(self.dataset_root):
# Sort the subdirectories so that os.walk() order is stable between
# runs.
dirs.sort()
reldir = root[len(str(self.dataset_root)) + 1 :]
for filename in sorted(files):
# If we have an expected file suffix then ignore files that do
# not match, and strip the suffix from files that do match.
if self.benchmark_file_suffix:
if not filename.endswith(self.benchmark_file_suffix):
continue
filename = filename[: -len(self.benchmark_file_suffix)]
# Use os.path.join() rather than simple '/' concatenation as
# reldir may be empty.
yield os.path.join(self.name, reldir, filename)
@property
def _benchmark_uris(self) -> List[str]:
return list(self._benchmark_uris_iter)
def benchmark_uris(self) -> Iterable[str]:
if self._memoized_uris:
yield from self._memoized_uris
elif self.memoize_uris:
self._memoized_uris = self._benchmark_uris
yield from self._memoized_uris
else:
yield from self._benchmark_uris_iter
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
path = Path(
# Use normpath() rather than joinpath() because uri.path may start
# with a leading '/'.
os.path.normpath(
f"{self.dataset_root}/{uri.path}{self.benchmark_file_suffix}"
)
)
if not path.is_file():
raise LookupError(f"Benchmark not found: {uri} (file not found: {path})")
return self.benchmark_class.from_file(uri, path)
def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark:
return self.benchmark(random_state.choice(list(self.benchmark_uris())))
|
CompilerGym-development
|
compiler_gym/datasets/files_dataset.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections import Counter
from collections.abc import Collection
from typing import Optional, Tuple
import numpy as np
from gym.spaces import Space
class SpaceSequence(Space):
"""Variable-length sequence of subspaces that have the same definition."""
def __init__(
self, name: str, space: Space, size_range: Tuple[int, Optional[int]] = (0, None)
):
"""Constructor.
:param name: The name of the space.
:param space: Shared definition of the spaces in the sequence.
:param size_range: Range of the sequence length.
"""
self.name = name
self.space = space
self.size_range = size_range
def contains(self, x):
if not isinstance(x, Collection):
return False
lower_bound = self.size_range[0]
upper_bound = float("inf") if self.size_range[1] is None else self.size_range[1]
if not (lower_bound <= len(x) <= upper_bound):
return False
for element in x:
if not self.space.contains(element):
return False
return True
def __eq__(self, other) -> bool:
return (
isinstance(self, other.__class__)
and self.name == other.name
and Counter(self.size_range) == Counter(other.size_range)
and self.space == other.space
)
def sample(self):
return [
self.space.sample()
for _ in range(
np.random.randint(
low=self.size_range[0],
high=None if self.size_range[1] is None else self.size_range[1] + 1,
)
)
]
|
CompilerGym-development
|
compiler_gym/spaces/space_sequence.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from gym.spaces import Space
from gym.spaces import Tuple as GymTuple
class Tuple(GymTuple):
"""A tuple (i.e., product) of simpler spaces.
Wraps the underlying :code:`gym.spaces.Tuple` space with a name attribute.
"""
def __init__(self, spaces: List[Space], name: str):
"""Constructor.
:param spaces: The composite spaces.
:param name: The name of the space.
"""
super().__init__(spaces)
self.name = name
def __eq__(self, other) -> bool:
return (
isinstance(self, other.__class__)
and self.name == other.name
and super().__eq__(other)
)
|
CompilerGym-development
|
compiler_gym/spaces/tuple.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Iterable, Optional
import numpy as np
from gym.spaces import Box as GymBox
class Box(GymBox):
"""A (possibly unbounded) box in R^n. Specifically, a Box represents the
Cartesian product of n closed intervals. Each interval has the form of one
of [a, b], (-oo, b], [a, oo), or (-oo, oo).
Wraps the underlying :code:`gym.spaces.Box` with a name attribute.
"""
def __init__(
self,
low: float,
high: float,
name: str,
shape: Optional[Iterable[int]] = None,
dtype=np.float32,
):
"""Constructor.
:param low: The lower bound, inclusive.
:param high: The upper bound, inclusive.
:param name: The name of the space.
:param shape: The shape of the space.
:param dtype: The dtype of the space.
"""
super().__init__(low=low, high=high, shape=shape, dtype=dtype)
self.name = name
def __eq__(self, other) -> bool:
return (
isinstance(self, other.__class__)
and self.name == other.name
and super().__eq__(other)
)
|
CompilerGym-development
|
compiler_gym/spaces/box.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional, Tuple
import numpy as np
from gym.spaces import Space
from compiler_gym.spaces.common import issubdtype
from compiler_gym.spaces.scalar import Scalar
class Sequence(Space):
"""A sequence of values. Each element of the sequence is of `dtype`. The
length of the sequence is bounded by `size_range`.
Example:
::
>>> space = Sequence(size_range=(0, None), dtype=str)
>>> space.contains("Hello, world!")
True
::
>>> space = Sequence(size_range=(256, 256), dtype=bytes)
>>> space.contains("Hello, world!")
False
:ivar size_range: A tuple indicating the `(lower, upper)` bounds for
sequence lengths. An upper bound of `None` means no upper bound. All
sequences must have a lower bound of length >= 0.
:ivar dtype: The data type for each element in a sequence.
:ivar opaque_data_format: An optional string describing an opaque data
format, e.g. a data structure that is serialized to a string/binary
array for transmission to the client. It is up to the client and service
to agree on how to decode observations using this value. For example,
an opaque_data_format of `string_json` could be used to indicate that
the observation is a string-serialized JSON value.
"""
def __init__(
self,
name: str,
size_range: Tuple[int, Optional[int]] = (0, None),
dtype=bytes,
opaque_data_format: Optional[str] = None,
scalar_range: Optional[Scalar] = None,
):
"""Constructor.
:param name: The name of the space.
:param size_range: A tuple indicating the `(lower, upper)` bounds for
sequence lengths. An upper bound of `None` means no upper bound. All
sequences must have a lower bound of length >= 0.
:param dtype: The data type for each element in a sequence.
:param opaque_data_format: An optional string describing an opaque data
format, e.g. a data structure that is serialized to a string/binary
array for transmission to the client. It is up to the client and
service to agree on how to decode observations using this value. For
example, an opaque_data_format of `string_json` could be used to
indicate that the observation is a string-serialized JSON value.
:param scalar_range: If specified, this denotes the legal range of each
element in the sequence. This is enforced by :meth:`contains()
<compiler_gym.spaces.Sequence.contains>` checks.
"""
self.name = name
self.size_range = size_range
self.dtype = dtype
self.opaque_data_format = opaque_data_format
self.scalar_range = scalar_range
def __repr__(self) -> str:
upper_bound = "inf" if self.size_range[1] is None else self.size_range[1]
d = f" -> {self.opaque_data_format}" if self.opaque_data_format else ""
return (
f"{self.dtype.__name__}_list<>[{int(self.size_range[0])},{upper_bound}]){d}"
)
def contains(self, x):
lower_bound = self.size_range[0]
upper_bound = float("inf") if self.size_range[1] is None else self.size_range[1]
if not (lower_bound <= len(x) <= upper_bound):
return False
# TODO(cummins): The dtype API is inconsistent. When dtype=str or
# dtype=bytes, we expect this to be the type of the entire sequence. But
# for dtype=int, we expect this to be the type of each element. We
# should distinguish these differences better.
if self.dtype in {str, bytes}:
if not isinstance(x, self.dtype):
return False
elif hasattr(x, "dtype"):
if not issubdtype(x.dtype, self.dtype):
return False
# Run the bounds check on every scalar element, if there is a scalar
# range specified.
elif self.scalar_range:
return all(self.scalar_range.contains(s) for s in x)
else:
for element in x:
if not issubdtype(type(element), self.dtype):
return False
return True
def sample(self):
"""
.. warning::
The `Sequence` space cannot be sampled from.
:raises NotImplementedError: Not supported.
"""
raise NotImplementedError
def __eq__(self, other):
if not isinstance(other, Sequence):
return False
return (
self.name == other.name
and self.size_range == other.size_range
and np.dtype(self.dtype) == np.dtype(other.dtype)
and self.opaque_data_format == other.opaque_data_format
and self.scalar_range == other.scalar_range
)
|
CompilerGym-development
|
compiler_gym/spaces/sequence.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import random
from typing import Optional
import numpy as np
from gym.spaces import Space
from compiler_gym.spaces.common import issubdtype
class Scalar(Space):
"""A scalar value."""
def __init__(
self,
name: str,
min: Optional[float] = None,
max: Optional[float] = None,
dtype=np.float64,
):
"""Constructor.
:param name: The name of the space.
:param min: The lower bound for a value in this space. If None, there is
no lower bound.
:param max: The upper bound for a value in this space. If None, there is
no upper bound.
:param dtype: The type of this scalar.
"""
self.name = name
self.min = min
self.max = max
self.dtype = dtype
def sample(self):
min = 0 if self.min is None else self.min
max = 1 if self.max is None else self.max
return self.dtype(random.uniform(min, max))
def contains(self, x):
if not issubdtype(type(x), self.dtype):
return False
min = -float("inf") if self.min is None else self.min
max = float("inf") if self.max is None else self.max
return min <= x <= max
def __repr__(self):
if self.min is None and self.max is None:
return self.dtype.__name__
lower_bound = "-inf" if self.min is None else self.min
upper_bound = "inf" if self.max is None else self.max
return f"{self.dtype.__name__}<{lower_bound},{upper_bound}>"
def __eq__(self, rhs):
"""Equality test."""
if not isinstance(rhs, Scalar):
return False
return (
self.name == rhs.name
and self.min == rhs.min
and self.max == rhs.max
and np.dtype(self.dtype) == np.dtype(rhs.dtype)
)
|
CompilerGym-development
|
compiler_gym/spaces/scalar.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from gym.spaces import Discrete as GymDiscrete
class Discrete(GymDiscrete):
"""A discrete space in :math:`{ 0, 1, \\dots, n-1 }`.
Wraps the underlying :code:`gym.spaces.Discrete` space with a name attribute.
"""
def __init__(self, n: int, name: str):
"""Constructor.
:param n: The upper bound.
:param name: The name of the space.
"""
super().__init__(n)
self.name = name
def __eq__(self, other) -> bool:
return (
isinstance(self, other.__class__)
and self.name == other.name
and super().__eq__(other)
)
|
CompilerGym-development
|
compiler_gym/spaces/discrete.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compiler_gym.spaces.action_space import ActionSpace
from compiler_gym.spaces.box import Box
from compiler_gym.spaces.commandline import Commandline, CommandlineFlag
from compiler_gym.spaces.dict import Dict
from compiler_gym.spaces.discrete import Discrete
from compiler_gym.spaces.named_discrete import NamedDiscrete
from compiler_gym.spaces.permutation import Permutation
from compiler_gym.spaces.reward import DefaultRewardFromObservation, Reward
from compiler_gym.spaces.runtime_reward import RuntimeReward
from compiler_gym.spaces.scalar import Scalar
from compiler_gym.spaces.sequence import Sequence
from compiler_gym.spaces.space_sequence import SpaceSequence
from compiler_gym.spaces.tuple import Tuple
__all__ = [
"ActionSpace",
"Box",
"Commandline",
"CommandlineFlag",
"DefaultRewardFromObservation",
"Dict",
"Discrete",
"NamedDiscrete",
"Permutation",
"Reward",
"RuntimeReward",
"Scalar",
"Sequence",
"SpaceSequence",
"Tuple",
]
|
CompilerGym-development
|
compiler_gym/spaces/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Iterable, List, NamedTuple
from compiler_gym.spaces.named_discrete import NamedDiscrete
class CommandlineFlag(NamedTuple):
"""A single flag in a Commandline space."""
name: str
"""The name of the flag, e.g. :code:`LoopUnroll`."""
flag: str
"""The flag string, e.g. :code:`--unroll`."""
description: str
"""A human-readable description of the flag."""
class Commandline(NamedDiscrete):
"""A :class:`NamedDiscrete <compiler_gym.spaces.NamedDiscrete>` space where
each element represents a commandline flag.
Example usage:
>>> space = Commandline([
CommandlineFlag("a", "-a", "A flag"),
CommandlineFlag("b", "-b", "Another flag"),
])
>>> space.n
2
>>> space["a"]
0
>>> space.names[0]
a
>>> space.flags[0]
-a
>>> space.descriptions[0]
A flag
>>> space.sample()
1
>>> space.commandline([0, 1])
-a -b
:ivar flags: A list of flag strings.
:ivar descriptions: A list of flag descriptions.
"""
def __init__(self, items: Iterable[CommandlineFlag], name: str):
"""Constructor.
:param items: The commandline flags that comprise the space.
:param name: The name of the space.
"""
items = list(items)
self.flags = [f.flag for f in items]
self.descriptions = [f.description for f in items]
super().__init__([f.flag for f in items], name=name)
def __repr__(self) -> str:
return f"Commandline([{' '.join(self.flags)}])"
def to_string(self, values: List[int]) -> str:
"""Produce a commandline invocation from a sequence of values.
:param values: A numeric value from the space, or sequence of values.
:return: A string commandline invocation.
"""
return " ".join([self.flags[v] for v in values])
def from_string(self, commandline: str) -> List[int]:
"""Produce a sequence of actions from a commandline.
:param commandline: A string commandline invocation, as produced by
:func:`to_string()
<compiler_gym.spaces.commandline.Commandline.to_string>`.
:return: A list of action values.
:raises LookupError: If any of the flags in the commandline are not
recognized.
"""
flags = commandline.split()
values = []
for flag in flags:
try:
values.append(self.flags.index(flag))
except IndexError:
raise LookupError(f"Unknown flag: `{flag}`")
return values
|
CompilerGym-development
|
compiler_gym/spaces/commandline.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from inspect import isclass
from numbers import Integral, Real
import numpy as np
def issubdtype(subtype, supertype):
if isclass(subtype) and isclass(supertype) and issubclass(subtype, supertype):
return True
subdtype = np.dtype(subtype)
superdtype = np.dtype(supertype)
if np.dtype(subdtype) == np.dtype(superdtype):
return True
common_dtype = np.find_common_type([], [subdtype, superdtype])
if not np.issubdtype(common_dtype, superdtype):
return False
if (
issubclass(common_dtype.type, Real)
and issubclass(subdtype.type, Integral)
and 2 ** np.finfo(common_dtype).nmant < np.iinfo(subdtype).max
):
return False
return True
|
CompilerGym-development
|
compiler_gym/spaces/common.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from numbers import Integral
import numpy as np
from compiler_gym.spaces.scalar import Scalar
from compiler_gym.spaces.sequence import Sequence
class Permutation(Sequence):
"""The space of permutations of all numbers in the range `scalar_range`."""
def __init__(self, name: str, scalar_range: Scalar):
"""Constructor.
:param name: The name of the permutation space.
:param scalar_range: Range of numbers in the permutation.
For example the scalar range [1, 3] would define permutations like
[1, 2, 3] or [2, 1, 3], etc.
:raises TypeError: If `scalar_range.dtype` is not an integral type.
"""
if not issubclass(np.dtype(scalar_range.dtype).type, Integral):
raise TypeError("Permutation space can have integral scalar range only.")
sz = scalar_range.max - scalar_range.min + 1
super().__init__(
name=name,
size_range=(sz, sz),
dtype=scalar_range.dtype,
scalar_range=scalar_range,
)
def sample(self):
return (
np.random.choice(self.size_range[0], size=self.size_range[1], replace=False)
+ self.scalar_range.min
)
def __eq__(self, other) -> bool:
return isinstance(self, other.__class__) and super().__eq__(other)
|
CompilerGym-development
|
compiler_gym/spaces/permutation.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections import Counter
from collections.abc import Iterable as IterableType
from typing import Iterable, List, Union
from compiler_gym.spaces.discrete import Discrete
from compiler_gym.util.gym_type_hints import ActionType
class NamedDiscrete(Discrete):
"""An extension of the :code:`Discrete` space in which each point in the
space has a name. Additionally, the space itself may have a name.
:ivar name: The name of the space.
:vartype name: str
:ivar names: A list of names for each element in the space.
:vartype names: List[str]
Example usage:
>>> space = NamedDiscrete(["a", "b", "c"])
>>> space.n
3
>>> space["a"]
0
>>> space.names[0]
a
>>> space.sample()
1
"""
def __init__(self, items: Iterable[str], name: str):
"""Constructor.
:param items: A list of names for items in the space.
:param name: The name of the space.
"""
items = list(items)
if not items:
raise ValueError("No values for discrete space")
self.names = [str(x) for x in items]
super().__init__(n=len(self.names), name=name)
def __getitem__(self, name: str) -> int:
"""Lookup the numeric value of a point in the space.
:param name: A name.
:return: The numeric value.
:raises ValueError: If the name is not in the space.
"""
return self.names.index(name)
def __repr__(self) -> str:
return f"NamedDiscrete([{', '.join(self.names)}])"
def to_string(self, values: Union[int, Iterable[ActionType]]) -> str:
"""Convert an action, or sequence of actions, to string.
:param values: A numeric value, or list of numeric values.
:return: A string representing the values.
"""
if isinstance(values, IterableType):
return " ".join([self.names[v] for v in values])
else:
return self.names[values]
def from_string(self, string: str) -> Union[ActionType, List[ActionType]]:
"""Convert a name, or list of names, to numeric values.
:param values: A name, or list of names.
:return: A numeric value, or list of numeric values.
"""
return [self.names.index(v) for v in string.split(" ")]
def __eq__(self, other) -> bool:
return (
isinstance(self, other.__class__)
and self.name == other.name
and Counter(self.names) == Counter(other.names)
and super().__eq__(other)
)
|
CompilerGym-development
|
compiler_gym/spaces/named_discrete.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict as DictType
from typing import List, Union
from gym.spaces import Dict as GymDict
from gym.spaces import Space
class Dict(GymDict):
"""A dictionary of simpler spaces.
Wraps the underlying :code:`gym.spaces.Dict` space with a name attribute.
"""
def __init__(self, spaces: Union[DictType[str, Space], List[Space]], name: str):
"""Constructor.
:param spaces: The composite spaces.
:param name: The name of the space.
"""
super().__init__(spaces)
self.name = name
def __eq__(self, other) -> bool:
return (
isinstance(self, other.__class__)
and self.name == other.name
and super().__eq__(other)
)
|
CompilerGym-development
|
compiler_gym/spaces/dict.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Tuple, Union
import numpy as np
import compiler_gym
from compiler_gym.spaces.scalar import Scalar
from compiler_gym.util.gym_type_hints import ActionType, ObservationType, RewardType
class Reward(Scalar):
"""An extension of the :class:`Scalar <compiler_gym.spaces.Scalar>` space
that is used for computing a reward signal.
A :code:`Reward` is a scalar value used to determine the reward for a
particular action. An instance of :code:`Reward` is used to represent the
reward function for a particular episode. For every
:meth:`env.step() <compiler_gym.envs.CompilerEnv.step>` of the environment,
the :meth:`reward.update() <compiler_gym.spaces.Reward.update>` method is
called to produce a new incremental reward.
Environments provide implementations of :code:`Reward` that compute reward
signals based on observation values computed by the backend service.
"""
def __init__(
self,
name: str,
observation_spaces: Optional[List[str]] = None,
default_value: RewardType = 0,
min: Optional[RewardType] = None,
max: Optional[RewardType] = None,
default_negates_returns: bool = False,
success_threshold: Optional[RewardType] = None,
deterministic: bool = False,
platform_dependent: bool = True,
):
"""Constructor.
:param name: The name of the reward space. This is a unique name used to
represent the reward.
:param observation_spaces: A list of observation space IDs
(:class:`space.id <compiler_gym.views.ObservationSpaceSpec>` values)
that are used to compute the reward. May be an empty list if no
observations are requested. Requested observations will be provided
to the :code:`observations` argument of :meth:`reward.update()
<compiler_gym.spaces.Reward.update>`.
:param default_value: A default reward. This value will be returned by
:meth:`env.step() <compiler_gym.envs.CompilerEnv.step>` if the
service terminates.
:param min: The lower bound of the reward.
:param max: The upper bound of the reward.
:param default_negates_returns: If true, the default value will be
offset by the sum of all rewards for the current episode. For
example, given a default reward value of *-10.0* and an episode with
prior rewards *[0.1, 0.3, -0.15]*, the default value is: *-10.0 -
sum(0.1, 0.3, -0.15)*.
:param success_threshold: The cumulative reward threshold before an
episode is considered successful. For example, episodes where reward
is scaled to an existing heuristic can be considered “successful”
when the reward exceeds the existing heuristic.
:param deterministic: Whether the reward space is deterministic.
:param platform_dependent: Whether the reward values depend on the
execution environment of the service.
"""
super().__init__(
name=name,
min=-np.inf if min is None else min,
max=np.inf if max is None else max,
dtype=np.float64,
)
self.name = name or id
if not self.name:
raise TypeError("No name given")
self.observation_spaces = observation_spaces or []
self.default_value: RewardType = default_value
self.default_negates_returns: bool = default_negates_returns
self.success_threshold = success_threshold
self.deterministic = deterministic
self.platform_dependent = platform_dependent
def reset(
self, benchmark: str, observation_view: "compiler_gym.views.ObservationView"
) -> None:
"""Reset the rewards space. This is called on
:meth:`env.reset() <compiler_gym.envs.CompilerEnv.reset>`.
:param benchmark: The URI of the benchmark that is used for this
episode.
:param observation: An observation view for reward initialization
"""
pass
def update(
self,
actions: List[ActionType],
observations: List[ObservationType],
observation_view: "compiler_gym.views.ObservationView", # noqa: F821
) -> RewardType:
"""Calculate a reward for the given action.
:param action: The action performed.
:param observations: A list of observation values as requested by the
:code:`observation_spaces` constructor argument.
:param observation_view: The
:class:`ObservationView <compiler_gym.views.ObservationView>`
instance.
"""
raise NotImplementedError("abstract class")
def reward_on_error(self, episode_reward: RewardType) -> RewardType:
"""Return the reward value for an error condition.
This method should be used to produce the reward value that should be
used if the compiler service cannot be reached, e.g. because it has
crashed or the connection has dropped.
:param episode_reward: The current cumulative reward of an episode.
:return: A reward.
"""
if self.default_negates_returns:
return self.default_value - episode_reward
else:
return self.default_value
@property
def range(self) -> Tuple[RewardType, RewardType]:
"""The lower and upper bounds of the reward."""
return (self.min, self.max)
def __repr__(self):
return self.name
def __eq__(self, other: Union["Reward", str]) -> bool:
if isinstance(other, str):
return self.name == other
elif isinstance(other, Reward):
return self.name == other.name
else:
return False
class DefaultRewardFromObservation(Reward):
def __init__(self, observation_name: str, **kwargs):
super().__init__(
observation_spaces=[observation_name], name=observation_name, **kwargs
)
self.previous_value: Optional[ObservationType] = None
def reset(self, benchmark: str, observation_view) -> None:
"""Called on env.reset(). Reset incremental progress."""
del benchmark # unused
self.previous_value = None
def update(
self,
action: int,
observations: List[ObservationType],
observation_view: "compiler_gym.views.ObservationView", # noqa: F821
) -> RewardType:
"""Called on env.step(). Compute and return new reward."""
del action # unused
del observation_view # unused
value: RewardType = observations[0]
if self.previous_value is None:
self.previous_value = 0
reward = RewardType(value - self.previous_value)
self.previous_value = value
return reward
|
CompilerGym-development
|
compiler_gym/spaces/reward.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional
from gym.spaces import Space
from compiler_gym.util.gym_type_hints import ActionType
class ActionSpace(Space):
"""A wrapper around a :code:`gym.spaces.Space` with additional functionality
for action spaces.
"""
def __init__(self, space: Space):
"""Constructor.
:param space: The space that this action space wraps.
"""
self.wrapped = space
def __getattr__(self, name: str):
return getattr(self.wrapped, name)
def __getitem__(self, name: str):
return self.wrapped[name]
def sample(self) -> ActionType:
return self.wrapped.sample()
def seed(self, seed: Optional[int] = None) -> ActionType:
return self.wrapped.seed(seed)
def contains(self, x: ActionType) -> bool:
"""Return boolean specifying if x is a valid member of this space."""
raise self.wrapped.contains(x)
def __contains__(self, x: ActionType) -> bool:
"""Return boolean specifying if x is a valid member of this space."""
return self.wrapped.contains(x)
def __eq__(self, rhs) -> bool:
if isinstance(rhs, ActionSpace):
return self.wrapped == rhs.wrapped
else:
return self.wrapped == rhs
def __ne__(self, rhs) -> bool:
if isinstance(rhs, ActionSpace):
return self.wrapped != rhs.wrapped
else:
return self.wrapped != rhs
def to_string(self, actions: List[ActionType]) -> str:
"""Render the provided list of actions to a string.
This method is used to produce a human-readable string to represent a
sequence of actions. Subclasses may override the default implementation
to provide custom rendering.
This is the complement of :meth:`from_string()
<compiler_gym.spaces.ActionSpace.from_string>`. The two methods
are bidirectional:
>>> actions = env.actions
>>> s = env.action_space.to_string(actions)
>>> actions == env.action_space.from_string(s)
True
:param actions: A list of actions drawn from this space.
:return: A string representation that can be decoded using
:meth:`from_string()
<compiler_gym.spaces.ActionSpace.from_string>`.
"""
if hasattr(self.wrapped, "to_string"):
return self.wrapped.to_string(actions)
return ",".join(str(x) for x in actions)
def from_string(self, string: str) -> List[ActionType]:
"""Return a list of actions from the given string.
This is the complement of :meth:`to_string()
<compiler_gym.spaces.ActionSpace.to_string>`. The two methods are
bidirectional:
>>> actions = env.actions
>>> s = env.action_space.to_string(actions)
>>> actions == env.action_space.from_string(s)
True
:param string: A string.
:return: A list of actions.
"""
if hasattr(self.wrapped, "from_string"):
return self.wrapped.from_string(string)
return [self.dtype.type(x) for x in string.split(",")]
def __repr__(self) -> str:
return f"{type(self).__name__}({self.wrapped})"
|
CompilerGym-development
|
compiler_gym/spaces/action_space.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Iterable, List, Optional
from compiler_gym.errors import BenchmarkInitError, ServiceError
from compiler_gym.spaces.reward import Reward
from compiler_gym.util.gym_type_hints import ActionType, ObservationType
class RuntimeReward(Reward):
def __init__(
self,
runtime_count: int,
warmup_count: int,
estimator: Callable[[Iterable[float]], float],
default_value: int = 0,
):
super().__init__(
name="runtime",
observation_spaces=["Runtime"],
default_value=default_value,
min=None,
max=None,
default_negates_returns=True,
deterministic=False,
platform_dependent=True,
)
self.runtime_count = runtime_count
self.warmup_count = warmup_count
self.starting_runtime: Optional[float] = None
self.previous_runtime: Optional[float] = None
self.current_benchmark: Optional[str] = None
self.estimator = estimator
def reset(self, benchmark, observation_view) -> None:
# If we are changing the benchmark then check that it is runnable.
if benchmark != self.current_benchmark:
if not observation_view["IsRunnable"]:
raise BenchmarkInitError(f"Benchmark is not runnable: {benchmark}")
self.current_benchmark = benchmark
self.starting_runtime = None
# Compute initial runtime if required, else use previously computed
# value.
if self.starting_runtime is None:
self.starting_runtime = self.estimator(observation_view["Runtime"])
self.previous_runtime = self.starting_runtime
def update(
self,
actions: List[ActionType],
observations: List[ObservationType],
observation_view,
) -> float:
del actions # unused
del observation_view # unused
runtimes = observations[0]
if len(runtimes) != self.runtime_count:
raise ServiceError(
f"Expected {self.runtime_count} runtimes but received {len(runtimes)}"
)
runtime = self.estimator(runtimes)
reward = self.previous_runtime - runtime
self.previous_runtime = runtime
return reward
|
CompilerGym-development
|
compiler_gym/spaces/runtime_reward.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This package contains modules that can be used for preparing leaderboard
submissions.
We provide `leaderboards
<https://github.com/facebookresearch/CompilerGym#leaderboards>`_ to track the
performance of user-submitted algorithms on compiler optimization tasks. The
goal of the leaderboards is to provide a venue for researchers to promote their
work, and to provide a common framework for evaluating and comparing different
approaches. We accept submissions to the leaderboards through pull requests, see
`here
<https://facebookresearch.github.io/CompilerGym/contributing.html#leaderboard-submissions>`_
for instructions.
"""
|
CompilerGym-development
|
compiler_gym/leaderboard/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""LLVM is a popular open source compiler used widely in industry and research.
The :code:`llvm-ic-v0` environment exposes LLVM's optimizing passes as a set of
actions that can be applied to a particular program. The goal of the agent is to
select the sequence of optimizations that lead to the greatest reduction in
instruction count in the program being compiled. Reward is the reduction in
instruction count achieved scaled to the reduction achieved by LLVM's builtin
:code:`-Oz` pipeline.
+--------------------+------------------------------------------------------+
| Property | Value |
+====================+======================================================+
| Environment | :class:`LlvmEnv <compiler_gym.envs.LlvmEnv>`. |
+--------------------+------------------------------------------------------+
| Observation Space | Any. |
+--------------------+------------------------------------------------------+
| Reward Space | Instruction count reduction relative to :code:`-Oz`. |
+--------------------+------------------------------------------------------+
| Test Dataset | The 23 cBench benchmarks. |
+--------------------+------------------------------------------------------+
Users who wish to create a submission for this leaderboard may use
:func:`eval_llvm_instcount_policy()
<compiler_gym.leaderboard.llvm_instcount.eval_llvm_instcount_policy>` to
automatically evaluate their agent on the test set.
"""
import logging
import os
from itertools import islice
from pathlib import Path
from threading import Thread
from time import sleep
from typing import Callable, List
import gym
import humanize
from absl import app, flags
import compiler_gym.envs # noqa Register environments.
from compiler_gym.bin.validate import main as validate
from compiler_gym.compiler_env_state import (
CompilerEnvState,
CompilerEnvStateReader,
CompilerEnvStateWriter,
)
from compiler_gym.envs import LlvmEnv
from compiler_gym.util.statistics import arithmetic_mean, geometric_mean
from compiler_gym.util.timer import Timer, humanize_duration_hms
flags.DEFINE_string(
"leaderboard_results",
"llvm_instcount-results.csv",
"The path of the file to write results to.",
)
flags.DEFINE_string(
"leaderboard_logfile",
"llvm_instcount-results.log",
"The path of a file to stream CompilerGym logs to.",
)
flags.DEFINE_integer(
"max_benchmarks",
0,
"If > 0, use only the the first --max_benchmarks benchmarks from the "
"dataset, as determined by alphabetical sort. If not set, all benchmarks "
"from the dataset are used.",
)
flags.DEFINE_integer(
"n", 10, "The number of repetitions of the search to run for each benchmark."
)
flags.DEFINE_string("test_dataset", "cbench-v1", "The dataset to use for the search.")
flags.DEFINE_boolean("validate", True, "Run validation on the results.")
flags.DEFINE_boolean(
"resume",
False,
"If true, read the --leaderboard_results file first and run only the "
"evaluations not already in the results file.",
)
FLAGS = flags.FLAGS
# A policy is a function that accepts as input an LLVM environment, and
# interacts with that environment with the goal of maximising cumulative reward.
Policy = Callable[[LlvmEnv], None]
class _EvalPolicyWorker(Thread):
"""Worker thread to evaluate a policy."""
def __init__(
self,
env: LlvmEnv,
benchmarks: List[str],
policy: Policy,
init_states: List[CompilerEnvState],
):
super().__init__()
self.env = env
self.benchmarks = benchmarks
self.policy = policy
self.states: List[CompilerEnvState] = init_states
self.alive = True
def run(self):
# Determine if we need to print a header.
header = (
not Path(FLAGS.leaderboard_results).is_file()
or os.stat(FLAGS.leaderboard_results).st_size == 0
)
with CompilerEnvStateWriter(
open(FLAGS.leaderboard_results, "a"), header=header
) as writer:
for benchmark in self.benchmarks:
self.env.reset(benchmark=benchmark)
with Timer() as timer:
self.policy(self.env)
# Sanity check that the policy didn't change the expected
# experimental setup.
assert self.env.in_episode, "Environment is no longer in an episode"
assert self.env.benchmark and (
self.env.benchmark == benchmark
), "Policy changed environment benchmark"
assert self.env.reward_space, "Policy unset environment reward space"
assert (
self.env.reward_space.name == "IrInstructionCountOz"
), "Policy changed environment reward space"
# Override walltime in the generated state.
state = self.env.state.copy()
state.walltime = timer.time
writer.write_state(state, flush=True)
self.states.append(state)
if not self.alive:
return
def eval_llvm_instcount_policy(policy: Policy) -> None:
"""Evaluate an LLVM codesize policy and generate results for a leaderboard
submission.
To use it, you define your policy as a function that takes an
:class:`LlvmEnv <compiler_gym.envs.LlvmEnv>` instance as input and modifies
it in place. For example, for a trivial random policy:
>>> from compiler_gym.envs import LlvmEnv
>>> def my_policy(env: LlvmEnv) -> None:
.... # Defines a policy that takes 10 random steps.
... for _ in range(10):
... _, _, done, _ = env.step(env.action_space.sample())
... if done: break
If your policy is stateful, you can use a class and override the
:code:`__call__()` method:
>>> class MyPolicy:
... def __init__(self):
... self.my_stateful_vars = {} # or similar
... def __call__(self, env: LlvmEnv) -> None:
... pass # ... do fun stuff!
>>> my_policy = MyPolicy()
The role of your policy is to perform a sequence of actions on the supplied
environment so as to maximize cumulative reward. By default, no observation
space is set on the environment, so :meth:`env.step()
<compiler_gym.envs.CompilerEnv.step>` will return :code:`None` for the
observation. You may set a new observation space:
>>> env.observation_space = "InstCount" # Set a new space for env.step()
>>> env.observation["InstCount"] # Calculate a one-off observation.
However, the policy may not change the reward space of the environment, or
the benchmark.
Once you have defined your policy, call the
:func:`eval_llvm_instcount_policy()
<compiler_gym.leaderboard.llvm_instcount.eval_llvm_instcount_policy>` helper
function, passing it your policy as its only argument:
>>> eval_llvm_instcount_policy(my_policy)
The :func:`eval_llvm_instcount_policy()
<compiler_gym.leaderboard.llvm_instcount.eval_llvm_instcount_policy>`
function calls the policy function for each benchmark in the dataset, one at
a time, from a single thread. Stateful policies can assume thread safe
access to member variables.
Put together as a complete example, a leaderboard submission script may look
like:
.. code-block:: python
# my_policy.py
from compiler_gym.leaderboard.llvm_instcount import eval_llvm_instcount_policy
from compiler_gym.envs import LlvmEnv
def my_policy(env: LlvmEnv) -> None:
env.observation_space = "InstCount" # we're going to use instcount space
pass # ... do fun stuff!
if __name__ == "__main__":
eval_llvm_instcount_policy(my_policy)
The :func:`eval_llvm_instcount_policy()
<compiler_gym.leaderboard.llvm_instcount.eval_llvm_instcount_policy>` helper
defines a number of commandline flags that can be overriden to control the
behavior of the evaluation. For example the flag :code:`--n` determines the
number of times the policy is run on each benchmark (default is 10), and
:code:`--leaderboard_results` determines the path of the generated results
file:
.. code-block::
$ python my_policy.py --n=5 --leaderboard_results=my_policy_results.csv
You can use :code:`--helpfull` flag to list all of the flags that are
defined:
.. code-block::
$ python my_policy.py --helpfull
Once you are happy with your approach, see the `contributing guide
<https://github.com/facebookresearch/CompilerGym/blob/development/CONTRIBUTING.md#leaderboard-submissions>`_
for instructions on preparing a submission to the leaderboard.
"""
def main(argv):
assert len(argv) == 1, f"Unknown args: {argv[:1]}"
assert FLAGS.n > 0, "n must be > 0"
with gym.make("llvm-ic-v0") as env:
# Stream verbose CompilerGym logs to file.
logger = logging.getLogger("compiler_gym")
logger.setLevel(logging.DEBUG)
log_handler = logging.FileHandler(FLAGS.leaderboard_logfile)
logger.addHandler(log_handler)
logger.propagate = False
print(f"Writing results to {FLAGS.leaderboard_results}")
print(f"Writing logs to {FLAGS.leaderboard_logfile}")
# Build the list of benchmarks to evaluate.
benchmarks = env.datasets[FLAGS.test_dataset].benchmark_uris()
if FLAGS.max_benchmarks:
benchmarks = islice(benchmarks, FLAGS.max_benchmarks)
benchmarks = list(benchmarks)
# Repeat the searches for the requested number of iterations.
benchmarks *= FLAGS.n
total_count = len(benchmarks)
# If we are resuming from a previous job, read the states that have
# already been proccessed and remove those benchmarks from the list
# of benchmarks to evaluate.
init_states = []
if FLAGS.resume and Path(FLAGS.leaderboard_results).is_file():
with CompilerEnvStateReader(open(FLAGS.leaderboard_results)) as reader:
for state in reader:
init_states.append(state)
if state.benchmark in benchmarks:
benchmarks.remove(state.benchmark)
# Run the benchmark loop in background so that we can asynchronously
# log progress.
worker = _EvalPolicyWorker(env, benchmarks, policy, init_states)
worker.start()
timer = Timer().reset()
try:
print(
f"=== Evaluating policy on "
f"{humanize.intcomma(total_count)} "
f"{FLAGS.test_dataset} benchmarks ==="
"\n\n" # Blank lines will be filled below
)
while worker.is_alive():
done_count = len(worker.states)
remaining_count = total_count - done_count
time = timer.time
gmean_reward = geometric_mean([s.reward for s in worker.states])
mean_walltime = (
arithmetic_mean([s.walltime for s in worker.states]) or time
)
print(
"\r\033[2A"
"\033[K"
f"Runtime: {humanize_duration_hms(time)}. "
f"Estimated completion: {humanize_duration_hms(mean_walltime * remaining_count)}. "
f"Completed: {humanize.intcomma(done_count)} / {humanize.intcomma(total_count)} "
f"({done_count / total_count:.1%})."
"\n\033[K"
f"Current mean walltime: {mean_walltime:.3f}s / benchmark."
"\n\033[K"
f"Current geomean reward: {gmean_reward:.4f}.",
flush=True,
end="",
)
sleep(1)
except KeyboardInterrupt:
print("\nkeyboard interrupt", flush=True)
worker.alive = False
# User interrupt, don't validate.
FLAGS.validate = False
if FLAGS.validate:
FLAGS.env = "llvm-ic-v0"
validate(["argv0", FLAGS.leaderboard_results])
app.run(main)
|
CompilerGym-development
|
compiler_gym/leaderboard/llvm_instcount.py
|
# Protoxygen, from https://github.com/lisroach/Protoxygen
##
# Doxygen filter for Google Protocol Buffers .proto files.
# This script converts .proto files into C++ style ones
# and prints the output to standard output.
#
# version 0.6-beta
#
# How to enable this filter in Doxygen:
# 1. Generate Doxygen configuration file with command 'doxygen -g <filename>'
# e.g. doxygen -g doxyfile
# 2. In the Doxygen configuration file, find JAVADOC_AUTOBRIEF and set it enabled
# JAVADOC_AUTOBRIEF = YES
# 3. In the Doxygen configuration file, find FILE_PATTERNS and add *.proto
# FILE_PATTERNS = *.proto
# 4. In the Doxygen configuration file, find EXTENSION_MAPPING and add proto=C
# EXTENSION_MAPPING = proto=C
# 5. In the Doxygen configuration file, find INPUT_FILTER and add this script
# INPUT_FILTER = "python proto2cpp.py"
# 6. Run Doxygen with the modified configuration
# doxygen doxyfile
#
#
# Copyright (C) 2012-2015 Timo Marjoniemi
# All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
##
import fnmatch
import inspect
import os
import re
import sys
# Class for converting Google Protocol Buffers .proto files into C++ style output to enable Doxygen usage.
##
# The C++ style output is printed into standard output.<br />
# There are three different logging levels for the class:
# <ul><li>#logNone: do not log anything</li>
# <li>#logErrors: log errors only</li>
# <li>#logAll: log everything</li></ul>
# Logging level is determined by \c #logLevel.<br />
# Error logs are written to file determined by \c #errorLogFile.<br />
# Debug logs are written to file determined by \c #logFile.
#
class proto2cpp:
# Logging level: do not log anything.
logNone = 0
# Logging level: log errors only.
logErrors = 1
# Logging level: log everything.
logAll = 2
# Conmessageor
#
def __init__(self):
# Debug log file name.
self.logFile = "proto2cpp.log"
# Error log file name.
self.errorLogFile = "proto2cpp.error.log"
# Logging level.
self.logLevel = self.logNone
# Handles a file.
##
# If @p fileName has .proto suffix, it is processed through parseFile().
# Otherwise it is printed to stdout as is except for file \c proto2cpp.py without
# path since it's the script given to python for processing.
##
# @param fileName Name of the file to be handled.
#
def handleFile(self, fileName):
if fnmatch.fnmatch(filename, "*.proto"):
self.log("\nXXXXXXXXXX\nXX " + filename + "\nXXXXXXXXXX\n\n")
# Open the file. Use try to detect whether or not we have an actual
# file.
try:
with open(filename, "r") as inputFile:
self.parseFile(inputFile)
pass
except IOError:
self.logError(
"the file " + filename + " could not be opened for reading"
)
elif not fnmatch.fnmatch(
filename, os.path.basename(inspect.getfile(inspect.currentframe()))
):
self.log("\nXXXXXXXXXX\nXX " + filename + "\nXXXXXXXXXX\n\n")
try:
with open(filename, "r") as theFile:
output = ""
for theLine in theFile:
output += theLine
print(output)
self.log(output)
pass
except IOError:
self.logError(
"the file " + filename + " could not be opened for reading"
)
else:
self.log("\nXXXXXXXXXX\nXX " + filename + " --skipped--\nXXXXXXXXXX\n\n")
# Parser function.
##
# The function takes a .proto file object as input
# parameter and modifies the contents into C++ style.
# The modified data is printed into standard output.
##
# @param inputFile Input file object
#
def parseFile(self, inputFile):
# Go through the input file line by line.
isEnum = False
# This variable is here as a workaround for not getting extra line breaks (each line
# ends with a line separator and print() method will add another one).
# We will be adding lines into this var and then print the var out at
# the end.
theOutput = ""
for line in inputFile:
# Search for comment ("//") and add one more slash character ("/") to the comment
# block to make Doxygen detect it.
matchComment = re.search("//", line)
# Search for semicolon and if one is found before comment, add a third slash character
# ("/") and a smaller than ("<") chracter to the comment to make Doxygen detect it.
matchSemicolon = re.search(";", line)
if matchSemicolon is not None and (
matchComment is not None
and matchSemicolon.start() < matchComment.start()
):
line = (
line[: matchComment.start()] + "///<" + line[matchComment.end() :]
)
elif matchSemicolon is not None and (
matchComment is not None
and matchSemicolon.start() > matchComment.start()
):
line = line.replace("//", "")
elif matchComment is not None:
line = line[: matchComment.start()] + "///" + line[matchComment.end() :]
# Search for "enum" and if one is found before comment,
# start changing all semicolons (";") to commas (",").
matchEnum = re.search("enum", line)
if matchEnum is not None and (
matchComment is None or matchEnum.start() < matchComment.start()
):
isEnum = True
# Search again for semicolon if we have detected an enum, and
# replace semicolon with comma.
if isEnum is True and re.search(";", line) is not None:
matchSemicolon = re.search(";", line)
line = (
line[: matchSemicolon.start()] + "," + line[matchSemicolon.end() :]
)
# Search for a closing brace.
matchClosingBrace = re.search("}", line)
if isEnum is True and matchClosingBrace is not None:
line = (
line[: matchClosingBrace.start()]
+ "};"
+ line[matchClosingBrace.end() :]
)
isEnum = False
elif isEnum is False and re.search("}", line) is not None:
# Message (to be struct) ends => add semicolon so that it'll
# be a proper C(++) message and Doxygen will handle it
# correctly.
line = (
line[: matchClosingBrace.start()]
+ "};"
+ line[matchClosingBrace.end() :]
)
# Search for 'import' and replace it with '#include' unless
# 'import' is behind a comment.
matchMsg = re.search("message", line)
if matchMsg is not None and (
matchComment is None or matchMsg.start() < matchComment.start()
):
line = "struct" + line[: matchMsg.start()] + line[matchMsg.end() :]
matchSrv = re.search("^service", line)
if matchSrv is not None and (
matchComment is None or matchSrv.start() < matchComment.start()
):
line = "namespace" + line[: matchSrv.start()] + line[matchSrv.end() :]
matchImp = re.search("import", line)
if matchImp is not None and (
matchComment is None or matchImp.start() < matchComment.start()
):
line = "#include" + line[: matchImp.start()] + line[matchImp.end() :]
else:
theOutput += line
# Search for 'stuct' and replace it with 'message' unless 'message'
# is behind a comment.
# Now that we've got all lines in the string let's split the lines and print out
# one by one.
# This is a workaround to get rid of extra empty line at the end which
# print() method adds.
lines = theOutput.splitlines()
for line in lines:
if len(line) > 0:
print(line)
# Our logger does not add extra line breaks so explicitly
# adding one to make the log more readable.
self.log(line + "\n")
else:
self.log("\n --- skipped empty line")
# Writes @p string to log file.
##
# logLevel must be #logAll or otherwise the logging is skipped.
##
# @param string String to be written to log file.
#
def log(self, string):
if self.logLevel >= self.logAll:
with open(self.logFile, "a") as theFile:
theFile.write(string)
# Writes @p string to error log file.
##
# logLevel must be #logError or #logAll or otherwise the logging is skipped.
##
# @param string String to be written to error log file.
#
def logError(self, string):
if self.logLevel >= self.logError:
with open(self.errorLogFile, "a") as theFile:
theFile.write(string)
converter = proto2cpp()
# Doxygen will give us the file names
for filename in sys.argv[1:]:
converter.handleFile(filename)
# end of file
|
CompilerGym-development
|
compiler_gym/third_party/proto2cpp.py
|
"""This module defines an API for processing LLVM-IR with inst2vec."""
import pickle
from typing import List
import numpy as np
from compiler_gym.third_party.inst2vec import inst2vec_preprocess
from compiler_gym.util.runfiles_path import runfiles_path
_PICKLED_VOCABULARY = runfiles_path(
"compiler_gym/third_party/inst2vec/dictionary.pickle"
)
_PICKLED_EMBEDDINGS = runfiles_path(
"compiler_gym/third_party/inst2vec/embeddings.pickle"
)
class Inst2vecEncoder:
"""An LLVM encoder for inst2vec."""
def __init__(self):
# TODO(github.com/facebookresearch/CompilerGym/issues/122): Lazily
# instantiate inst2vec encoder.
with open(str(_PICKLED_VOCABULARY), "rb") as f:
self.vocab = pickle.load(f)
with open(str(_PICKLED_EMBEDDINGS), "rb") as f:
self.embeddings = pickle.load(f)
self.unknown_vocab_element = self.vocab["!UNK"]
def preprocess(self, ir: str) -> List[str]:
"""Produce a list of pre-processed statements from an IR."""
lines = [[x] for x in ir.split("\n")]
try:
structs = inst2vec_preprocess.GetStructTypes(ir)
for line in lines:
for struct, definition in structs.items():
line[0] = line[0].replace(struct, definition)
except ValueError:
pass
preprocessed_lines, _ = inst2vec_preprocess.preprocess(lines)
preprocessed_texts = [
inst2vec_preprocess.PreprocessStatement(x[0]) if len(x) else ""
for x in preprocessed_lines
]
return [x for x in preprocessed_texts if x]
def encode(self, preprocessed: List[str]) -> List[int]:
"""Produce embedding indices for a list of pre-processed statements."""
return [
self.vocab.get(statement, self.unknown_vocab_element)
for statement in preprocessed
]
def embed(self, encoded: List[int]) -> np.ndarray:
"""Produce a matrix of embeddings from a list of encoded statements."""
return np.vstack([self.embeddings[index] for index in encoded])
|
CompilerGym-development
|
compiler_gym/third_party/inst2vec/__init__.py
|
# NCC: Neural Code Comprehension
# https://github.com/spcl/ncc
# Copyright 2018 ETH Zurich
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ==============================================================================
# flake8: noqa
"""Helper variables and functions for regular expressions and statement tags"""
import re
########################################################################################################################
# Regex manipulation: helper functions
########################################################################################################################
def any_of(possibilities, to_add=""):
r"""
Helper function for regex manipulation:
Construct a regex representing "any of" the given possibilities
:param possibilities: list of strings representing different word possibilities
:param to_add: string to add at the beginning of each possibility (optional)
:return: string corresponding to regex which represents any of the given possibilities
r"""
assert len(possibilities) > 0
s = r"(?:"
if len(to_add) > 0:
s += possibilities[0] + to_add + r" "
else:
s += possibilities[0]
for i in range(len(possibilities) - 1):
if len(to_add) > 0:
s += r"|" + possibilities[i + 1] + to_add + r" "
else:
s += r"|" + possibilities[i + 1]
return s + r")"
########################################################################################################################
# Regex manipulation: helper variables
########################################################################################################################
# Identifiers
global_id = r'(?<!%")@[r"\w\d\.\-\_\$\\]+'
local_id_no_perc = r'[r"\@\d\w\.\-\_\:]+'
local_id = r"%" + local_id_no_perc
local_or_global_id = r"(" + global_id + r"|" + local_id + r")"
# Options and linkages
linkage = any_of(
[
r" private",
r" external",
r" internal",
r" linkonce_odr",
r" appending",
r" external",
r" internal",
r" unnamed_addr",
r" common",
r" hidden",
r" weak",
r" linkonce",
r" extern_weak",
r" weak_odr",
r" private",
r" available_externally",
r" local_unnamed_addr",
r" thread_local",
r" linker_private",
]
)
# Immediate values
immediate_value_ad_hoc = r"#[\d\w]+"
immediate_value_true = r"true"
immediate_value_false = r"false"
immediate_value_bool = (
r"(?:" + immediate_value_true + r"|" + immediate_value_false + r")"
)
immediate_value_int = r"(?<!\w)[-]?[0-9]+"
immediate_value_float_sci = r"(?<!\w)[-]?[0-9]+\.[0-9]+(?:e\+?-?[0-9]+)?"
immediate_value_float_hexa = r"(?<!\w)[-]?0[xX][hklmHKLM]?[A-Fa-f0-9]+"
immediate_value_float = (
r"(?:" + immediate_value_float_sci + r"|" + immediate_value_float_hexa + r")"
)
immediate_value_vector_bool = (
r"<i1 "
+ immediate_value_bool
+ r"(?:, i1 (?:"
+ immediate_value_bool
+ r"|undef))*>"
)
immediate_value_vector_int = (
r"<i\d+ r"
+ immediate_value_int
+ r"(?:, i\d+ (?:"
+ immediate_value_int
+ r"|undef))*>"
)
immediate_value_vector_float = (
r"<float "
+ immediate_value_float
+ r"(?:, float (?:"
+ immediate_value_float
+ r"|undef))*>"
)
immediate_value_vector_double = (
r"<double "
+ immediate_value_float
+ r"(?:, double (?:"
+ immediate_value_float
+ r"|undef))*>"
)
immediate_value_string = r'(?<!\w)c".+"'
immediate_value_misc = r"(?:null|zeroinitializer)"
immediate_value = any_of(
[
immediate_value_true,
immediate_value_false,
immediate_value_int,
immediate_value_float_sci,
immediate_value_float_hexa,
immediate_value_string,
immediate_value_misc,
]
)
immediate_value_undef = r"undef"
immediate_value_or_undef = any_of(
[
immediate_value_true,
immediate_value_false,
immediate_value_int,
immediate_value_float_sci,
immediate_value_float_hexa,
immediate_value_string,
immediate_value_misc,
immediate_value_ad_hoc,
immediate_value_undef,
]
)
# Combos
immediate_or_local_id = any_of(
[
immediate_value_true,
immediate_value_false,
immediate_value_int,
immediate_value_float_sci,
immediate_value_float_hexa,
immediate_value_vector_int,
immediate_value_vector_float,
immediate_value_vector_double,
local_id,
immediate_value_misc,
]
)
immediate_or_local_id_or_undef = any_of(
[
immediate_value_true,
immediate_value_false,
immediate_value_int,
immediate_value_float_sci,
immediate_value_float_hexa,
immediate_value_vector_int,
immediate_value_vector_float,
immediate_value_vector_double,
local_id,
immediate_value_misc,
immediate_value_undef,
]
)
# Names of aggregate types
# Lookahead so that names like '%struct.attribute_group**' won't be matched as just %struct.attribute
struct_lookahead = r"(?=[\s,\*\]\}])"
struct_name_add_on = r'(?:\([\w\d=]+\)")?'
struct_name_without_lookahead = (
r'%[r"\@\d\w\.\-\_:]+(?:(?:<[r"\@\d\w\.\-\_:,<>\(\) \*]+>|\([r"\@\d\w\.\-\_:,<> \*]+\)|\w+)?::[r" \@\d\w\.\-\_:\)\(]*)*'
+ struct_name_add_on
)
struct_name = struct_name_without_lookahead + struct_lookahead
# Functions
func_name = r"@[\"\w\d\._\$\\]+"
func_call_pattern = r".* @[\w\d\._]+"
func_call_pattern_or_bitcast = r"(.* @[\w\d\._]+|.*bitcast .* @[\w\d\._]+ to .*)"
# new basic block
start_basic_block = (
r"((?:<label>:)?(" + local_id_no_perc + r"):|; <label>:" + local_id_no_perc + r" )"
)
# Types
base_type = r"(?:i\d+|double|float|opaque)\**"
first_class_types = [
r"i\d+",
r"half",
r"float",
r"double",
r"fp_128",
r"x86_fp80",
r"ppc_fp128",
r"<%ID>",
]
first_class_type = any_of(first_class_types) + r"\**"
base_type_or_struct_name = any_of([base_type, struct_name_without_lookahead])
ptr_to_base_type = base_type + r"\*+"
vector_type = r"<\d+ x " + base_type + r">"
ptr_to_vector_type = vector_type + r"\*+"
array_type = r"\[\d+ x " + base_type + r"\]"
ptr_to_array_type = array_type + r"\*+"
array_of_array_type = r"\[\d+ x " + r"\[\d+ x " + base_type + r"\]" + r"\]"
struct = struct_name_without_lookahead
ptr_to_struct = struct + r"\*+"
function_type = (
base_type
+ r" \("
+ any_of([base_type, vector_type, array_type, "..."], ",")
+ r"*"
+ any_of([base_type, vector_type, array_type, "..."])
+ r"\)\**"
)
any_type = any_of(
[
base_type,
ptr_to_base_type,
vector_type,
ptr_to_vector_type,
array_type,
ptr_to_array_type,
]
)
any_type_or_struct = any_of(
[
base_type,
ptr_to_base_type,
vector_type,
ptr_to_vector_type,
array_type,
ptr_to_array_type,
ptr_to_struct,
]
)
structure_entry = any_of(
[
base_type,
vector_type,
array_type,
array_of_array_type,
function_type,
r"{ .* }\**",
]
)
structure_entry_with_comma = any_of(
[base_type, vector_type, array_type, array_of_array_type, function_type], ","
)
literal_structure = (
r"(<?{ " + structure_entry_with_comma + r"*" + structure_entry + r" }>?|{})"
)
# Tokens
unknown_token = r"!UNK" # starts with '!' to guarantee it will appear first in the alphabetically sorted vocabulary
########################################################################################################################
# Tags for clustering statements (by statement semantics) and helper functions
########################################################################################################################
# List of families of operations
llvm_IR_stmt_families = [
# [r"tag level 1", r"tag level 2", r"tag level 3", r"regex" ]
[r"unknown token", "unknown token", "unknown token", "!UNK"],
[r"integer arithmetic", "addition", "add integers", "<%ID> = add .*"],
[r"integer arithmetic", "subtraction", "subtract integers", "<%ID> = sub .*"],
[
r"integer arithmetic",
r"multiplication",
r"multiply integers",
r"<%ID> = mul .*",
],
[
r"integer arithmetic",
r"division",
r"unsigned integer division",
r"<%ID> = udiv .*",
],
[
r"integer arithmetic",
r"division",
r"signed integer division",
r"<%ID> = sdiv .*",
],
[
r"integer arithmetic",
r"remainder",
r"remainder of signed div",
r"<%ID> = srem .*",
],
[
r"integer arithmetic",
r"remainder",
r"remainder of unsigned div.",
r"<%ID> = urem .*",
],
[r"floating-point arithmetic", "addition", "add floats", "<%ID> = fadd .*"],
[
r"floating-point arithmetic",
r"subtraction",
r"subtract floats",
r"<%ID> = fsub .*",
],
[
r"floating-point arithmetic",
r"multiplication",
r"multiply floats",
r"<%ID> = fmul .*",
],
[r"floating-point arithmetic", "division", "divide floats", "<%ID> = fdiv .*"],
[r"bitwise arithmetic", "and", "and", "<%ID> = and .*"],
[r"bitwise arithmetic", "or", "or", "<%ID> = or .*"],
[r"bitwise arithmetic", "xor", "xor", "<%ID> = xor .*"],
[r"bitwise arithmetic", "shift left", "shift left", "<%ID> = shl .*"],
[r"bitwise arithmetic", "arithmetic shift right", "ashr", "<%ID> = ashr .*"],
[
r"bitwise arithmetic",
r"logical shift right",
r"logical shift right",
r"<%ID> = lshr .*",
],
[
r"comparison operation",
r"compare integers",
r"compare integers",
r"<%ID> = icmp .*",
],
[
r"comparison operation",
r"compare floats",
r"compare floats",
r"<%ID> = fcmp .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast single val",
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque) .* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast single val*",
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\* .* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast single val**",
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\*\* .* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast single val***",
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\*\*\* .* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast single val****",
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\*\*\*\* .* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast array",
r"<%ID> = bitcast \[\d.* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast vector",
r"<%ID> = bitcast <\d.* to .*",
],
[
r"conversion operation",
r"bitcast",
r"bitcast structure",
r'<%ID> = bitcast (%"|<{|<%|{).* to .*',
],
[r"conversion operation", "bitcast", "bitcast void", "<%ID> = bitcast void "],
[
r"conversion operation",
r"extension/truncation",
r"extend float",
r"<%ID> = fpext .*",
],
[
r"conversion operation",
r"extension/truncation",
r"truncate floats",
r"<%ID> = fptrunc .*",
],
[
r"conversion operation",
r"extension/truncation",
r"sign extend ints",
r"<%ID> = sext .*",
],
[
r"conversion operation",
r"extension/truncation",
r"truncate int to ... ",
r"<%ID> = trunc .* to .*",
],
[
r"conversion operation",
r"extension/truncation",
r"zero extend integers",
r"<%ID> = zext .*",
],
[
r"conversion operation",
r"convert",
r"convert signed integers to... ",
r"<%ID> = sitofp .*",
],
[
r"conversion operation",
r"convert",
r"convert unsigned integer to... ",
r"<%ID> = uitofp .*",
],
[
r"conversion operation",
r"convert int to ptr",
r"convert int to ptr",
r"<%ID> = inttoptr .*",
],
[
r"conversion operation",
r"convert ptr to int",
r"convert ptr to int",
r"<%ID> = ptrtoint .*",
],
[
r"conversion operation",
r"convert floats",
r"convert float to sint",
r"<%ID> = fptosi .*",
],
[
r"conversion operation",
r"convert floats",
r"convert float to uint",
r"<%ID> = fptoui .*",
],
[r"control flow", "phi", "phi", "<%ID> = phi .*"],
[
r"control flow",
r"switch",
r"jump table line",
r"i\d{1,2} <(INT|FLOAT)>, label <%ID>",
],
[r"control flow", "select", "select", "<%ID> = select .*"],
[r"control flow", "invoke", "invoke and ret type", "<%ID> = invoke .*"],
[r"control flow", "invoke", "invoke void", "invoke (fastcc )?void .*"],
[r"control flow", "branch", "branch conditional", "br i1 .*"],
[r"control flow", "branch", "branch unconditional", "br label .*"],
[r"control flow", "branch", "branch indirect", "indirectbr .*"],
[r"control flow", "control flow", "switch", "switch .*"],
[r"control flow", "return", "return", "ret .*"],
[r"control flow", "resume", "resume", "resume .*"],
[r"control flow", "unreachable", "unreachable", "unreachable.*"],
[r"control flow", "exception handling", "catch block", "catch .*"],
[r"control flow", "exception handling", "cleanup clause", "cleanup"],
[
r"control flow",
r"exception handling",
r"landingpad for exceptions",
r"<%ID> = landingpad .",
],
[
r"function",
r"function call",
r"sqrt (llvm-intrinsic)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>) @(llvm|llvm\..*)\.sqrt.*",
],
[
r"function",
r"function call",
r"fabs (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.fabs.*",
],
[
r"function",
r"function call",
r"max (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.max.*",
],
[
r"function",
r"function call",
r"min (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.min.*",
],
[
r"function",
r"function call",
r"fma (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.fma.*",
],
[
r"function",
r"function call",
r"phadd (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.phadd.*",
],
[
r"function",
r"function call",
r"pabs (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.pabs.*",
],
[
r"function",
r"function call",
r"pmulu (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call (fast |)?(i\d+|float|double|x86_fp80|<%ID>|<\d x float>|<\d x double>|<\d x i\d+>) @(llvm|llvm\..*)\.pmulu.*",
],
[
r"function",
r"function call",
r"umul (llvm-intr.)",
r"<%ID> = (tail |musttail |notail )?call {.*} @llvm\.umul.*",
],
[
r"function",
r"function call",
r"prefetch (llvm-intr.)",
r"(tail |musttail |notail )?call void @llvm\.prefetch.*",
],
[
r"function",
r"function call",
r"trap (llvm-intr.)",
r"(tail |musttail |notail )?call void @llvm\.trap.*",
],
[r"function", "func decl / def", "function declaration", "declare .*"],
[r"function", "func decl / def", "function definition", "define .*"],
[
r"function",
r"function call",
r"function call void",
r"(tail |musttail |notail )?call( \w+)? void [\w\)\(\}\{\.\,\*\d\[\]\s<>%]*(<[@%]ID>\(|.*bitcast )",
],
[
r"function",
r"function call",
r"function call mem lifetime",
r"(tail |musttail |notail )?call( \w+)? void ([\w)(\.\,\*\d ])*@llvm\.lifetime.*",
],
[
r"function",
r"function call",
r"function call mem copy",
r"(tail |musttail |notail )?call( \w+)? void ([\w)(\.\,\*\d ])*@llvm\.memcpy\..*",
],
[
r"function",
r"function call",
r"function call mem set",
r"(tail |musttail |notail )?call( \w+)? void ([\w)(\.\,\*\d ])*@llvm\.memset\..*",
],
[
r"function",
r"function call",
r"function call single val",
r"<%ID> = (tail |musttail |notail )?call[^{]* (i\d+|float|double|x86_fp80|<\d+ x (i\d+|float|double)>) (.*<[@%]ID>\(|(\(.*\) )?bitcast ).*",
],
[
r"function",
r"function call",
r"function call single val*",
r"<%ID> = (tail |musttail |notail )?call[^{]* (i\d+|float|double|x86_fp80)\* (.*<[@%]ID>\(|\(.*\) bitcast ).*",
],
[
r"function",
r"function call",
r"function call single val**",
r"<%ID> = (tail |musttail |notail )?call[^{]* (i\d+|float|double|x86_fp80)\*\* (.*<[@%]ID>\(|\(.*\) bitcast ).*",
],
[
r"function",
r"function call",
r"function call array",
r"<%ID> = (tail |musttail |notail )?call[^{]* \[.*\] (\(.*\) )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call array*",
r"<%ID> = (tail |musttail |notail )?call[^{]* \[.*\]\* (\(.*\) )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call array**",
r"<%ID> = (tail |musttail |notail )?call[^{]* \[.*\]\*\* (\(.*\) )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call structure",
r"<%ID> = (tail |musttail |notail )?call[^{]* (\{ .* \}[\w\_]*|<?\{ .* \}>?|opaque|\{\}|<%ID>) (\(.*\)\*? )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call structure*",
r"<%ID> = (tail |musttail |notail )?call[^{]* (\{ .* \}[\w\_]*|<?\{ .* \}>?|opaque|\{\}|<%ID>)\* (\(.*\)\*? )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call structure**",
r"<%ID> = (tail |musttail |notail )?call[^{]* (\{ .* \}[\w\_]*|<?\{ .* \}>?|opaque|\{\}|<%ID>)\*\* (\(.*\)\*? )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call structure***",
r"<%ID> = (tail |musttail |notail )?call[^{]* (\{ .* \}[\w\_]*|<?\{ .* \}>?|opaque|\{\}|<%ID>)\*\*\* (\(.*\)\*? )?(<[@%]ID>\(|\(.*\) bitcast )",
],
[
r"function",
r"function call",
r"function call asm value",
r"<%ID> = (tail |musttail |notail )?call.* asm .*",
],
[
r"function",
r"function call",
r"function call asm void",
r"(tail |musttail |notail )?call void asm .*",
],
[
r"function",
r"function call",
r"function call function",
r"<%ID> = (tail |musttail |notail )?call[^{]* void \([^\(\)]*\)\** <[@%]ID>\(",
],
[
r"global variables",
r"glob. var. definition",
r"???",
r"<@ID> = (?!.*constant)(?!.*alias).*",
],
[r"global variables", "constant definition", "???", "<@ID> = .*constant .*"],
[
r"memory access",
r"load from memory",
r"load structure",
r'<%ID> = load (\w* )?(%"|<\{|\{ <|\{ \[|\{ |<%|opaque).*',
],
[
r"memory access",
r"load from memory",
r"load single val",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val*",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val**",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val***",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*\*\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val****",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*\*\*\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val*****",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*\*\*\*\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val******",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*\*\*\*\*\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load single val*******",
r"<%ID> = load (\w* )?(i\d+|float|double|x86_fp80)\*\*\*\*\*\*\*[, ].*",
],
[
r"memory access",
r"load from memory",
r"load vector",
r"<%ID> = load <\d+ x .*",
],
["memory access", "load from memory", "load array", r"<%ID> = load \[\d.*"],
[
r"memory access",
r"load from memory",
r"load fction ptr",
r"<%ID> = load void \(",
],
[r"memory access", "store", "store", "store.*"],
[r"memory addressing", "GEP", "GEP", r"<%ID> = getelementptr .*"],
[
r"memory allocation",
r"allocate on stack",
r"allocate structure",
r'<%ID> = alloca (%"|<{|<%|{ |opaque).*',
],
[
r"memory allocation",
r"allocate on stack",
r"allocate vector",
r"<%ID> = alloca <\d.*",
],
[
r"memory allocation",
r"allocate on stack",
r"allocate array",
r"<%ID> = alloca \[\d.*",
],
[
r"memory allocation",
r"allocate on stack",
r"allocate single value",
r"<%ID> = alloca (double|float|i\d{1,3})\*?.*",
],
[
r"memory allocation",
r"allocate on stack",
r"allocate void",
r"<%ID> = alloca void \(.*",
],
[
r"memory atomics",
r"atomic memory modify",
r"atomicrw xchg",
r"<%ID> = atomicrmw.* xchg .*",
],
[
r"memory atomics",
r"atomic memory modify",
r"atomicrw add",
r"<%ID> = atomicrmw.* add .*",
],
[
r"memory atomics",
r"atomic memory modify",
r"atomicrw sub",
r"<%ID> = atomicrmw.* sub .*",
],
[
r"memory atomics",
r"atomic memory modify",
r"atomicrw or",
r"<%ID> = atomicrmw.* or .*",
],
[
r"memory atomics",
r"atomic compare exchange",
r"cmpxchg single val",
r"<%ID> = cmpxchg (weak )?(i\d+|float|double|x86_fp80)\*",
],
[
r"non-instruction",
r"label",
r"label declaration",
r"; <label>:.*(\s+; preds = <LABEL>)?",
],
[
r"non-instruction",
r"label",
r"label declaration",
r"<LABEL>:( ; preds = <LABEL>)?",
],
[
r"value aggregation",
r"extract value",
r"extract value",
r"<%ID> = extractvalue .*",
],
[
r"value aggregation",
r"insert value",
r"insert value",
r"<%ID> = insertvalue .*",
],
[
r"vector operation",
r"insert element",
r"insert element",
r"<%ID> = insertelement .*",
],
[
r"vector operation",
r"extract element",
r"extract element",
r"<%ID> = extractelement .*",
],
[
r"vector operation",
r"shuffle vector",
r"shuffle vector",
r"<%ID> = shufflevector .*",
],
]
# Helper functions for exploring llvm_IR_families
def get_list_tag_level_1():
r"""
Get the list of all level-1 tags in the data structure llvm_IR_families
:return: list containing strings corresponding to all level 1 tags
r"""
list_tags = list()
for fam in llvm_IR_stmt_families:
list_tags.append(fam[0])
return list(set(list_tags))
def get_list_tag_level_2(tag_level_1="all"):
r"""
Get the list of all level-2 tags in the data structure llvm_IR_families
corresponding to the string given as an input, or absolutely all of them
if input == r'all'
:param tag_level_1: string containing the level-1 tag to query, or 'all'
:return: list of strings
r"""
# Make sure the input parameter is valid
assert tag_level_1 in get_list_tag_level_1() or tag_level_1 == r"all", (
tag_level_1 + r" invalid"
)
list_tags = list()
if tag_level_1 == r"all":
for fam in llvm_IR_stmt_families:
list_tags.append(fam[1])
list_tags = sorted(set(list_tags))
else:
for fam in llvm_IR_stmt_families:
if fam[0] == tag_level_1:
list_tags.append(fam[1])
return list(set(list_tags))
########################################################################################################################
# Tags for clustering statements (by statement type)
########################################################################################################################
# Helper lists
types_int = [r"i1", "i8", "i16", "i32", "i64"]
types_flpt = [r"half", "float", "double", "fp128", "x86_fp80", "ppc_fp128"]
fast_math_flag = [
r"",
r"nnan ",
r"ninf ",
r"nsz ",
r"arcp ",
r"contract ",
r"afn ",
r"reassoc ",
r"fast ",
]
opt_load = [r"atomic ", "volatile "]
opt_addsubmul = [r"nsw ", "nuw ", "nuw nsw "]
opt_usdiv = [r"", "exact "]
opt_icmp = [
r"eq ",
r"ne ",
r"ugt ",
r"uge ",
r"ult ",
r"ule ",
r"sgt ",
r"sge ",
r"slt ",
r"sle ",
]
opt_fcmp = [
r"false ",
r"oeq ",
r"ogt ",
r"oge ",
r"olt ",
r"olt ",
r"ole ",
r"one ",
r"ord ",
r"ueq ",
r"ugt ",
r"uge ",
r"ult ",
r"ule ",
r"une ",
r"uno ",
r"true ",
]
opt_define = [
r"",
r"linkonce_odr ",
r"linkonce_odr ",
r"zeroext ",
r"dereferenceable\(\d+\) ",
r"hidden ",
r"internal ",
r"nonnull ",
r"weak_odr ",
r"fastcc ",
r"noalias ",
r"signext ",
r"spir_kernel ",
]
opt_invoke = [
r"",
r"dereferenceable\(\d+\) ",
r"noalias ",
r"fast ",
r"zeroext ",
r"signext ",
r"fastcc ",
]
opt_GEP = [r"", "inbounds "]
# Helper functions
def any_of(possibilities, to_add=""):
r"""
Construct a regex representing "any of" the given possibilities
:param possibilities: list of strings representing different word possibilities
:param to_add: string to add at the beginning of each possibility (optional)
:return: string corresponding to regex which represents any of the given possibilities
r"""
assert len(possibilities) > 0
s = r"("
if len(to_add) > 0:
s += possibilities[0] + to_add + r" "
else:
s += possibilities[0]
for i in range(len(possibilities) - 1):
if len(to_add) > 0:
s += r"|" + possibilities[i + 1] + to_add + r" "
else:
s += r"|" + possibilities[i + 1]
return s + r")"
# Main tags
llvm_IR_stmt_tags = [
# ['regex' r'tag' r'tag general'
[
r"<@ID> = (?!.*constant)(?!.*alias).*",
r"global definition",
r"global variable definition",
],
[r"<@ID> = .*constant .*", "global const. def.", "global variable definition"],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = add " + any_of(opt_addsubmul) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = sub " + any_of(opt_addsubmul) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = mul " + any_of(opt_addsubmul) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = udiv " + any_of(opt_usdiv) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = sdiv " + any_of(opt_usdiv) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<%ID> .*",
r"struct operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<%ID>\* .*",
r"struct* operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<%ID>\*\* .*",
r"struct** operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<%ID>\*\*\* .*",
r"struct*** operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i24 .*",
r"i24 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i24> .*",
r"<d x i24> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i40 .*",
r"i40 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i40> .*",
r"<d x i40> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i1\* .*",
r"i1* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i2\* .*",
r"i2* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i4\* .*",
r"i4* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i8\* .*",
r"i8* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i16\* .*",
r"i16* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i32\* .*",
r"i32* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i40\* .*",
r"i40* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i64\* .*",
r"i64* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i128\* .*",
r"i128* operation",
r"int* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?float\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?double\* .*",
r"double* operation",
r"floating point* operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i1\*\* .*",
r"i1** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i2\*\* .*",
r"i2** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i4\*\* .*",
r"i4** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i8\*\* .*",
r"i8** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i16\*\* .*",
r"i16** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i32\*\* .*",
r"i32** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i40\*\* .*",
r"i40** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i64\*\* .*",
r"i64** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?i128\*\* .*",
r"i128** operation",
r"int** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?x86_fp80\*\* .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?float\*\* .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?double\*\* .*",
r"double** operation",
r"floating point** operation",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<%ID>\* .*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r'?(%"|opaque).*',
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = icmp " + any_of(opt_icmp) + r"?void \(.*",
r"function op",
r"struct/class op",
],
[r"<%ID> = srem i1 .*", "i1 operation", "int operation"],
[r"<%ID> = srem <\d+ x i1> .*", "<d x i1> operation", "<d x int> operation"],
[r"<%ID> = srem i2 .*", "i2 operation", "int operation"],
[r"<%ID> = srem <\d+ x i2> .*", "<d x i2> operation", "<d x int> operation"],
[r"<%ID> = srem i4 .*", "i4 operation", "int operation"],
[r"<%ID> = srem <\d+ x i4> .*", "<d x i4> operation", "<d x int> operation"],
[r"<%ID> = srem i8 .*", "i8 operation", "int operation"],
[r"<%ID> = srem <\d+ x i8> .*", "<d x i8> operation", "<d x int> operation"],
[r"<%ID> = srem i16 .*", "i16 operation", "int operation"],
[
r"<%ID> = srem <\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[r"<%ID> = srem i32 .*", "i32 operation", "int operation"],
[
r"<%ID> = srem <\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[r"<%ID> = srem i64 .*", "i64 operation", "int operation"],
[
r"<%ID> = srem <\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[r"<%ID> = srem i128 .*", "i128 operation", "int operation"],
[
r"<%ID> = srem <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[r"<%ID> = urem i1 .*", "i1 operation", "int operation"],
[r"<%ID> = urem <\d+ x i1> .*", "<d x i1> operation", "<d x int> operation"],
[r"<%ID> = urem i2 .*", "i2 operation", "int operation"],
[r"<%ID> = urem <\d+ x i2> .*", "<d x i2> operation", "<d x int> operation"],
[r"<%ID> = urem i4 .*", "i4 operation", "int operation"],
[r"<%ID> = urem <\d+ x i4> .*", "<d x i4> operation", "<d x int> operation"],
[r"<%ID> = urem i8 .*", "i8 operation", "int operation"],
[r"<%ID> = urem <\d+ x i8> .*", "<d x i8> operation", "<d x int> operation"],
[r"<%ID> = urem i16 .*", "i16 operation", "int operation"],
[
r"<%ID> = urem <\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[r"<%ID> = urem i32 .*", "i32 operation", "int operation"],
[
r"<%ID> = urem <\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[r"<%ID> = urem i64 .*", "i32 operation", "int operation"],
[
r"<%ID> = urem <\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[r"<%ID> = urem i128 .*", "i128 operation", "int operation"],
[
r"<%ID> = urem <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = fadd " + any_of(fast_math_flag) + r"?x86_fp80.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fadd " + any_of(fast_math_flag) + r"?<\d+ x x86_fp80>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fadd " + any_of(fast_math_flag) + r"?float.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fadd " + any_of(fast_math_flag) + r"?<\d+ x float>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fadd " + any_of(fast_math_flag) + r"?double.*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = fadd " + any_of(fast_math_flag) + r"?<\d+ x double>.*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fsub " + any_of(fast_math_flag) + r"?x86_fp80.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fsub " + any_of(fast_math_flag) + r"?<\d+ x x86_fp80>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fsub " + any_of(fast_math_flag) + r"?float.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fsub " + any_of(fast_math_flag) + r"?<\d+ x float>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fsub " + any_of(fast_math_flag) + r"?double.*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = fsub " + any_of(fast_math_flag) + r"?<\d+ x double>.*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fmul " + any_of(fast_math_flag) + r"?x86_fp80.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fmul " + any_of(fast_math_flag) + r"?<\d+ x x86_fp80>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fmul " + any_of(fast_math_flag) + r"?float.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fmul " + any_of(fast_math_flag) + r"?<\d+ x float>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fmul " + any_of(fast_math_flag) + r"?double.*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = fmul " + any_of(fast_math_flag) + r"?<\d+ x double>.*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fdiv " + any_of(fast_math_flag) + r"?x86_fp80.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fdiv " + any_of(fast_math_flag) + r"?<\d+ x x86_fp80>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fdiv " + any_of(fast_math_flag) + r"?float.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fdiv " + any_of(fast_math_flag) + r"?<\d+ x float>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fdiv " + any_of(fast_math_flag) + r"?double.*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = fdiv " + any_of(fast_math_flag) + r"?<\d+ x double>.*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = frem " + any_of(fast_math_flag) + r"?x86_fp80.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = frem " + any_of(fast_math_flag) + r"?<\d+ x x86_fp80>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = frem " + any_of(fast_math_flag) + r"?float.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = frem " + any_of(fast_math_flag) + r"?<\d+ x float>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = frem " + any_of(fast_math_flag) + r"?double.*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = frem " + any_of(fast_math_flag) + r"?<\d+ x double>.*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fcmp (fast |)?" + any_of(opt_fcmp) + r"?x86_fp80.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fcmp (fast |)?" + any_of(opt_fcmp) + r"?<\d+ x x86_fp80>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fcmp (fast |)?" + any_of(opt_fcmp) + r"?float.*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = fcmp (fast |)?" + any_of(opt_fcmp) + r"?<\d+ x float>.*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = fcmp (fast |)?" + any_of(opt_fcmp) + r"?double.*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = fcmp (fast |)?" + any_of(opt_fcmp) + r"?<\d+ x double>.*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[r"<%ID> = atomicrmw add i1\* .*", "i1* operation", "int* operation"],
[r"<%ID> = atomicrmw add i2\* .*", "i2* operation", "int* operation"],
[r"<%ID> = atomicrmw add i4\* .*", "i4* operation", "int* operation"],
[r"<%ID> = atomicrmw add i8\* .*", "i8* operation", "int* operation"],
[r"<%ID> = atomicrmw add i16\* .*", "i16* operation", "int* operation"],
[r"<%ID> = atomicrmw add i32\* .*", "i32* operation", "int* operation"],
[r"<%ID> = atomicrmw add i64\* .*", "i64* operation", "int* operation"],
[r"<%ID> = atomicrmw add i128\* .*", "i128* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i1\* .*", "i1* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i2\* .*", "i2* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i4\* .*", "i4* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i8\* .*", "i8* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i16\* .*", "i16* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i32\* .*", "i32* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i64\* .*", "i64* operation", "int* operation"],
[r"<%ID> = atomicrmw sub i128\* .*", "i128* operation", "int* operation"],
[r"<%ID> = atomicrmw or i1\* .*", "i1* operation", "int* operation"],
[r"<%ID> = atomicrmw or i2\* .*", "i2* operation", "int* operation"],
[r"<%ID> = atomicrmw or i4\* .*", "i4* operation", "int* operation"],
[r"<%ID> = atomicrmw or i8\* .*", "i8* operation", "int* operation"],
[r"<%ID> = atomicrmw or i16\* .*", "i16* operation", "int* operation"],
[r"<%ID> = atomicrmw or i32\* .*", "i32* operation", "int* operation"],
[r"<%ID> = atomicrmw or i64\* .*", "i64* operation", "int* operation"],
[r"<%ID> = atomicrmw or i128\* .*", "i128* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i1\* .*", "i1* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i2\* .*", "i2* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i4\* .*", "i4* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i8\* .*", "i8* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i16\* .*", "i16* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i32\* .*", "i32* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i64\* .*", "i64* operation", "int* operation"],
[r"<%ID> = atomicrmw xchg i128\* .*", "i128* operation", "int* operation"],
[r"<%ID> = alloca i1($|,).*", "i1 operation", "int operation"],
[r"<%ID> = alloca i2($|,).*", "i2 operation", "int operation"],
[r"<%ID> = alloca i4($|,).*", "i4 operation", "int operation"],
[r"<%ID> = alloca i8($|,).*", "i8 operation", "int operation"],
[r"<%ID> = alloca i16($|,).*", "i16 operation", "int operation"],
[r"<%ID> = alloca i32($|,).*", "i32 operation", "int operation"],
[r"<%ID> = alloca i64($|,).*", "i64 operation", "int operation"],
[r"<%ID> = alloca i128($|,).*", "i128 operation", "int operation"],
[r"<%ID> = alloca i1\*($|,).*", "i1* operation", "int* operation"],
[r"<%ID> = alloca i2\*($|,).*", "i2* operation", "int* operation"],
[r"<%ID> = alloca i4\*($|,).*", "i4* operation", "int* operation"],
[r"<%ID> = alloca i8\*($|,).*", "i8* operation", "int* operation"],
[r"<%ID> = alloca i16\*($|,).*", "i16* operation", "int* operation"],
[r"<%ID> = alloca i32\*($|,).*", "i32* operation", "int* operation"],
[r"<%ID> = alloca i64\*($|,).*", "i64* operation", "int* operation"],
[r"<%ID> = alloca i128\*($|,).*", "i128* operation", "int* operation"],
[
r"<%ID> = alloca x86_fp80($|,).*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = alloca float($|,).*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = alloca double($|,).*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = alloca x86_fp80\*($|,).*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = alloca float\*($|,).*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = alloca double\*($|,).*",
r"double* operation",
r"floating point* operation",
],
['<%ID> = alloca %".*', "struct/class op", "struct/class op"],
[r"<%ID> = alloca <%.*", "struct/class op", "struct/class op"],
[r"<%ID> = alloca <?{.*", "struct/class op", "struct/class op"],
[r"<%ID> = alloca opaque.*", "struct/class op", "struct/class op"],
[
r"<%ID> = alloca <\d+ x i1>, .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i2>, .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i4>, .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i8>, .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i16>, .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i32>, .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i64>, .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x i128>, .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = alloca <\d+ x x86_fp80>, .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = alloca <\d+ x float>, .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = alloca <\d+ x double>, .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = alloca <\d+ x \{ .* \}>, .*",
r"<d x structure> operation",
r"<d x structure> operation",
],
[
r"<%ID> = alloca <\d+ x i1>\*, .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i2>\*, .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i4>\*, .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i8>\*, .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i16>\*, .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i32>\*, .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i64>\*, .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x i128>\*, .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = alloca <\d+ x x86_fp80>\*, .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = alloca <\d+ x float>\*, .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = alloca <\d+ x double>\*, .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = alloca <\d+ x \{ .* \}>\*, .*",
r"<d x structure>* operation",
r"<d x structure>* operation",
],
[
r"<%ID> = alloca \[\d+ x i1\], .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i2\], .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i4\], .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i8\], .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i16\], .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i32\], .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i64\], .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x i128\], .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"<%ID> = alloca \[\d+ x x86_fp80\], .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = alloca \[\d+ x float\], .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = alloca \[\d+ x double\], .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = alloca \[\d+ x \{ .* \}\], .*",
r"[d x structure] operation",
r"[d x structure] operation",
],
[
r"<%ID> = alloca { { float, float } }, .*",
r"{ float, float } operation",
r"complex operation",
],
[
r"<%ID> = alloca { { double, double } }, .*",
r"{ double, double } operation",
r"complex operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i1, .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i2, .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i4, .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i8, .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i16, .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i24, .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i32, .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i40, .*",
r"i40 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i64, .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i128, .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i256, .*",
r"i256 operation",
r"int operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i1\*, .*",
r"i1* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i2\*, .*",
r"i2* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i4\*, .*",
r"i4* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i8\*, .*",
r"i8* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i16\*, .*",
r"i16* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i24\*, .*",
r"i16* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i32\*, .*",
r"i32* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i40\*, .*",
r"i40* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i64\*, .*",
r"i64* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i128\*, .*",
r"i128* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i256\*, .*",
r"i256* operation",
r"int* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i1\*\*, .*",
r"i1** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i2\*\*, .*",
r"i2** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i4\*\*, .*",
r"i4** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i8\*\*, .*",
r"i8** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i16\*\*, .*",
r"i16** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i24\*\*, .*",
r"i16** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i32\*\*, .*",
r"i32** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i40\*\*, .*",
r"i40** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i64\*\*, .*",
r"i64** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i128\*\*, .*",
r"i128** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i256\*\*, .*",
r"i256** operation",
r"int** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i1\*\*\*, .*",
r"i1*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i2\*\*\*, .*",
r"i2*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i4\*\*\*, .*",
r"i4*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i8\*\*\*, .*",
r"i8*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i16\*\*\*, .*",
r"i16*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i24\*\*\*, .*",
r"i16*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i32\*\*\*, .*",
r"i32*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i40\*\*\*, .*",
r"i40*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i64\*\*\*, .*",
r"i64*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i128\*\*\*, .*",
r"i128*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?i256\*\*\*, .*",
r"i256*** operation",
r"int*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?x86_fp80, .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?float, .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?double, .*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?x86_fp80\*, .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?float\*, .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?double\*, .*",
r"double* operation",
r"floating point* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?x86_fp80\*\*, .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?float\*\*, .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?double\*\*, .*",
r"double** operation",
r"floating point** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?x86_fp80\*\*\*, .*",
r"float*** operation",
r"floating point*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?float\*\*\*, .*",
r"float*** operation",
r"floating point*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?double\*\*\*, .*",
r"double*** operation",
r"floating point*** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r'?%".*',
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<%.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i1>, .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i2>, .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i4>, .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i8>, .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i16>, .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i24>, .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i32>, .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i40>, .*",
r"<d x i40> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i64>, .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i128>, .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x x86_fp80>, .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x float>, .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x double>, .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x \{ .* \}>, .*",
r"<d x structure> operation",
r"<d x structure> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i1\*>, .*",
r"<d x i1*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i2\*>, .*",
r"<d x i2*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i4\*>, .*",
r"<d x i4*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i8\*>, .*",
r"<d x i8*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i16\*>, .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i24\*>, .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i32\*>, .*",
r"<d x i32*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i40\*>, .*",
r"<d x i40*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i64\*>, .*",
r"<d x i64*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i128\*>, .*",
r"<d x i128*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x x86_fp80\*>, .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x float\*>, .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x double\*>, .*",
r"<d x double*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i1>\*, .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i2>\*, .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i4>\*, .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i8>\*, .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i16>\*, .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i24>\*, .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i32>\*, .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i40>\*, .*",
r"<d x i40>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i64>\*, .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x i128>\*, .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x x86_fp80>\*, .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x float>\*, .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x double>\*, .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x \{ .* \}>\*, .*",
r"<d x structure>* operation",
r"<d x structure>* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x x86_fp80>\*\*, .*",
r"<d x float>** operation",
r"<d x floating point>** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x float>\*\*, .*",
r"<d x float>** operation",
r"<d x floating point>** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x double>\*\*, .*",
r"<d x double>** operation",
r"<d x floating point>** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?<\d+ x \{ .* \}>\*\*, .*",
r"<d x structure>** operation",
r"<d x structure>** operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i1\], .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i2\], .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i4\], .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i8\], .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i16\], .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i24\], .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i32\], .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i40\], .*",
r"[d x i40] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i64\], .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i128\], .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x x86_fp80\], .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x float\], .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x double\], .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x \{ .* \}\], .*",
r"[d x structure] operation",
r"[d x structure] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i1\]\*, .*",
r"[d x i1]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i2\]\*, .*",
r"[d x i2]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i4\]\*, .*",
r"[d x i4]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i8\]\*, .*",
r"[d x i8]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i16\]\*, .*",
r"[d x i16]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i32\]\*, .*",
r"[d x i32]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i40\]\*, .*",
r"[d x i40]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i64\]\*, .*",
r"[d x i64]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x i128\]\*, .*",
r"[d x i128]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x x86_fp80\]\*, .*",
r"[d x float]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x float\]\*, .*",
r"[d x float]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x double\]\*, .*",
r"[d x double]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?\[\d+ x \{ .* \}\]\*, .*",
r"[d x structure]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = load " + any_of(opt_load) + r"?.*\(.*\)\*+, .*",
r"function operation",
r"function operation",
],
[r"store " + any_of(opt_load) + r"?i1 .*", "i1 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i2 .*", "i2 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i4 .*", "i4 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i8 .*", "i8 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i16 .*", "i16 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i24 .*", "i16 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i32 .*", "i32 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i40 .*", "i32 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i64 .*", "i64 operation", "int operation"],
[r"store " + any_of(opt_load) + r"?i128 .*", "i128 operation", "int operation"],
[
r"store " + any_of(opt_load) + r"?i1\* .*",
r"i1* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i2\* .*",
r"i2* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i4\* .*",
r"i4* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i8\* .*",
r"i8* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i16\* .*",
r"i16* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i32\* .*",
r"i32* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i64\* .*",
r"i64* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i128\* .*",
r"i128* operation",
r"int* operation",
],
[
r"store " + any_of(opt_load) + r"?i1\*\* .*",
r"i1** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i2\*\* .*",
r"i2** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i4\*\* .*",
r"i4** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i8\*\* .*",
r"i8** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i16\*\* .*",
r"i16** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i32\*\* .*",
r"i32** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i64\*\* .*",
r"i64** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?i128\*\* .*",
r"i128** operation",
r"int** operation",
],
[
r"store " + any_of(opt_load) + r"?x86_fp80 .*",
r"float operation",
r"floating point operation",
],
[
r"store " + any_of(opt_load) + r"?float .*",
r"float operation",
r"floating point operation",
],
[
r"store " + any_of(opt_load) + r"?double .*",
r"double operation",
r"floating point operation",
],
[
r"store " + any_of(opt_load) + r"?x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"store " + any_of(opt_load) + r"?float\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"store " + any_of(opt_load) + r"?double\* .*",
r"double* operation",
r"floating point* operation",
],
[
r"store " + any_of(opt_load) + r"?x86_fp80\*\* .*",
r"float** operation",
r"floating point** operation",
],
[
r"store " + any_of(opt_load) + r"?float\*\* .*",
r"float** operation",
r"floating point** operation",
],
[
r"store " + any_of(opt_load) + r"?double\*\* .*",
r"double** operation",
r"floating point** operation",
],
[r"store " + any_of(opt_load) + r"?void \(.*", "function op", "function op"],
[r"store " + any_of(opt_load) + r'?%".*', "struct/class op", "struct/class op"],
[r"store " + any_of(opt_load) + r"?<%.*", "struct/class op", "struct/class op"],
[
r"store " + any_of(opt_load) + r"?<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"store " + any_of(opt_load) + r"?opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x \{ .* \}> .*",
r"<d x \{ .* \}> operation",
r"<d x \{ .* \}> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i1\*> .*",
r"<d x i1*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i2\*> .*",
r"<d x i2*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i4\*> .*",
r"<d x i4*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i8\*> .*",
r"<d x i8*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i16\*> .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i32\*> .*",
r"<d x i32*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i64\*> .*",
r"<d x i64*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i128\*> .*",
r"<d x i128*> operation",
r"<d x int*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x x86_fp80\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x float\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x double\*> .*",
r"<d x double*> operation",
r"<d x floating point*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x \{ .* \}\*> .*",
r"<d x \{ .* \}*> operation",
r"<d x \{ .* \}*> operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i1>\* .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i2>\* .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i4>\* .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i8>\* .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i16>\* .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i32>\* .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i64>\* .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x i128>\* .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x x86_fp80>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x float>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x double>\* .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x \{ .* \}\*?>\* .*",
r"<d x struct>* operation",
r"<d x \{ .* \}>* operation",
],
[
r"store " + any_of(opt_load) + r"?<\d+ x void \(.*",
r"<d x function>* operation",
r"<d x function operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i1\] .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i2\] .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i4\] .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i8\] .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i16\] .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i32\] .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i64\] .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x i128\] .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x x86_fp80\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x float\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x double\] .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[
r"store " + any_of(opt_load) + r"?\[\d+ x \{ .* \}\] .*",
r"[d x structure] operation",
r"[d x structure] operation",
],
[r"declare (noalias |nonnull )*void .*", "void operation", "void operation"],
[r"declare (noalias |nonnull )*i1 .*", "i1 operation", "int operation"],
[r"declare (noalias |nonnull )*i2 .*", "i2 operation", "int operation"],
[r"declare (noalias |nonnull )*i4 .*", "i4 operation", "int operation"],
[r"declare (noalias |nonnull )*i8 .*", "i8 operation", "int operation"],
[r"declare (noalias |nonnull )*i16 .*", "i16 operation", "int operation"],
[r"declare (noalias |nonnull )*i32 .*", "i32 operation", "int operation"],
[r"declare (noalias |nonnull )*i64 .*", "i64 operation", "int operation"],
[r"declare (noalias |nonnull )*i8\* .*", "i8* operation", "int* operation"],
[r"declare (noalias |nonnull )*i16\* .*", "i16* operation", "int* operation"],
[r"declare (noalias |nonnull )*i32\* .*", "i32* operation", "int* operation"],
[r"declare (noalias |nonnull )*i64\* .*", "i64* operation", "int* operation"],
[
r"declare (noalias |nonnull )*x86_fp80 .*",
r"float operation",
r"floating point operation",
],
[
r"declare (noalias |nonnull )*float .*",
r"float operation",
r"floating point operation",
],
[
r"declare (noalias |nonnull )*double .*",
r"double operation",
r"floating point operation",
],
[
r"declare (noalias |nonnull )*x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"declare (noalias |nonnull )*float\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"declare (noalias |nonnull )*double\* .*",
r"double* operation",
r"floating point* operation",
],
['declare (noalias |nonnull )*%".*', "struct/class op", "struct/class op"],
[r"declare (noalias |nonnull )*<%.*", "struct/class op", "struct/class op"],
[r"declare (noalias |nonnull )*<?{.*", "struct/class op", "struct/class op"],
[
r"declare (noalias |nonnull )*opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"declare (noalias |nonnull )*<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i1>\* .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i2>\* .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i4>\* .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i8>\* .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i16>\* .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i32>\* .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i64>\* .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x i128>\* .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x x86_fp80>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x float>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"declare (noalias |nonnull )*<\d+ x double>\* .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i1\] .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i2\] .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i4\] .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i8\] .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i16\] .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i32\] .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i64\] .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x i128\] .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x x86_fp80\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x float\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"declare (noalias |nonnull )*\[\d+ x double\] .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[
r"define " + any_of(opt_define) + r"+void .*",
r"void operation",
r"void operation",
],
[r"define " + any_of(opt_define) + r"+i1 .*", "i1 operation", "int operation"],
[r"define " + any_of(opt_define) + r"+i2 .*", "i2 operation", "int operation"],
[r"define " + any_of(opt_define) + r"+i4 .*", "i4 operation", "int operation"],
[r"define " + any_of(opt_define) + r"+i8 .*", "i8 operation", "int operation"],
[
r"define " + any_of(opt_define) + r"+i16 .*",
r"i16 operation",
r"int operation",
],
[
r"define " + any_of(opt_define) + r"+i32 .*",
r"i32 operation",
r"int operation",
],
[
r"define " + any_of(opt_define) + r"+i64 .*",
r"i64 operation",
r"int operation",
],
[
r"define " + any_of(opt_define) + r"+i128 .*",
r"i128 operation",
r"int operation",
],
[
r"define " + any_of(opt_define) + r"+i1\* .*",
r"i1* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i2\* .*",
r"i2* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i4\* .*",
r"i4* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i8\* .*",
r"i8* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i16\* .*",
r"i16* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i32\* .*",
r"i32* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i64\* .*",
r"i64* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+i128\* .*",
r"i128* operation",
r"int* operation",
],
[
r"define " + any_of(opt_define) + r"+x86_fp80 .*",
r"float operation",
r"floating point operation",
],
[
r"define " + any_of(opt_define) + r"+float .*",
r"float operation",
r"floating point operation",
],
[
r"define " + any_of(opt_define) + r"+double .*",
r"double operation",
r"floating point operation",
],
[
r"define " + any_of(opt_define) + r"+x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"define " + any_of(opt_define) + r"+float\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"define " + any_of(opt_define) + r"+double\* .*",
r"double* operation",
r"floating point* operation",
],
[
r"define " + any_of(opt_define) + r'+%".*',
r"struct/class op",
r"struct/class op",
],
[
r"define " + any_of(opt_define) + r"+<%.*",
r"struct/class op",
r"struct/class op",
],
[
r"define " + any_of(opt_define) + r"+<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"define " + any_of(opt_define) + r"+opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i1>\* .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i2>\* .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i4>\* .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i8>\* .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i16>\* .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i32>\* .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i64>\* .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x i128>\* .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x x86_fp80>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x float>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"define " + any_of(opt_define) + r"+<\d+ x double>\* .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i1\] .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i2\] .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i4\] .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i8\] .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i16\] .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i32\] .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i64\] .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x i128\] .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x x86_fp80\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x float\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"define " + any_of(opt_define) + r"+\[\d+ x double\] .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i1\* .*",
r"i1* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i2\* .*",
r"i2* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i4\* .*",
r"i4* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i8\* .*",
r"i8* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i16\* .*",
r"i16* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i32\* .*",
r"i32* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i64\* .*",
r"i64* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i128\* .*",
r"i128* operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i1\*\* .*",
r"i1** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i2\*\* .*",
r"i2** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i4\*\* .*",
r"i4** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*i8\*\* .*",
r"i8** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*i16\*\* .*",
r"i16** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*i32\*\* .*",
r"i32** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*i64\*\* .*",
r"i64** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*i128\*\* .*",
r"i128** operation",
r"int* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*x86_fp80 .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*float .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*double .*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*float\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*double\* .*",
r"double* operation",
r"floating point* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*x86_fp80\*\* .*",
r"float** operation",
r"floating point* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*float\*\* .*",
r"float** operation",
r"floating point* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*double\*\* .*",
r"double** operation",
r"floating point* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r'*%".*',
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*<%.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = (tail |musttail |notail )?call " + any_of(opt_invoke) + r"*opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i1>\* .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i2>\* .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i4>\* .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i8>\* .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i16>\* .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i32>\* .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i64>\* .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x i128>\* .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x x86_fp80>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x float>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*<\d+ x double>\* .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i1\] .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i2\] .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i4\] .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i8\] .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i16\] .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i32\] .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i64\] .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x i128\] .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x x86_fp80\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x float\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = (tail |musttail |notail )?call "
+ any_of(opt_invoke)
+ r"*\[\d+ x double\] .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[r"ret i1 .*", "i1 operation", "int operation"],
[r"ret i2 .*", "i2 operation", "int operation"],
[r"ret i4 .*", "i4 operation", "int operation"],
[r"ret i8 .*", "i8 operation", "int operation"],
[r"ret i16 .*", "i16 operation", "int operation"],
[r"ret i32 .*", "i32 operation", "int operation"],
[r"ret i64 .*", "i64 operation", "int operation"],
[r"ret i128 .*", "i128 operation", "int operation"],
[r"ret i1\* .*", "i1* operation", "int* operation"],
[r"ret i2\* .*", "i2* operation", "int* operation"],
[r"ret i4\* .*", "i4* operation", "int* operation"],
[r"ret i8\* .*", "i8* operation", "int* operation"],
[r"ret i16\* .*", "i16* operation", "int* operation"],
[r"ret i32\* .*", "i32* operation", "int* operation"],
[r"ret i64\* .*", "i64* operation", "int* operation"],
[r"ret i128\* .*", "i128* operation", "int* operation"],
[r"ret x86_fp80 .*", "x86_fp80 operation", "floating point operation"],
[r"ret float .*", "float operation", "floating point operation"],
[r"ret double .*", "double operation", "floating point operation"],
[r"ret x86_fp80\* .*", "x86_fp80* operation", "floating point* operation"],
[r"ret float\* .*", "float* operation", "floating point* operation"],
[r"ret double\* .*", "double* operation", "floating point* operation"],
['ret %".*', "struct/class op", "struct/class op"],
[r"ret <%.*", "struct/class op", "struct/class op"],
[r"ret <?{.*", "struct/class op", "struct/class op"],
[r"ret opaque.*", "struct/class op", "struct/class op"],
[r"ret <\d+ x i1> .*", "<d x i1> operation", "<d x int> operation"],
[r"ret <\d+ x i2> .*", "<d x i2> operation", "<d x int> operation"],
[r"ret <\d+ x i4> .*", "<d x i4> operation", "<d x int> operation"],
[r"ret <\d+ x i8> .*", "<d x i8> operation", "<d x int> operation"],
[r"ret <\d+ x i16> .*", "<d x i16> operation", "<d x int> operation"],
[r"ret <\d+ x i32> .*", "<d x i32> operation", "<d x int> operation"],
[r"ret <\d+ x i64> .*", "<d x i64> operation", "<d x int> operation"],
[r"ret <\d+ x i128> .*", "<d x i128> operation", "<d x int> operation"],
[
r"ret <\d+ x x86_fp80> .*",
r"<d x x86_fp80> operation",
r"<d x floating point> operation",
],
[
r"ret <\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"ret <\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[r"ret <\d+ x i1>\* .*", "<d x i1>* operation", "<d x int>* operation"],
[r"ret <\d+ x i2>\* .*", "<d x i2>* operation", "<d x int>* operation"],
[r"ret <\d+ x i4>\* .*", "<d x i4>* operation", "<d x int>* operation"],
[r"ret <\d+ x i8>\* .*", "<d x i8>* operation", "<d x int>* operation"],
[r"ret <\d+ x i16>\* .*", "<d x i16>* operation", "<d x int>* operation"],
[r"ret <\d+ x i32>\* .*", "<d x i32>* operation", "<d x int>* operation"],
[r"ret <\d+ x i64>\* .*", "<d x i64>* operation", "<d x int>* operation"],
[r"ret <\d+ x i128>\* .*", "<d x i128>* operation", "<d x int>* operation"],
[
r"ret <\d+ x x86_fp80>\* .*",
r"<d x x86_fp80>* operation",
r"<d x floating point>* operation",
],
[
r"ret <\d+ x float>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"ret <\d+ x double>\* .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[r"ret \[\d+ x i1\] .*", "[d x i1] operation", "[d x int] operation"],
[r"ret \[\d+ x i2\] .*", "[d x i2] operation", "[d x int] operation"],
[r"ret \[\d+ x i4\] .*", "[d x i4] operation", "[d x int] operation"],
[r"ret \[\d+ x i8\] .*", "[d x i8] operation", "[d x int] operation"],
[r"ret \[\d+ x i16\] .*", "[d x i16] operation", "[d x int] operation"],
[r"ret \[\d+ x i32\] .*", "[d x i32] operation", "[d x int] operation"],
[r"ret \[\d+ x i64\] .*", "[d x i64] operation", "[d x int] operation"],
[r"ret \[\d+ x i128\] .*", "[d x i128] operation", "[d x int] operation"],
[
r"ret \[\d+ x x86_fp80\] .*",
r"[d x x86_fp80] operation",
r"[d x floating point] operation",
],
[
r"ret \[\d+ x float\] .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"ret \[\d+ x double\] .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[r"<%ID> = and i1 .*", "i1 operation", "int operation"],
[r"<%ID> = and <\d+ x i1> .*", "<d x i1> operation", "<d x int> operation"],
[r"<%ID> = and i2 .*", "i2 operation", "int operation"],
[r"<%ID> = and <\d+ x i2> .*", "<d x i2> operation", "<d x int> operation"],
[r"<%ID> = and i4 .*", "i4 operation", "int operation"],
[r"<%ID> = and <\d+ x i4> .*", "<d x i4> operation", "<d x int> operation"],
[r"<%ID> = and i8 .*", "i8 operation", "int operation"],
[r"<%ID> = and <\d+ x i8> .*", "<d x i8> operation", "<d x int> operation"],
[r"<%ID> = and i16 .*", "i16 operation", "int operation"],
[r"<%ID> = and <\d+ x i16> .*", "<d x i16> operation", "<d x int> operation"],
[r"<%ID> = and i24 .*", "i24 operation", "int operation"],
[r"<%ID> = and <\d+ x i24> .*", "<d x i24> operation", "<d x int> operation"],
[r"<%ID> = and i32 .*", "i32 operation", "int operation"],
[r"<%ID> = and <\d+ x i32> .*", "<d x i32> operation", "<d x int> operation"],
[r"<%ID> = and i40 .*", "i40 operation", "int operation"],
[r"<%ID> = and <\d+ x i40> .*", "<d x i40> operation", "<d x int> operation"],
[r"<%ID> = and i64 .*", "i64 operation", "int operation"],
[r"<%ID> = and <\d+ x i64> .*", "<d x i64> operation", "<d x int> operation"],
[r"<%ID> = and i128 .*", "i128 operation", "int operation"],
[
r"<%ID> = and <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[r"<%ID> = or i1 .*", "i1 operation", "int operation"],
[r"<%ID> = or <\d+ x i1> .*", "<d x i1> operation", "<d x int> operation"],
[r"<%ID> = or i2 .*", "i2 operation", "int operation"],
[r"<%ID> = or <\d+ x i2> .*", "<d x i2> operation", "<d x int> operation"],
[r"<%ID> = or i4 .*", "i4 operation", "int operation"],
[r"<%ID> = or <\d+ x i4> .*", "<d x i4> operation", "<d x int> operation"],
[r"<%ID> = or i8 .*", "i8 operation", "int operation"],
[r"<%ID> = or <\d+ x i8> .*", "<d x i8> operation", "<d x int> operation"],
[r"<%ID> = or i16 .*", "i16 operation", "int operation"],
[r"<%ID> = or <\d+ x i16> .*", "<d x i16> operation", "<d x int> operation"],
[r"<%ID> = or i24 .*", "i24 operation", "int operation"],
[r"<%ID> = or <\d+ x i24> .*", "<d x i24> operation", "<d x int> operation"],
[r"<%ID> = or i32 .*", "i32 operation", "int operation"],
[r"<%ID> = or <\d+ x i32> .*", "<d x i32> operation", "<d x int> operation"],
[r"<%ID> = or i40 .*", "i40 operation", "int operation"],
[r"<%ID> = or <\d+ x i40> .*", "<d x i40> operation", "<d x int> operation"],
[r"<%ID> = or i64 .*", "i64 operation", "int operation"],
[r"<%ID> = or <\d+ x i64> .*", "<d x i64> operation", "<d x int> operation"],
[r"<%ID> = or i128 .*", "i128 operation", "int operation"],
[r"<%ID> = or <\d+ x i128> .*", "<d x i128> operation", "<d x int> operation"],
[r"<%ID> = xor i1 .*", "i1 operation", "int operation"],
[r"<%ID> = xor <\d+ x i1>.*", "<d x i1> operation", "<d x int> operation"],
[r"<%ID> = xor i4 .*", "i4 operation", "int operation"],
[r"<%ID> = xor <\d+ x i2>.*", "<d x i2> operation", "<d x int> operation"],
[r"<%ID> = xor i2 .*", "i2 operation", "int operation"],
[r"<%ID> = xor <\d+ x i4>.*", "<d x i4> operation", "<d x int> operation"],
[r"<%ID> = xor i8 .*", "i8 operation", "int operation"],
[r"<%ID> = xor <\d+ x i8>.*", "<d x i8> operation", "<d x int> operation"],
[r"<%ID> = xor i16 .*", "i16 operation", "int operation"],
[r"<%ID> = xor <\d+ x i16>.*", "<d x i16> operation", "<d x int> operation"],
[r"<%ID> = xor i24 .*", "i16 operation", "int operation"],
[r"<%ID> = xor <\d+ x i24>.*", "<d x i16> operation", "<d x int> operation"],
[r"<%ID> = xor i32 .*", "i32 operation", "int operation"],
[r"<%ID> = xor <\d+ x i32>.*", "<d x i32> operation", "<d x int> operation"],
[r"<%ID> = xor i40 .*", "i40 operation", "int operation"],
[r"<%ID> = xor <\d+ x i40>.*", "<d x i40> operation", "<d x int> operation"],
[r"<%ID> = xor i64 .*", "i64 operation", "int operation"],
[r"<%ID> = xor <\d+ x i64>.*", "<d x i64> operation", "<d x int> operation"],
[r"<%ID> = xor i128 .*", "i128 operation", "int operation"],
[r"<%ID> = xor <\d+ x i128>.*", "<d x i128> operation", "<d x int> operation"],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i4 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i40 .*",
r"i40 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i40> .*",
r"<d x i40> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?i256 .*",
r"i256 operation",
r"int operation",
],
[
r"<%ID> = shl " + any_of(opt_addsubmul) + r"?<\d+ x i256> .*",
r"<d x i256> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i40 .*",
r"i40 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i40> .*",
r"<d x i40> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?i256 .*",
r"i256 operation",
r"int operation",
],
[
r"<%ID> = ashr " + any_of(opt_usdiv) + r"?<\d+ x i256> .*",
r"<d x i256> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i24 .*",
r"i24 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i24> .*",
r"<d x i24> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i40 .*",
r"i40 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i40> .*",
r"<d x i40> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?i256 .*",
r"i256 operation",
r"int operation",
],
[
r"<%ID> = lshr " + any_of(opt_usdiv) + r"?<\d+ x i256> .*",
r"<d x i256> operation",
r"<d x int> operation",
],
[r"<%ID> = phi i1 .*", "i1 operation", "int operation"],
[r"<%ID> = phi <\d+ x i1> .*", "<d x i1> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i1\*> .*",
r"<d x i1*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i1>\* .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[r"<%ID> = phi \[\d+ x i1\] .*", "[d x i1] operation", "[d x int] operation"],
[
r"<%ID> = phi \[\d+ x i1\]\* .*",
r"[d x i1]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i1\]\*\* .*",
r"[d x i1]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i1\]\*\*\* .*",
r"[d x i1]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i2 .*", "i2 operation", "int operation"],
[r"<%ID> = phi <\d+ x i2> .*", "<d x i2> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i2\*> .*",
r"<d x i2*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i2>\* .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[r"<%ID> = phi \[\d+ x i2\] .*", "[d x i2] operation", "[d x int] operation"],
[
r"<%ID> = phi \[\d+ x i2\]\* .*",
r"[d x i2]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i2\]\*\* .*",
r"[d x i2]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i2\]\*\*\* .*",
r"[d x i2]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i4 .*", "i4 operation", "int operation"],
[r"<%ID> = phi <\d+ x i4> .*", "<d x i4> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i4\*> .*",
r"<d x i4*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i4>\* .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[r"<%ID> = phi \[\d+ x i4\] .*", "[d x i4] operation", "[d x int] operation"],
[
r"<%ID> = phi \[\d+ x i4\]\* .*",
r"[d x i4]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i4\]\*\* .*",
r"[d x i4]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i4\]\*\*\* .*",
r"[d x i4]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i8 .*", "i8 operation", "int operation"],
[r"<%ID> = phi <\d+ x i8> .*", "<d x i8> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i8\*> .*",
r"<d x i8*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i8>\* .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[r"<%ID> = phi \[\d+ x i8\] .*", "[d x i4] operation", "[d x int] operation"],
[
r"<%ID> = phi \[\d+ x i8\]\* .*",
r"[d x i4]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i8\]\*\* .*",
r"[d x i4]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i8\]\*\*\* .*",
r"[d x i4]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i16 .*", "i16 operation", "int operation"],
[r"<%ID> = phi <\d+ x i16> .*", "<d x i16> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i16\*> .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i16>\* .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = phi \[\d+ x i16\] .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"<%ID> = phi \[\d+ x i16\]\* .*",
r"[d x i16]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i16\]\*\* .*",
r"[d x i16]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i16\]\*\*\* .*",
r"[d x i16]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i32 .*", "i32 operation", "int operation"],
[r"<%ID> = phi <\d+ x i32> .*", "<d x i32> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i32\*> .*",
r"<d x i32*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i32>\* .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = phi \[\d+ x i32\] .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"<%ID> = phi \[\d+ x i32\]\* .*",
r"[d x i32]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i32\]\*\* .*",
r"[d x i32]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i32\]\*\*\* .*",
r"[d x i32]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i40 .*", "i32 operation", "int operation"],
[r"<%ID> = phi <\d+ x i40> .*", "<d x i40> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i40\*> .*",
r"<d x i40*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i40>\* .*",
r"<d x i40>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = phi \[\d+ x i40\] .*",
r"[d x i40] operation",
r"[d x int] operation",
],
[
r"<%ID> = phi \[\d+ x i40\]\* .*",
r"[d x i40]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i40\]\*\* .*",
r"[d x i40]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i40\]\*\*\* .*",
r"[d x i40]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i64 .*", "i64 operation", "int operation"],
[r"<%ID> = phi <\d+ x i64> .*", "<d x i64> operation", "<d x int> operation"],
[
r"<%ID> = phi <\d+ x i64\*> .*",
r"<d x i64*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i64>\* .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = phi \[\d+ x i64\] .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"<%ID> = phi \[\d+ x i64\]\* .*",
r"[d x i64]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i64\]\*\* .*",
r"[d x i64]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i64\]\*\*\* .*",
r"[d x i64]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i128 .*", "i128 operation", "int operation"],
[
r"<%ID> = phi <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = phi <\d+ x i128\*> .*",
r"<d x i128*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = phi <\d+ x i128>\* .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = phi \[\d+ x i128\] .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"<%ID> = phi \[\d+ x i128\]\* .*",
r"[d x i128]* operation",
r"[d x int]* operation",
],
[
r"<%ID> = phi \[\d+ x i126\]\*\* .*",
r"[d x i128]** operation",
r"[d x int]** operation",
],
[
r"<%ID> = phi \[\d+ x i128\]\*\*\* .*",
r"[d x i128]*** operation",
r"[d x int]*** operation",
],
[r"<%ID> = phi i1\* .*", "i1* operation", "int* operation"],
[r"<%ID> = phi i2\* .*", "i2* operation", "int* operation"],
[r"<%ID> = phi i4\* .*", "i4* operation", "int* operation"],
[r"<%ID> = phi i8\* .*", "i8* operation", "int* operation"],
[r"<%ID> = phi i16\* .*", "i16* operation", "int* operation"],
[r"<%ID> = phi i32\* .*", "i32* operation", "int* operation"],
[r"<%ID> = phi i40\* .*", "i40* operation", "int* operation"],
[r"<%ID> = phi i64\* .*", "i64* operation", "int* operation"],
[r"<%ID> = phi i128\* .*", "i128* operation", "int* operation"],
[r"<%ID> = phi i1\*\* .*", "i1** operation", "int** operation"],
[r"<%ID> = phi i2\*\* .*", "i2** operation", "int** operation"],
[r"<%ID> = phi i4\*\* .*", "i4** operation", "int** operation"],
[r"<%ID> = phi i8\*\* .*", "i8** operation", "int** operation"],
[r"<%ID> = phi i16\*\* .*", "i16** operation", "int** operation"],
[r"<%ID> = phi i32\*\* .*", "i32** operation", "int** operation"],
[r"<%ID> = phi i40\*\* .*", "i40** operation", "int** operation"],
[r"<%ID> = phi i64\*\* .*", "i64** operation", "int** operation"],
[r"<%ID> = phi i128\*\* .*", "i128** operation", "int** operation"],
[r"<%ID> = phi i1\*\*\* .*", "i1*** operation", "int*** operation"],
[r"<%ID> = phi i2\*\*\* .*", "i2*** operation", "int*** operation"],
[r"<%ID> = phi i4\*\*\* .*", "i4*** operation", "int*** operation"],
[r"<%ID> = phi i8\*\*\* .*", "i8*** operation", "int*** operation"],
[r"<%ID> = phi i16\*\*\* .*", "i16*** operation", "int*** operation"],
[r"<%ID> = phi i32\*\*\* .*", "i32*** operation", "int*** operation"],
[r"<%ID> = phi i64\*\*\* .*", "i64*** operation", "int*** operation"],
[r"<%ID> = phi i128\*\*\* .*", "i128*** operation", "int*** operation"],
[r"<%ID> = phi x86_fp80 .*", "float operation", "floating point operation"],
[r"<%ID> = phi float .*", "float operation", "floating point operation"],
[r"<%ID> = phi double .*", "double operation", "floating point operation"],
[
r"<%ID> = phi <\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = phi <\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = phi <\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = phi x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = phi <\d+ x x86_fp80\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = phi <\d+ x float\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = phi <\d+ x double\*> .*",
r"<d x double*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = phi <\d+ x x86_fp80>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = phi <\d+ x float>\* .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = phi <\d+ x double>\* .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = phi x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[r"<%ID> = phi float\* .*", "float* operation", "floating point* operation"],
[r"<%ID> = phi double\* .*", "double* operation", "floating point* operation"],
[
r"<%ID> = phi x86_fp80\*\* .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = phi float\*\* .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = phi double\*\* .*",
r"double** operation",
r"floating point** operation",
],
[
r"<%ID> = phi x86_fp80\*\*\* .*",
r"float*** operation",
r"floating point*** operation",
],
[
r"<%ID> = phi float\*\*\* .*",
r"float*** operation",
r"floating point*** operation",
],
[
r"<%ID> = phi double\*\*\* .*",
r"double*** operation",
r"floating point*** operation",
],
[r"<%ID> = phi void \(.*\) \[.*", "function op", "function op"],
[r"<%ID> = phi void \(.*\)\* \[.*", "function* op", "function* op"],
[r"<%ID> = phi void \(.*\)\*\* \[.*", "function** op", "function** op"],
[r"<%ID> = phi void \(.*\)\*\*\* \[.*", "function*** op", "function*** op"],
[r"<%ID> = phi (<?{|opaque|<%ID>) .*", "struct/class op", "struct/class op"],
[
r"<%ID> = phi (<?{|opaque|<%ID>)\* .*",
r"struct/class* op",
r"struct/class* op",
],
[
r"<%ID> = phi (<?{|opaque|<%ID>)\*\* .*",
r"struct/class** op",
r"struct/class** op",
],
[
r"<%ID> = phi (<?{|opaque|<%ID>)\*\*\* .*",
r"struct/class*** op",
r"struct/class*** op",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i1, .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i2, .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i4, .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i8, .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i16, .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i32, .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i64, .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i128, .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i1\*, .*",
r"i1* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i2\*, .*",
r"i2* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i4\*, .*",
r"i4* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i8\*, .*",
r"i8* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i16\*, .*",
r"i16* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i32\*, .*",
r"i32* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i64\*, .*",
r"i64* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i128\*, .*",
r"i128* operation",
r"int* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i1\*\*, .*",
r"i1** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i2\*\*, .*",
r"i2** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i4\*\*, .*",
r"i4** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i8\*\*, .*",
r"i8** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i16\*\*, .*",
r"i16** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i32\*\*, .*",
r"i32** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i64\*\*, .*",
r"i64** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"i128\*\*, .*",
r"i128** operation",
r"int** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"x86_fp80, .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"float, .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"double, .*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"x86_fp80\*, .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"float\*, .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"double\*, .*",
r"double* operation",
r"floating point* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"x86_fp80\*\*, .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"float\*\*, .*",
r"float** operation",
r"floating point** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"double\*\*, .*",
r"double** operation",
r"floating point** operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r'%".*',
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<%.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i1>, .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i2>, .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i4>, .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i8>, .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i16>, .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i32>, .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i64>, .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i128>, .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x x86_fp80>, .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x float>, .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x double>, .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i1>\*, .*",
r"<d x i1>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i2>\*, .*",
r"<d x i2>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i4>\*, .*",
r"<d x i4>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i8>\*, .*",
r"<d x i8>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i16>\*, .*",
r"<d x i16>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i32>\*, .*",
r"<d x i32>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i64>\*, .*",
r"<d x i64>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x i128>\*, .*",
r"<d x i128>* operation",
r"<d x int>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x x86_fp80>\*, .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x float>\*, .*",
r"<d x float>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"<\d+ x double>\*, .*",
r"<d x double>* operation",
r"<d x floating point>* operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i1\], .*",
r"[d x i1] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i2\], .*",
r"[d x i2] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i4\], .*",
r"[d x i4] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i8\], .*",
r"[d x i8] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i16\], .*",
r"[d x i16] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i32\], .*",
r"[d x i32] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i64\], .*",
r"[d x i64] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i128\], .*",
r"[d x i128] operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x x86_fp80\], .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x float\], .*",
r"[d x float] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x double\], .*",
r"[d x double] operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x .*\], .*",
r"array of array operation",
r"array of array operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i1\]\*, .*",
r"[d x i1]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i2\]\*, .*",
r"[d x i2]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i4\]\*, .*",
r"[d x i4]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i8\]\*, .*",
r"[d x i8]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i16\]\*, .*",
r"[d x i16]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i32\]\*, .*",
r"[d x i32]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i64\]\*, .*",
r"[d x i64]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i128\]\*, .*",
r"[d x i128]* operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x x86_fp80\]\*, .*",
r"[d x float]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x float\]\*, .*",
r"[d x float]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x double\]\*, .*",
r"[d x double]* operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x .*\]\*, .*",
r"array of array* operation",
r"array of array operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i1\]\*\*, .*",
r"[d x i1]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i2\]\*\*, .*",
r"[d x i2]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i4\]\*\*, .*",
r"[d x i4]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i8\]\*\*, .*",
r"[d x i8]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i16\]\*\*, .*",
r"[d x i16]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i32\]\*\*, .*",
r"[d x i32]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i64\]\*\*, .*",
r"[d x i64]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x i128\]\*\*, .*",
r"[d x i128]** operation",
r"[d x int] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x x86_fp80\]\*\*, .*",
r"[d x float]** operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x float\]\*\*, .*",
r"[d x float]** operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x double\]\*\*, .*",
r"[d x double]** operation",
r"[d x floating point] operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r"\[\d+ x .*\], .*",
r"array of array** operation",
r"array of array operation",
],
[
r"<%ID> = getelementptr " + any_of(opt_GEP) + r".*\(.*\)\*+, .*",
r"function operation",
r"function operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i1 .*",
r"i1 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i2 .*",
r"i2 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i4 .*",
r"i4 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i8 .*",
r"i8 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i16 .*",
r"i16 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i32 .*",
r"i32 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i64 .*",
r"i64 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i128 .*",
r"i128 operation",
r"int operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i1\* .*",
r"i1* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i2\* .*",
r"i2* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i4\* .*",
r"i4* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i8\* .*",
r"i8* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i16\* .*",
r"i16* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i32\* .*",
r"i32* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i64\* .*",
r"i64* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*i128\* .*",
r"i128* operation",
r"int* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*x86_fp80 .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*float .*",
r"float operation",
r"floating point operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*double .*",
r"double operation",
r"floating point operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*x86_fp80\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*float\* .*",
r"float* operation",
r"floating point* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*double\* .*",
r"double* operation",
r"floating point* operation",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r'*%".*',
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*<?{.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r"*opaque.*",
r"struct/class op",
r"struct/class op",
],
[
r"<%ID> = invoke " + any_of(opt_invoke) + r'*%".*\*.*',
r"struct/class* op",
r"struct/class op",
],
[r"<%ID> = invoke " + any_of(opt_invoke) + r"*void .*", "void op", "void op"],
[r"invoke " + any_of(opt_invoke) + r"*void .*", "void op", "void op"],
[
r"<%ID> = extractelement <\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i1\*> .*",
r"<d x i1*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i2\*> .*",
r"<d x i2*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i4\*> .*",
r"<d x i4*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i8\*> .*",
r"<d x i8*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i16\*> .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i32\*> .*",
r"<d x i32*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i64\*> .*",
r"<d x i64*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = extractelement <\d+ x i128\*> .*",
r"<d x i128*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = extractelement <\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = extractelement <\d+ x x86_fp80\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = extractelement <\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = extractelement <\d+ x float\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = extractelement <\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = extractelement <\d+ x double\*> .*",
r"<d x double*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = extractelement <\d+ x \{.*\}> .*",
r"<d x struct> operation",
r"<d x struct> operation",
],
[
r"<%ID> = extractelement <\d+ x \{.*\}\*> .*",
r"<d x struct*> operation",
r"<d x struct*> operation",
],
[
r"<%ID> = insertelement <\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i1\*> .*",
r"<d x i1*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i2\*> .*",
r"<d x i2*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i4\*> .*",
r"<d x i4*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i8\*> .*",
r"<d x i8*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i16\*> .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i32\*> .*",
r"<d x i32*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i64\*> .*",
r"<d x i64*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = insertelement <\d+ x i128\*> .*",
r"<d x i128*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = insertelement <\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = insertelement <\d+ x x86_fp80\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = insertelement <\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = insertelement <\d+ x float\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = insertelement <\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = insertelement <\d+ x double\*> .*",
r"<d x double*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = insertelement <\d+ x \{.*\}> .*",
r"<d x struct> operation",
r"<d x struct> operation",
],
[
r"<%ID> = insertelement <\d+ x \{.*\}\*> .*",
r"<d x struct*> operation",
r"<d x struct*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i1> .*",
r"<d x i1> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i1\*> .*",
r"<d x i1*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i2> .*",
r"<d x i2> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i2\*> .*",
r"<d x i2*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i4> .*",
r"<d x i4> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i4\*> .*",
r"<d x i4*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i8> .*",
r"<d x i8> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i8\*> .*",
r"<d x i8*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i16> .*",
r"<d x i16> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i16\*> .*",
r"<d x i16*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i32> .*",
r"<d x i32> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i32\*> .*",
r"<d x i32*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i64> .*",
r"<d x i64> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i64\*> .*",
r"<d x i64*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x i128> .*",
r"<d x i128> operation",
r"<d x int> operation",
],
[
r"<%ID> = shufflevector <\d+ x i128\*> .*",
r"<d x i128*> operation",
r"<d x int*> operation",
],
[
r"<%ID> = shufflevector <\d+ x x86_fp80> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = shufflevector <\d+ x x86_fp80\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = shufflevector <\d+ x float> .*",
r"<d x float> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = shufflevector <\d+ x float\*> .*",
r"<d x float*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = shufflevector <\d+ x double> .*",
r"<d x double> operation",
r"<d x floating point> operation",
],
[
r"<%ID> = shufflevector <\d+ x double\*> .*",
r"<d x double*> operation",
r"<d x floating point*> operation",
],
[
r"<%ID> = shufflevector <\d+ x \{.*\}> .*",
r"<d x struct> operation",
r"<d x struct> operation",
],
[
r"<%ID> = shufflevector <\d+ x \{.*\}\*> .*",
r"<d x struct*> operation",
r"<d x struct*> operation",
],
[
r"<%ID> = bitcast void \(.* to .*",
r"in-between operation",
r"in-between operation",
],
[
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque) .* to .*",
r"in-between operation",
r"in-between operation",
],
[
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\* .* to .*",
r"in-between operation",
r"in-between operation",
],
[
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\*\* .* to .*",
r"in-between operation",
r"in-between operation",
],
[
r"<%ID> = bitcast (i\d+|float|double|x86_fp80|opaque)\*\*\* .* to .*",
r"in-between operation",
r"in-between operation",
],
[
r"<%ID> = bitcast \[\d+.* to .*",
r"in-between operation",
r"in-between operation",
],
[
r"<%ID> = bitcast <\d+.* to .*",
r"in-between operation",
r"in-between operation",
],
[
r'<%ID> = bitcast (%"|<%|<?{).* to .*',
r"in-between operation",
r"in-between operation",
],
[r"<%ID> = fpext .*", "in-between operation", "in-between operation"],
[r"<%ID> = fptrunc .*", "in-between operation", "in-between operation"],
[r"<%ID> = sext .*", "in-between operation", "in-between operation"],
[r"<%ID> = trunc .* to .*", "in-between operation", "in-between operation"],
[r"<%ID> = zext .*", "in-between operation", "in-between operation"],
[r"<%ID> = sitofp .*", "in-between operation", "in-between operation"],
[r"<%ID> = uitofp .*", "in-between operation", "in-between operation"],
[r"<%ID> = inttoptr .*", "in-between operation", "in-between operation"],
[r"<%ID> = ptrtoint .*", "in-between operation", "in-between operation"],
[r"<%ID> = fptosi .*", "in-between operation", "in-between operation"],
[r"<%ID> = fptoui .*", "in-between operation", "in-between operation"],
[r"<%ID> = extractvalue .*", "in-between operation", "in-between operation"],
[r"<%ID> = insertvalue .*", "in-between operation", "in-between operation"],
[r"resume .*", "in-between operation", "in-between operation"],
[r"(tail |musttail |notail )?call( \w+)? void .*", "call void", "call void"],
[r"i\d{1,2} <(INT|FLOAT)>, label <%ID>", "blob", "blob"],
[r"<%ID> = select .*", "blob", "blob"],
[r".*to label.*unwind label.*", "blob", "blob"],
[r"catch .*", "blob", "blob"],
[r"cleanup", "blob", "blob"],
[r"<%ID> = landingpad .", "blob", "blob"],
[r"; <label>:<LABEL>", "blob", "blob"],
[r"<LABEL>:", "blob", "blob"],
[r"br i1 .*", "blob", "blob"],
[r"br label .*", "blob", "blob"],
[r"indirectbr .*", "blob", "blob"],
[r"switch .*", "blob", "blob"],
[r"unreachable.*", "blob", "blob"],
[r"ret void", "blob", "blob"],
[r"!UNK", "blob", "blob"],
]
|
CompilerGym-development
|
compiler_gym/third_party/inst2vec/rgx_utils.py
|
# NCC: Neural Code Comprehension
# https://github.com/spcl/ncc
# Copyright 2018 ETH Zurich
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ==============================================================================
# flake8: noqa
"""Preprocess LLVM IR code to XFG for inst2vec training"""
import copy
import os
import pickle
import re
from typing import Dict
import networkx as nx
from compiler_gym.third_party.inst2vec import rgx_utils as rgx
########################################################################################################################
# LLVM IR preprocessing
########################################################################################################################
def GetFunctionsDeclaredInFile(bytecode_lines):
functions_declared_in_file = []
# Loop on all lines in data
for line in bytecode_lines:
# Check whether it contains a function declaration
if "declare" in line and not line.startswith("call void"):
# Find the function name
func = re.match(r"declare .*(" + rgx.func_name + r")", line)
if func is None:
raise ValueError(f"Could not match function name in {line}")
func = func.group(1)
# Add it to the list
functions_declared_in_file.append(func)
return functions_declared_in_file
def get_functions_declared_in_files(data):
"""
For each file, construct a list of names of the functions declared in the file, before the corresponding statements
are removed by pre-processing. The list is used later on in the graph construction to identify the names of
functions declared in this file.
:param data: input data as a list of files where each file is a list of strings
:return: functions_declared_in_files: list of lists of names of the functions declared in this file
"""
return [GetFunctionsDeclaredInFile(file) for file in data]
def keep(line):
"""
Determine whether a line of code is representative
and should be kept in the data set or not.
:param line: string representing the line of code to test
:return: boolean: True if the line is to be kept,
False if the line is to be discarded
"""
# Ignore empty lines.
if line == "":
return False
# Ignore comment lines (except labels).
if line[0] == ";" and not line[0:9] == "; <label>":
return False
if line[0] == "!" or line[0] == "\n":
return False
if (
line.strip()[0] == "{"
or line.strip()[0] == "}"
or line.strip()[0] == "["
or line.strip()[0] == "]"
):
return False
# Ignore empty lines (NOTE: possible dupe of `if line == ''` above?).
if len(line) == 0:
return False
if "source_filename" in line:
return False
if "target triple" in line:
return False
if "target datalayout" in line:
return False
if "attributes" in line:
return False
if "module asm " in line:
return False
if "declare" in line:
return False
modif_line = re.sub(r"\".*\"", "", line)
if re.match(rgx.global_id + r" = .*alias ", modif_line):
return False
if re.search("call void asm", line):
return False
match = re.search(r"\$.* = comdat any", line)
if match:
return False
match = re.match(r"\s+;", line)
if match:
return False
# If none of the above matched, keep the line.
return True
def remove_non_representative_code(data):
"""
Remove lines of code that aren't representative of LLVM-IR "language"
and shouldn't be used for training the embeddings
:param data: input data as a list of files where each file is a list of strings
:return: input data with non-representative lines of code removed
"""
for i in range(len(data)):
data[i] = [line for line in data[i] if keep(line)]
return data
def remove_leading_spaces(data):
"""
Remove the leading spaces (indentation) of lines of code
:param data: input data as a list of files, where each file is a list of strings
:return: input data with leading spaces removed
"""
for i in range(len(data)):
for j in range(len(data[i])):
data[i][j] = data[i][j].strip()
return data
def remove_trailing_comments_and_metadata(data):
"""
Remove comments, metadata and attribute groups trailing at the end of a line
:param data: input data as a list of files where each file is a list of strings
:return: modified input data
"""
for i in range(len(data)):
for j in range(len(data[i])):
line = data[i][j]
# If the line contains a trailing metadata
pos = line.find("!")
if pos != -1:
# Remove metadatas which are function arguments
while re.search(r"\(.*metadata !.*\)", line) is not None:
line = re.sub(r"(, )?metadata !\d+(, )?", "", line)
line = re.sub(r"(, )?metadata !\w+(, )?", "", line)
line = re.sub(r"metadata !\d+(, )?", "", line)
line = re.sub(r"metadata !\w+(, )?", "", line)
pos = line.find("!")
if pos != -1:
# Check whether the '!' is part of a string expression
pos_string = line[:pos].find('c"')
if (
pos_string == -1
): # there is no string expression earlier on the line
line = line[:pos].strip() # erase from here to the end of the line
if line[-1] == ",": # can happen with !tbaa
line = line[:-1].strip()
else: # there is a string expression earlier on the line
pos_endstring = line[pos_string + 2 : pos].find('"')
if (
pos_endstring != -1
): # the string has been terminated before the ;
line = line[
:pos
].strip() # erase from here to the end of the line
if line[-1] == ",": # can happen with !tbaa
line = line[:-1].strip()
# If the line contains a trailing attribute group
pos = line.find("#")
if pos != -1:
# Check whether the ';' is part of a string expression
s = re.search(r'c".*"', line[:pos])
if not s: # there is no string expression earlier on the line
line = line[:pos].strip() # erase from here to the end of the line
else: # there is a string expression earlier on the line
pos_endstring = s.end()
if (
pos_endstring != -1
): # the string has been terminated before the ;
line = line[
:pos
].strip() # erase from here to the end of the line
data[i][j] = line
return data
def collapse_stmt_units_to_a_line(data):
"""
Some statements are written on several lines though they really are just one statement
Detect and collapse these
:param data: input data as a list of files where each file is a list of strings
:return: modified input data
"""
to_track = ""
erase_token = "to_erase" # Helper variable to mark lines to be erased
separator = "\n "
# Detect multi-line statements and collapse them
for file in data:
for i in range(len(file)):
if file[i] == to_track:
print("Found", to_track)
if re.match(rgx.local_id + " = landingpad", file[i]):
if i + 1 < len(file):
if (
re.match(r"cleanup", file[i + 1])
or re.match(r"filter", file[i + 1])
or re.match(r"catch", file[i + 1])
):
file[i] += separator + file[i + 1] # collapse lines
file[i + 1] = erase_token # mark as "to erase"
else:
continue
if i + 2 < len(file):
if (
re.match(r"cleanup", file[i + 2])
or re.match(r"filter", file[i + 2])
or re.match(r"catch", file[i + 2])
):
file[i] += separator + file[i + 2] # collapse lines
file[i + 2] = erase_token # mark as "to erase"
else:
continue
if i + 3 < len(file):
if (
re.match(r"cleanup", file[i + 3])
or re.match(r"filter", file[i + 3])
or re.match(r"catch", file[i + 3])
):
file[i] += separator + file[i + 3] # collapse lines
file[i + 3] = erase_token # mark as "to erase"
else:
continue
elif re.match(r"switch", file[i]):
for j in range(i + 1, len(file)):
if re.search(r"i\d+ -?\d+, label " + rgx.local_id, file[j]):
# if this statement is part of the switch,
file[i] += separator + file[j] # collapse lines
file[j] = erase_token # mark as "to erase"
else:
# if this statement isn't part of the switch
file[i] += "]" # add closing bracket
break
elif re.search(r"invoke", file[i]):
if i + 1 < len(file):
if re.match(
r"to label " + rgx.local_id + " unwind label " + rgx.local_id,
file[i + 1],
):
file[i] += separator + file[i + 1] # collapse lines
file[i + 1] = erase_token # mark as "to erase"
# Erase statements which have been rendered superfluous from collapsing
for i in range(len(data)):
data[i] = [line for line in data[i] if line != erase_token]
return data
def remove_structure_definitions(data):
"""
Remove lines of code that aren't representative of LLVM-IR "language"
and shouldn't be used for training the embeddings
:param data: input data as a list of files where each file is a list of strings
:return: input data with non-representative lines of code removed
"""
for i in range(len(data)):
data[i] = [
line
for line in data[i]
if not re.match("%.* = type (<?{ .* }|opaque|{})", line)
]
return data
def preprocess(data):
"""Pre-processing of source code:
- remove non-representative lines of code
- remove leading spaces (indentation)
- remove trailing comments and metadata
:param data: input data as a list of files where each file is a list of strings
:return: preprocessed_data: modified input data
functions_declared_in_files:
"""
functions_declared_in_files = get_functions_declared_in_files(data)
data = remove_non_representative_code(data)
data = remove_leading_spaces(data)
data = remove_trailing_comments_and_metadata(data)
data = collapse_stmt_units_to_a_line(data)
preprocessed_data = copy.deepcopy(data)
preprocessed_data = remove_structure_definitions(preprocessed_data)
return preprocessed_data, functions_declared_in_files
########################################################################################################################
# XFG-transforming (inline and abstract statements)
########################################################################################################################
# Helper regexs for structure type inlining
vector_type = r"<\d+ x " + rgx.first_class_type + r">"
array_type = r"\[\d+ x " + rgx.first_class_type + r"\]"
array_of_array_type = r"\[\d+ x " + r"\[\d+ x " + rgx.first_class_type + r"\]" + r"\]"
function_type = (
rgx.first_class_type
+ r" \("
+ rgx.any_of([rgx.first_class_type, vector_type, array_type, "..."], ",")
+ "*"
+ rgx.any_of([rgx.first_class_type, vector_type, array_type, "..."])
+ r"\)\**"
)
structure_entry = rgx.any_of(
[
rgx.first_class_type,
vector_type,
array_type,
array_of_array_type,
function_type,
]
)
structure_entry_with_comma = rgx.any_of(
[
rgx.first_class_type,
vector_type,
array_type,
array_of_array_type,
function_type,
],
",",
)
literal_structure = (
"(<?{ " + structure_entry_with_comma + "*" + structure_entry + " }>?|opaque|{})"
)
literal_structure_with_comma = literal_structure + ", "
def construct_struct_types_dictionary_for_file(data):
"""
Construct a dictionary of structure names
:param data: list of strings representing the content of one file
:return: data: modified input data
ready: dictionary of structure names
"""
# Optional: tracking
to_track = ""
# Three dictionaries
to_process = dict() # contains non-literal structures
to_inline = dict() # contains literal structures to be inlined in "to_process"
ready = dict() # contains literal structures which have already been inlined
# Helper strings
struct_prev = [structure_entry, literal_structure]
struct_prev_with_comma = [
structure_entry_with_comma,
literal_structure_with_comma,
]
use_previously_inlined_stmts = False
# Put all "type" expressions from "data" into "to_process"
for stmt in data:
if len(to_track) > 0:
if to_track in stmt:
print("Found statement ", to_track)
if re.match(rgx.struct_name + r" = type <?{?", stmt):
k = re.sub(r"(" + rgx.struct_name + r") = type <?{?.*}?>?$", r"\g<1>", stmt)
v = re.sub(rgx.struct_name + " = type (<?{?.*}?>?)$", r"\g<1>", stmt)
to_process[k] = v
# Loop over contents of "to_process"
for i in list(to_process.items()):
# Move the literal structures to to_inline
if re.match(literal_structure, i[1]):
to_inline[i[0]] = i[1]
del to_process[i[0]]
# Helper variables for iteration checks
counter = 0
prev_to_process_len = len(to_process)
# While "to_process" is not empty
while len(to_process) > 0:
# Loop over contents of to_inline
for i in list(to_inline.items()):
# and inline these statements in to_process
for p in list(to_process.items()):
pattern = re.escape(i[0]) + rgx.struct_lookahead
if re.search(pattern, p[1]):
to_process[p[0]] = re.sub(pattern, i[1], p[1])
# Under certain circumstances
if use_previously_inlined_stmts:
# print("\t... using previously inlined statements")
# Loop over contents of "to_process"
for p in list(to_process.items()):
# and inline these statements with structures from "ready"
for i in list(ready.items()):
pattern = re.escape(i[0]) + rgx.struct_lookahead
if re.search(pattern, p[1]):
print("bingo")
to_process[p[0]] = re.sub(pattern, i[1], p[1])
# Move contents of to_inline to ready
ready.update(to_inline)
to_inline = {}
# Update possible structure entries
if counter < 3:
comp_structure_entry = rgx.any_of(struct_prev)
comp_structure_entry_with_comma = rgx.any_of(struct_prev_with_comma)
comp_structure = (
"<?{ "
+ comp_structure_entry_with_comma
+ "*"
+ comp_structure_entry
+ " }>?"
)
struct_prev.append(comp_structure)
struct_prev_with_comma.append(comp_structure + ", ")
else:
comp_structure = r"<?{ [ <>{}\dx\[\]\(\)\.,\*%IDvfloatdubeipqcy]+}>?$"
# Loop over contents of to_process
for i in list(to_process.items()):
if re.match(comp_structure, i[1]):
to_inline[i[0]] = i[1]
del to_process[i[0]]
# Update counter
counter += 1
# Make sure progress as been made since the last iteration
if len(to_process) == prev_to_process_len and counter > 3:
# If this isn't the case, check if there is a type defined cyclically
cycle_found = False
for i in list(to_process.items()):
# - Recursive, eg %intlist = type { %intlist*, i32 }
# tracking
if len(to_track) > 0:
if to_track in i[0]:
print("Found", to_track)
if re.search(re.escape(i[0]) + rgx.struct_lookahead, i[1]):
cycle_found = True
new_entry = i[0] + "_cyclic"
to_inline[new_entry] = "opaque"
to_process[i[0]] = re.sub(
re.escape(i[0]) + rgx.struct_lookahead, new_entry, i[1]
)
# break
if not cycle_found:
# - Cyclic, eg
# %"class.std::ios_base": { i32 (...)**, i64, i32, %"struct.std::ios_base::_Callback_list"*, ...}
# %"struct.std::ios_base::_Callback_list": { opaque*, void (i32, %"class.std::ios_base"*, i32)* }
for j in list(to_process.items()):
if i != j and re.search(
re.escape(i[0]) + rgx.struct_lookahead, j[1]
):
cycle_found = True
new_entry = i[0] + "_cyclic"
to_inline[new_entry] = "opaque"
to_process[j[0]] = re.sub(
re.escape(i[0]) + rgx.struct_lookahead, new_entry, j[1]
)
# break
# If no cyclic type definition was found although no progress was made since the last pass, abort
if not cycle_found:
if not use_previously_inlined_stmts:
# Perhaps some stmts which should be inlined are hiding in "ready": use these at the next pass
use_previously_inlined_stmts = True
else:
assert cycle_found, (
"Counter step: "
+ str(counter)
+ ", could not inline "
+ str(len(to_process))
+ " statements : \n"
+ string_of_items(to_process)
)
else:
use_previously_inlined_stmts = False # reset
prev_to_process_len = len(to_process)
# Stopping condition in case we've been looping for a suspiciously long time
assert counter < 1000, (
"Could not inline "
+ str(len(to_process))
+ " statements after "
+ str(counter)
+ " steps: \n"
+ string_of_items(to_process)
)
# Move contents of "to_inline" to "ready"
ready.update(to_inline)
return data, ready
def GetStructTypes(ir: str) -> Dict[str, str]:
"""Extract a dictionary of struct definitions from the given IR.
:param ir: A string of LLVM IR.
:return: A dictionary of <name, def> entries, where <name> is the name of a struct
definition (e.g. "%struct.foo"), and <def> is the definition of the member
types, e.g. "{ i32 }".
"""
try:
_, dict_temp = construct_struct_types_dictionary_for_file(ir.split("\n"))
return dict_temp
except AssertionError as e:
raise ValueError(e) from e
def PreprocessStatement(stmt: str) -> str:
# Remove local identifiers
stmt = re.sub(rgx.local_id, "<%ID>", stmt)
# Global identifiers
stmt = re.sub(rgx.global_id, "<@ID>", stmt)
# Remove labels
if re.match(r"; <label>:\d+:?(\s+; preds = )?", stmt):
stmt = re.sub(r":\d+", ":<LABEL>", stmt)
stmt = re.sub("<%ID>", "<LABEL>", stmt)
elif re.match(rgx.local_id_no_perc + r":(\s+; preds = )?", stmt):
stmt = re.sub(rgx.local_id_no_perc + ":", "<LABEL>:", stmt)
stmt = re.sub("<%ID>", "<LABEL>", stmt)
if "; preds = " in stmt:
s = stmt.split(" ")
if s[-1][0] == " ":
stmt = s[0] + s[-1]
else:
stmt = s[0] + " " + s[-1]
# Remove floating point values
stmt = re.sub(rgx.immediate_value_float_hexa, "<FLOAT>", stmt)
stmt = re.sub(rgx.immediate_value_float_sci, "<FLOAT>", stmt)
# Remove integer values
if (
re.match("<%ID> = extractelement", stmt) is None
and re.match("<%ID> = extractvalue", stmt) is None
and re.match("<%ID> = insertelement", stmt) is None
and re.match("<%ID> = insertvalue", stmt) is None
):
stmt = re.sub(r"(?<!align)(?<!\[) " + rgx.immediate_value_int, " <INT>", stmt)
# Remove string values
stmt = re.sub(rgx.immediate_value_string, " <STRING>", stmt)
# Remove index types
if (
re.match("<%ID> = extractelement", stmt) is not None
or re.match("<%ID> = insertelement", stmt) is not None
):
stmt = re.sub(r"i\d+ ", "<TYP> ", stmt)
return stmt
|
CompilerGym-development
|
compiler_gym/third_party/inst2vec/inst2vec_preprocess.py
|
#!/usr/bin/env python3
#
# This script compiles and links the sources for a cBench benchmark into a
# single unoptimized LLVM module.
#
# Usage:
#
# $ make_cBench_llvm_module.py <in_dir> <outpath> [<cflag>...]
#
# This compiles the code from <in_dir> and generates an LLVM bitcode module at
# the given <outpath>, using any additional <cflags> as clang arguments.
import sys
from pathlib import Path
from typing import List
from compiler_gym.envs.llvm.llvm_benchmark import make_benchmark
def make_cbench_llvm_module(
benchmark_dir: Path, cflags: List[str], output_path: Path
) -> str:
"""Compile a cBench benchmark into an unoptimized LLVM bitcode file."""
src_dir = benchmark_dir / "src"
if not src_dir.is_dir():
src_dir = benchmark_dir
assert src_dir.is_dir(), f"Source directory not found: {src_dir}"
src_files = [path for path in src_dir.iterdir() if path.name.endswith(".c")]
assert src_files, f"No source files in {src_dir}"
benchmark = make_benchmark(inputs=src_files, copt=cflags or [])
# Write just the bitcode to file.
with open(output_path, "wb") as f:
f.write(benchmark.proto.program.contents)
def main():
"""Main entry point."""
# Parse arguments.
benchmark_dir, output_path, *cflags = sys.argv[1:]
benchmark_dir = Path(benchmark_dir).absolute().resolve()
output_path = Path(output_path).absolute().resolve()
make_cbench_llvm_module(benchmark_dir, cflags, output_path)
if __name__ == "__main__":
main()
|
CompilerGym-development
|
compiler_gym/third_party/cbench/make_llvm_module.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
AUTOPHASE_FEATURE_NAMES = [
"BBNumArgsHi",
"BBNumArgsLo",
"onePred",
"onePredOneSuc",
"onePredTwoSuc",
"oneSuccessor",
"twoPred",
"twoPredOneSuc",
"twoEach",
"twoSuccessor",
"morePreds",
"BB03Phi",
"BBHiPhi",
"BBNoPhi",
"BeginPhi",
"BranchCount",
"returnInt",
"CriticalCount",
"NumEdges",
"const32Bit",
"const64Bit",
"numConstZeroes",
"numConstOnes",
"UncondBranches",
"binaryConstArg",
"NumAShrInst",
"NumAddInst",
"NumAllocaInst",
"NumAndInst",
"BlockMid",
"BlockLow",
"NumBitCastInst",
"NumBrInst",
"NumCallInst",
"NumGetElementPtrInst",
"NumICmpInst",
"NumLShrInst",
"NumLoadInst",
"NumMulInst",
"NumOrInst",
"NumPHIInst",
"NumRetInst",
"NumSExtInst",
"NumSelectInst",
"NumShlInst",
"NumStoreInst",
"NumSubInst",
"NumTruncInst",
"NumXorInst",
"NumZExtInst",
"TotalBlocks",
"TotalInsts",
"TotalMemInst",
"TotalFuncs",
"ArgsPhi",
"testUnary",
]
# The dimensionality of the autophase feature vector.
AUTOPHASE_FEATURE_DIM: int = len(AUTOPHASE_FEATURE_NAMES)
|
CompilerGym-development
|
compiler_gym/third_party/autophase/__init__.py
|
# Copyright 2013 David Malcolm <dmalcolm@redhat.com>
# Copyright 2013 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
import argparse
import os
from pathlib import Path
def cmdline_to_argv(cmdline):
"""
Reconstruct an argv list from a cmdline string
"""
# Convert the input str to a list of characters
# and Quoted instances
def iter_fragments():
class Quoted:
def __init__(self, quotechar, text):
self.quotechar = quotechar
self.text = text
def __repr__(self):
return "Quoted(%r, %r)" % (self.quotechar, self.text)
def __str__(self):
return "%s%s%s" % (self.quotechar, self.text, self.quotechar)
for i, fragment in enumerate(cmdline.split('"')):
if i % 2:
# within a quoted section:
yield Quoted('"', fragment)
else:
for ch in fragment:
yield ch
# Now split these characters+Quoted by whitespace:
result = []
pending_arg = ""
for fragment in iter_fragments():
if fragment in (" ", "\t"):
result.append(pending_arg)
pending_arg = ""
else:
pending_arg += str(fragment)
if pending_arg:
result.append(pending_arg)
return result
class GccInvocation:
"""
Parse a command-line invocation of GCC and extract various options
of interest
"""
def __init__(self, argv):
# Store the original argv for logging / debugging.
self.original_argv = argv
# Strip `-Xclang` arguments now because the hyphenated parameters
# confuse argparse:
sanitized_argv = argv.copy()
for i in range(len(argv) - 2, -1, -1):
if argv[i] == "-Xclang":
del argv[i + 1]
del argv[i]
self.argv = argv
self.executable = argv[0]
self.progname = os.path.basename(self.executable)
DRIVER_NAMES = (
"c89",
"c99",
"cc",
"gcc",
"c++",
"g++",
"xgcc",
"clang",
"clang++",
)
self.is_driver = self.progname in DRIVER_NAMES
self.sources = []
self.defines = []
self.includepaths = []
self.otherargs = []
if self.progname == "collect2":
# collect2 appears to have a (mostly) different set of
# arguments to the rest:
return
parser = argparse.ArgumentParser(add_help=False)
def add_flag_opt(flag):
parser.add_argument(flag, action="store_true")
def add_opt_with_param(flag):
parser.add_argument(flag, type=str)
def add_opt_NoDriverArg(flag):
if self.is_driver:
add_flag_opt(flag)
else:
add_opt_with_param(flag)
parser.add_argument("-o", type=str)
parser.add_argument("-D", type=str, action="append", default=[])
parser.add_argument("-U", type=str, action="append", default=[])
parser.add_argument("-I", type=str, action="append", default=[])
# Arguments that take a further param:
parser.add_argument("-x", type=str)
# (for now, drop them on the floor)
# Arguments for dependency generation (in the order they appear
# in gcc/c-family/c.opt)
# (for now, drop them on the floor)
add_flag_opt("-M")
add_opt_NoDriverArg("-MD")
add_opt_with_param("-MF")
add_flag_opt("-MG")
add_flag_opt("-MM")
add_opt_NoDriverArg("-MMD")
add_flag_opt("-MP")
add_opt_with_param("-MQ")
add_opt_with_param("-MT")
# Additional arguments for clang:
add_opt_with_param("-resource-dir")
add_opt_with_param("-target")
# Various other arguments that take a 2nd argument:
for arg in [
"-include",
"-imacros",
"-idirafter",
"-iprefix",
"-iwithprefix",
"-iwithprefixbefore",
"-isysroot",
"-imultilib",
"-isystem",
"-iquote",
]:
parser.add_argument(arg, type=str)
# (for now, drop them on the floor)
# Various arguments to cc1 etc that take a 2nd argument:
for arg in ["-dumpbase", "-auxbase-strip"]:
parser.add_argument(arg, type=str)
# (for now, drop them on the floor)
args, remainder = parser.parse_known_args(sanitized_argv[1:])
self.parsed_args = args
self.defines = args.D
self.includepaths = args.I
for arg in remainder:
if arg.startswith("-") and arg != "-":
self.otherargs.append(arg)
else:
self.sources.append(arg)
# Determine the absolute path of the generated output.
output = self.parsed_args.o or "a.out"
self.output_path = Path(output).absolute()
@classmethod
def from_cmdline(cls, cmdline):
return cls(cmdline_to_argv(cmdline))
def __repr__(self):
return (
"GccInvocation(executable=%r, sources=%r,"
" defines=%r, includepaths=%r, otherargs=%r)"
% (
self.executable,
self.sources,
self.defines,
self.includepaths,
self.otherargs,
)
)
def restrict_to_one_source(self, source):
"""
Make a new GccInvocation, preserving most arguments, but
restricting the compilation to just the given source file
"""
newargv = [self.executable]
newargv += ["-D%s" % define for define in self.defines]
newargv += ["-I%s" % include for include in self.includepaths]
newargv += self.otherargs
newargv += [source]
return GccInvocation(newargv)
|
CompilerGym-development
|
compiler_gym/third_party/gccinvocation/gccinvocation.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Module for resolving paths to LLVM binaries and libraries."""
import io
import logging
import shutil
import sys
import tarfile
from pathlib import Path
from threading import Lock
from typing import Optional
from fasteners import InterProcessLock
from compiler_gym.util.download import download
from compiler_gym.util.filesystem import extract_tar
from compiler_gym.util.runfiles_path import cache_path, runfiles_path, site_data_path
logger = logging.getLogger(__name__)
# The data archive containing LLVM binaries and libraries.
_LLVM_URL, _LLVM_SHA256 = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm-v0-macos.tar.bz2",
"731ae351b62c5713fb5043e0ccc56bfba4609e284dc816f0b2a5598fb809bf6b",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm-v0-linux.tar.bz2",
"59c3f328efd51994a11168ca15e43a8d422233796c6bc167c9eb771c7bd6b57e",
),
}[sys.platform]
# Thread lock to prevent race on download_llvm_files() from multi-threading.
# This works in tandem with the inter-process file lock - both are required.
_LLVM_DOWNLOAD_LOCK = Lock()
_LLVM_UNPACKED_LOCATION: Optional[Path] = None
def _download_llvm_files(destination: Path) -> Path:
"""Download and unpack the LLVM data pack."""
logger.warning(
"Installing the CompilerGym LLVM environment runtime. This may take a few moments ..."
)
# Tidy up an incomplete unpack.
shutil.rmtree(destination, ignore_errors=True)
tar_contents = io.BytesIO(download(_LLVM_URL, sha256=_LLVM_SHA256))
destination.parent.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=tar_contents, mode="r:bz2") as tar:
extract_tar(tar, destination)
assert destination.is_dir()
assert (destination / "LICENSE").is_file()
return destination
def download_llvm_files() -> Path:
"""Download and unpack the LLVM data pack."""
global _LLVM_UNPACKED_LOCATION
unpacked_location = site_data_path("llvm-v0")
# Fast path for repeated calls.
if _LLVM_UNPACKED_LOCATION == unpacked_location:
return unpacked_location
with _LLVM_DOWNLOAD_LOCK:
# Fast path for first call. This check will be repeated inside the locked
# region if required.
if (unpacked_location / ".unpacked").is_file():
_LLVM_UNPACKED_LOCATION = unpacked_location
return unpacked_location
with InterProcessLock(cache_path(".llvm-v0-install.LOCK")):
# Now that the lock is acquired, repeat the check to see if it is
# necessary to download the dataset.
if (unpacked_location / ".unpacked").is_file():
return unpacked_location
_download_llvm_files(unpacked_location)
# Create the marker file to indicate that the directory is unpacked
# and ready to go.
(unpacked_location / ".unpacked").touch()
_LLVM_UNPACKED_LOCATION = unpacked_location
return unpacked_location
def clang_path() -> Path:
"""Return the path of clang."""
return download_llvm_files() / "bin/clang"
def lli_path() -> Path:
"""Return the path of lli."""
return download_llvm_files() / "bin/lli"
def llc_path() -> Path:
"""Return the path of llc."""
return download_llvm_files() / "bin/llc"
def llvm_as_path() -> Path:
"""Return the path of llvm-as."""
return download_llvm_files() / "bin/llvm-as"
def llvm_dis_path() -> Path:
"""Return the path of llvm-as."""
return download_llvm_files() / "bin/llvm-dis"
def llvm_extract_one_path() -> Path:
"""Return the path of llvm-extract-one."""
return runfiles_path("compiler_gym/envs/llvm/service/llvm-extract-one")
def llvm_link_path() -> Path:
"""Return the path of llvm-link."""
return download_llvm_files() / "bin/llvm-link"
def llvm_stress_path() -> Path:
"""Return the path of llvm-stress."""
return download_llvm_files() / "bin/llvm-stress"
def llvm_diff_path() -> Path:
"""Return the path of llvm-diff."""
return download_llvm_files() / "bin/llvm-diff"
def opt_path() -> Path:
"""Return the path of opt."""
return download_llvm_files() / "bin/opt"
|
CompilerGym-development
|
compiler_gym/third_party/llvm/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Constants for the InstCount feature space."""
# Generated using:
#
# $ bazel run //compiler_gym/third_party/llvm:PrintInstCountFeatureNames
INST_COUNT_FEATURE_NAMES = [
"TotalInsts",
"TotalBlocks",
"TotalFuncs",
"Ret",
"Br",
"Switch",
"IndirectBr",
"Invoke",
"Resume",
"Unreachable",
"CleanupRet",
"CatchRet",
"CatchSwitch",
"CallBr",
"FNeg",
"Add",
"FAdd",
"Sub",
"FSub",
"Mul",
"FMul",
"UDiv",
"SDiv",
"FDiv",
"URem",
"SRem",
"FRem",
"Shl",
"LShr",
"AShr",
"And",
"Or",
"Xor",
"Alloca",
"Load",
"Store",
"GetElementPtr",
"Fence",
"AtomicCmpXchg",
"AtomicRMW",
"Trunc",
"ZExt",
"SExt",
"FPToUI",
"FPToSI",
"UIToFP",
"SIToFP",
"FPTrunc",
"FPExt",
"PtrToInt",
"IntToPtr",
"BitCast",
"AddrSpaceCast",
"CleanupPad",
"CatchPad",
"ICmp",
"FCmp",
"PHI",
"Call",
"Select",
"UserOp1",
"UserOp2",
"VAArg",
"ExtractElement",
"InsertElement",
"ShuffleVector",
"ExtractValue",
"InsertValue",
"LandingPad",
"Freeze",
]
INST_COUNT_FEATURE_DIMENSIONALITY = len(INST_COUNT_FEATURE_NAMES)
INST_COUNT_FEATURE_SHAPE = (INST_COUNT_FEATURE_DIMENSIONALITY,)
|
CompilerGym-development
|
compiler_gym/third_party/llvm/instcount.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Test that the DeepDataFlow dataset contains the expected numbers of files."""
import pytest
from compiler_gym.util.runfiles_path import runfiles_path
from tests.test_main import main
# The number of bitcode files in the DeepDataFlow dataset, grouped by source.
EXPECTED_NUMBER_OF_BITCODE_FILES = {
"blas": 300,
"linux": 13920,
"github": 50708,
"npb": 122,
"poj104": 49628,
"tensorflow": 1985,
}
@pytest.fixture(scope="session", params=list(EXPECTED_NUMBER_OF_BITCODE_FILES.keys()))
def subset(request):
return request.param
def test_deep_dataflow_file_count(subset: str):
bitcode_dir = runfiles_path("compiler_gym/third_party/DeepDataFlow") / subset
num_files = len([f for f in bitcode_dir.iterdir() if f.name.endswith(".bc")])
assert num_files == EXPECTED_NUMBER_OF_BITCODE_FILES[subset]
if __name__ == "__main__":
main()
|
CompilerGym-development
|
compiler_gym/third_party/DeepDataFlow/file_count_test.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines validation errors."""
from typing import Any, Dict
from pydantic import BaseModel
class ValidationError(BaseModel):
"""A ValidationError describes an error encountered in a call to
:meth:`env.validate() <compiler_gym.envs.CompilerEnv.validate>`.
"""
type: str
"""A short name describing the type of error that occured. E.g.
:code:`"Runtime crash"`.
"""
data: Dict[str, Any] = {}
"""A JSON-serializable dictionary of data that further describes the error.
This data dictionary can contain any information that may be relevant for
diagnosing the underlying issue, such as a stack trace or an error line
number. There is no specified schema for this data, validators are free to
return whatever data they like. Setting this field is optional.
"""
def __lt__(self, rhs):
# Implement the < operator so that lists of ValidationErrors can be
# sorted.
if not isinstance(rhs, ValidationError):
return True
return (self.type, self.data) <= (rhs.type, rhs.data)
|
CompilerGym-development
|
compiler_gym/errors/validation_errors.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compiler_gym.errors.dataset_errors import BenchmarkInitError, DatasetInitError
from compiler_gym.errors.download_errors import DownloadFailed, TooManyRequests
from compiler_gym.errors.service_errors import (
EnvironmentNotSupported,
ServiceError,
ServiceInitError,
ServiceIsClosed,
ServiceOSError,
ServiceTransportError,
SessionNotFound,
)
from compiler_gym.errors.validation_errors import ValidationError
__all__ = [
"ValidationError",
"BenchmarkInitError",
"ServiceError",
"SessionNotFound",
"ServiceOSError",
"ServiceInitError",
"EnvironmentNotSupported",
"ServiceTransportError",
"ServiceIsClosed",
"DownloadFailed",
"TooManyRequests",
"DatasetInitError",
]
|
CompilerGym-development
|
compiler_gym/errors/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines service related errors."""
class ServiceError(Exception):
"""Error raised from the service."""
class SessionNotFound(ServiceError):
"""Requested session ID not found in service."""
class ServiceOSError(ServiceError, OSError):
"""System error raised from the service."""
class ServiceInitError(ServiceError, OSError):
"""Error raised if the service fails to initialize."""
class EnvironmentNotSupported(ServiceInitError):
"""Error raised if the runtime requirements for an environment are not
met on the current system."""
class ServiceTransportError(ServiceError, OSError):
"""Error that is raised if communication with the service fails."""
class ServiceIsClosed(ServiceError, TypeError):
"""Error that is raised if trying to interact with a closed service."""
|
CompilerGym-development
|
compiler_gym/errors/service_errors.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class DownloadFailed(IOError):
"""Error thrown if a download fails."""
class TooManyRequests(DownloadFailed):
"""Error thrown by HTTP 429 response."""
|
CompilerGym-development
|
compiler_gym/errors/download_errors.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class BenchmarkInitError(OSError, ValueError):
"""Base class for errors raised if a benchmark fails to initialize."""
class DatasetInitError(OSError):
"""Base class for errors raised if a dataset fails to initialize."""
|
CompilerGym-development
|
compiler_gym/errors/dataset_errors.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Contains an implementation of the :class:`CompilerEnv<compiler_gym.envs.CompilerEnv>`
interface as a gRPC client service."""
import logging
import numbers
import warnings
from collections.abc import Iterable as IterableType
from copy import deepcopy
from math import isclose
from pathlib import Path
from time import time
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
from gym.spaces import Space
from compiler_gym.compiler_env_state import CompilerEnvState
from compiler_gym.datasets import Benchmark, Dataset, Datasets
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.compiler_env import CompilerEnv
from compiler_gym.errors import (
ServiceError,
ServiceIsClosed,
ServiceOSError,
ServiceTransportError,
SessionNotFound,
ValidationError,
)
from compiler_gym.service import CompilerGymServiceConnection, ConnectionOpts
from compiler_gym.service.proto import ActionSpace as ActionSpaceProto
from compiler_gym.service.proto import AddBenchmarkRequest
from compiler_gym.service.proto import Benchmark as BenchmarkProto
from compiler_gym.service.proto import (
EndSessionReply,
EndSessionRequest,
Event,
ForkSessionReply,
ForkSessionRequest,
GetVersionReply,
GetVersionRequest,
SendSessionParameterReply,
SendSessionParameterRequest,
SessionParameter,
StartSessionRequest,
StepReply,
StepRequest,
py_converters,
)
from compiler_gym.spaces import ActionSpace, DefaultRewardFromObservation, Reward
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.gym_type_hints import (
ActionType,
ObservationType,
OptionalArgumentValue,
RewardType,
StepType,
)
from compiler_gym.util.shell_format import plural
from compiler_gym.util.timer import Timer
from compiler_gym.validation_result import ValidationResult
from compiler_gym.views import ObservationSpaceSpec, ObservationView, RewardView
logger = logging.getLogger(__name__)
def _wrapped_step(
service: CompilerGymServiceConnection, request: StepRequest, timeout: float
) -> StepReply:
"""Call the Step() RPC endpoint."""
try:
return service(service.stub.Step, request, timeout=timeout)
except FileNotFoundError as e:
if str(e).startswith("Session not found"):
raise SessionNotFound(str(e))
raise
class ServiceMessageConverters:
"""Allows for customization of conversion to/from gRPC messages for the
:class:`ClientServiceCompilerEnv
<compiler_gym.service.client_service_compiler_env.ClientServiceCompilerEnv>`.
Supports conversion customizations:
- :code:`compiler_gym.service.proto.ActionSpace` ->
:code:`gym.spaces.Space`.
- :code:`compiler_gym.util.gym_type_hints.ActionType` ->
:code:`compiler_gym.service.proto.Event`.
"""
action_space_converter: Callable[[ActionSpaceProto], ActionSpace]
action_converter: Callable[[ActionType], Event]
def __init__(
self,
action_space_converter: Optional[
Callable[[ActionSpaceProto], ActionSpace]
] = None,
action_converter: Optional[Callable[[Any], Event]] = None,
):
"""Constructor."""
self.action_space_converter = (
py_converters.make_action_space_wrapper(
py_converters.make_message_default_converter()
)
if action_space_converter is None
else action_space_converter
)
self.action_converter = (
py_converters.to_event_message_default_converter()
if action_converter is None
else action_converter
)
class ClientServiceCompilerEnv(CompilerEnv):
"""Implementation of :class:`CompilerEnv <compiler_gym.envs.CompilerEnv>`
using gRPC for client-server communication.
:ivar service: A connection to the underlying compiler service.
:vartype service: compiler_gym.service.CompilerGymServiceConnection
"""
def __init__(
self,
service: Union[str, Path],
rewards: Optional[List[Reward]] = None,
datasets: Optional[Iterable[Dataset]] = None,
benchmark: Optional[Union[str, Benchmark]] = None,
observation_space: Optional[Union[str, ObservationSpaceSpec]] = None,
reward_space: Optional[Union[str, Reward]] = None,
action_space: Optional[str] = None,
derived_observation_spaces: Optional[List[Dict[str, Any]]] = None,
service_message_converters: ServiceMessageConverters = None,
connection_settings: Optional[ConnectionOpts] = None,
service_connection: Optional[CompilerGymServiceConnection] = None,
):
"""Construct and initialize a CompilerGym environment.
In normal use you should use :code:`gym.make(...)` rather than calling
the constructor directly.
:param service: The hostname and port of a service that implements the
CompilerGym service interface, or the path of a binary file which
provides the CompilerGym service interface when executed. See
:doc:`/compiler_gym/service` for details.
:param rewards: The reward spaces that this environment supports.
Rewards are typically calculated based on observations generated by
the service. See :class:`Reward <compiler_gym.spaces.Reward>` for
details.
:param benchmark: The benchmark to use for this environment. Either a
URI string, or a :class:`Benchmark
<compiler_gym.datasets.Benchmark>` instance. If not provided, the
first benchmark as returned by
:code:`next(env.datasets.benchmarks())` will be used as the default.
:param observation_space: Compute and return observations at each
:func:`step()` from this space. Accepts a string name or an
:class:`ObservationSpaceSpec
<compiler_gym.views.ObservationSpaceSpec>`. If not provided,
:func:`step()` returns :code:`None` for the observation value. Can
be set later using :meth:`env.observation_space
<compiler_gym.envs.ClientServiceCompilerEnv.observation_space>`. For available
spaces, see :class:`env.observation.spaces
<compiler_gym.views.ObservationView>`.
:param reward_space: Compute and return reward at each :func:`step()`
from this space. Accepts a string name or a :class:`Reward
<compiler_gym.spaces.Reward>`. If not provided, :func:`step()`
returns :code:`None` for the reward value. Can be set later using
:meth:`env.reward_space
<compiler_gym.envs.ClientServiceCompilerEnv.reward_space>`. For available spaces,
see :class:`env.reward.spaces <compiler_gym.views.RewardView>`.
:param action_space: The name of the action space to use. If not
specified, the default action space for this compiler is used.
:param derived_observation_spaces: An optional list of arguments to be
passed to :meth:`env.observation.add_derived_space()
<compiler_gym.views.observation.Observation.add_derived_space>`.
:param service_message_converters: Custom converters for action spaces and actions.
:param connection_settings: The settings used to establish a connection
with the remote service.
:param service_connection: An existing compiler gym service connection
to use.
:raises FileNotFoundError: If service is a path to a file that is not
found.
:raises TimeoutError: If the compiler service fails to initialize within
the parameters provided in :code:`connection_settings`.
"""
self.metadata = {"render.modes": ["human", "ansi"]}
# A compiler service supports multiple simultaneous environments. This
# session ID is used to identify this environment.
self._session_id: Optional[int] = None
self._service_endpoint: Union[str, Path] = service
self._connection_settings = connection_settings or ConnectionOpts()
self._params_to_send_on_reset: List[SessionParameter] = []
self.service = service_connection or CompilerGymServiceConnection(
endpoint=self._service_endpoint,
opts=self._connection_settings,
)
self._datasets = Datasets(datasets or [])
self.action_space_name = action_space
# If no reward space is specified, generate some from numeric observation spaces
rewards = rewards or [
DefaultRewardFromObservation(obs.name)
for obs in self.service.observation_spaces
if obs.default_observation.WhichOneof("value")
and isinstance(
getattr(
obs.default_observation, obs.default_observation.WhichOneof("value")
),
numbers.Number,
)
]
# The benchmark that is currently being used, and the benchmark that
# will be used on the next call to reset(). These are equal except in
# the gap between the user setting the env.benchmark property while in
# an episode and the next call to env.reset().
self._benchmark_in_use: Optional[Benchmark] = None
self._benchmark_in_use_proto: BenchmarkProto = BenchmarkProto()
self._next_benchmark: Optional[Benchmark] = None
# Normally when the benchmark is changed the updated value is not
# reflected until the next call to reset(). We make an exception for the
# constructor-time benchmark as otherwise the behavior of the benchmark
# property is counter-intuitive:
#
# >>> env = gym.make("example-compiler-v0", benchmark="foo")
# >>> env.benchmark
# None
# >>> env.reset()
# >>> env.benchmark
# "foo"
#
# By forcing the _benchmark_in_use URI at constructor time, the first
# env.benchmark above returns the benchmark as expected.
try:
self.benchmark = benchmark or next(self.datasets.benchmarks())
self._benchmark_in_use = self._next_benchmark
except StopIteration:
# StopIteration raised on next(self.datasets.benchmarks()) if there
# are no benchmarks available. This is to allow ClientServiceCompilerEnv to be
# used without any datasets by setting a benchmark before/during the
# first reset() call.
pass
self.service_message_converters = (
ServiceMessageConverters()
if service_message_converters is None
else service_message_converters
)
# Process the available action, observation, and reward spaces.
self.action_spaces = [
self.service_message_converters.action_space_converter(space)
for space in self.service.action_spaces
]
self.observation = self._observation_view_type(
raw_step=self.raw_step,
spaces=self.service.observation_spaces,
)
self.reward = self._reward_view_type(rewards, self.observation)
# Register any derived observation spaces now so that the observation
# space can be set below.
for derived_observation_space in derived_observation_spaces or []:
self.observation.add_derived_space(**derived_observation_space)
self.action_space: Optional[Space] = None
self.observation_space: Optional[Space] = None
# Mutable state initialized in reset().
self._reward_range: Tuple[float, float] = (-np.inf, np.inf)
self.episode_reward = None
self.episode_start_time: float = time()
self._actions: List[ActionType] = []
# Initialize the default observation/reward spaces.
self.observation_space_spec = None
self.reward_space_spec = None
self.observation_space = observation_space
self.reward_space = reward_space
@property
def observation_space_spec(self) -> ObservationSpaceSpec:
return self._observation_space_spec
@observation_space_spec.setter
def observation_space_spec(
self, observation_space_spec: Optional[ObservationSpaceSpec]
):
self._observation_space_spec = observation_space_spec
@property
def observation(self) -> ObservationView:
return self._observation
@observation.setter
def observation(self, observation: ObservationView) -> None:
self._observation = observation
@property
def reward_space_spec(self) -> Optional[Reward]:
return self._reward_space_spec
@reward_space_spec.setter
def reward_space_spec(self, val: Optional[Reward]):
self._reward_space_spec = val
@property
def datasets(self) -> Iterable[Dataset]:
return self._datasets
@datasets.setter
def datasets(self, datasets: Iterable[Dataset]):
self._datastes = datasets
@property
def episode_reward(self) -> Optional[float]:
return self._episode_reward
@episode_reward.setter
def episode_reward(self, episode_reward: Optional[float]):
self._episode_reward = episode_reward
@property
def actions(self) -> List[ActionType]:
return self._actions
@memoized_property
def versions(self) -> GetVersionReply:
"""Get the version numbers from the compiler service."""
return self.service(self.service.stub.GetVersion, GetVersionRequest())
@property
def version(self) -> str:
"""The version string of the compiler service."""
return self.versions.service_version
@property
def compiler_version(self) -> str:
"""The version string of the underlying compiler that this service supports."""
return self.versions.compiler_version
@property
def episode_walltime(self) -> float:
return time() - self.episode_start_time
@property
def state(self) -> CompilerEnvState:
return CompilerEnvState(
benchmark=str(self.benchmark) if self.benchmark else None,
reward=self.episode_reward,
walltime=self.episode_walltime,
commandline=self.action_space.to_string(self.actions),
)
@property
def action_space(self) -> ActionSpace:
return self._action_space
@action_space.setter
def action_space(self, action_space: Optional[str]) -> None:
self.action_space_name = action_space
index = (
[a.name for a in self.action_spaces].index(action_space)
if self.action_space_name
else 0
)
self._action_space: ActionSpace = self.action_spaces[index]
@property
def action_spaces(self) -> List[str]:
return self._action_spaces
@action_spaces.setter
def action_spaces(self, action_spaces: List[str]):
self._action_spaces = action_spaces
@property
def benchmark(self) -> Benchmark:
return self._benchmark_in_use
@benchmark.setter
def benchmark(self, benchmark: Union[str, Benchmark, BenchmarkUri]):
if self.in_episode:
warnings.warn(
"Changing the benchmark has no effect until reset() is called"
)
if isinstance(benchmark, str):
benchmark_object = self.datasets.benchmark(benchmark)
logger.debug("Setting benchmark by name: %s", benchmark_object)
self._next_benchmark = benchmark_object
elif isinstance(benchmark, Benchmark):
logger.debug("Setting benchmark: %s", benchmark.uri)
self._next_benchmark = benchmark
elif isinstance(benchmark, BenchmarkUri):
benchmark_object = self.datasets.benchmark_from_parsed_uri(benchmark)
logger.debug("Setting benchmark by name: %s", benchmark_object)
self._next_benchmark = benchmark_object
else:
raise TypeError(
f"Expected a Benchmark or str, received: '{type(benchmark).__name__}'"
)
@property
def reward_space(self) -> Optional[Reward]:
return self.reward_space_spec
@reward_space.setter
def reward_space(self, reward_space: Optional[Union[str, Reward]]) -> None:
# Coerce the observation space into a string.
reward_space: Optional[str] = (
reward_space.name if isinstance(reward_space, Reward) else reward_space
)
if reward_space:
if reward_space not in self.reward.spaces:
raise LookupError(f"Reward space not found: {reward_space}")
# The reward space remains unchanged, nothing to do.
if reward_space == self.reward_space:
return
self.reward_space_spec = self.reward.spaces[reward_space]
self._reward_range = (
self.reward_space_spec.min,
self.reward_space_spec.max,
)
# Reset any cumulative rewards, if we're in an episode.
if self.in_episode:
self.episode_reward = 0
else:
# If no reward space is being used then set the reward range to
# unbounded.
self.reward_space_spec = None
self._reward_range = (-np.inf, np.inf)
@property
def reward_range(self) -> Tuple[float, float]:
return self._reward_range
@property
def reward(self) -> RewardView:
return self._reward
@reward.setter
def reward(self, reward: RewardView) -> None:
self._reward = reward
@property
def in_episode(self) -> bool:
return self._session_id is not None
@property
def observation_space(self) -> Optional[Space]:
if self.observation_space_spec:
return self.observation_space_spec.space
@observation_space.setter
def observation_space(
self, observation_space: Optional[Union[str, ObservationSpaceSpec]]
) -> None:
# Coerce the observation space into a string.
observation_space: Optional[str] = (
observation_space.id
if isinstance(observation_space, ObservationSpaceSpec)
else observation_space
)
if observation_space:
if observation_space not in self.observation.spaces:
raise LookupError(f"Observation space not found: {observation_space}")
self.observation_space_spec = self.observation.spaces[observation_space]
else:
self.observation_space_spec = None
def _init_kwargs(self) -> Dict[str, Any]:
"""Retturn a dictionary of keyword arguments used to initialize the
environment.
"""
return {
"action_space": self.action_space,
"benchmark": self.benchmark,
"connection_settings": self._connection_settings,
"service": self._service_endpoint,
}
def fork(self) -> "ClientServiceCompilerEnv":
if not self.in_episode:
actions = self.actions.copy()
self.reset()
if actions:
logger.warning("Parent service of fork() has died, replaying state")
_, _, done, _ = self.multistep(actions)
assert not done, "Failed to replay action sequence"
request = ForkSessionRequest(session_id=self._session_id)
try:
reply: ForkSessionReply = self.service(
self.service.stub.ForkSession, request
)
# Create a new environment that shares the connection.
new_env = type(self)(**self._init_kwargs(), service_connection=self.service)
# Set the session ID.
new_env._session_id = reply.session_id # pylint: disable=protected-access
new_env.observation.session_id = reply.session_id
# Now that we have initialized the environment with the current
# state, set the benchmark so that calls to new_env.reset() will
# correctly revert the environment to the initial benchmark state.
#
# pylint: disable=protected-access
new_env._next_benchmark = self._benchmark_in_use
# Set the "visible" name of the current benchmark to hide the fact
# that we loaded from a custom benchmark file.
new_env._benchmark_in_use = self._benchmark_in_use
except NotImplementedError:
# Fallback implementation. If the compiler service does not support
# the Fork() operator then we create a new independent environment
# and apply the sequence of actions in the current environment to
# replay the state.
new_env = type(self)(**self._init_kwargs())
new_env.reset()
_, _, done, _ = new_env.multistep(self.actions)
assert not done, "Failed to replay action sequence in forked environment"
# Create copies of the mutable reward and observation spaces. This
# is required to correctly calculate incremental updates.
new_env.reward.spaces = deepcopy(self.reward.spaces)
new_env.observation.spaces = deepcopy(self.observation.spaces)
# Set the default observation and reward types. Note the use of IDs here
# to prevent passing the spaces by reference.
if self.observation_space:
new_env.observation_space = self.observation_space_spec.id
if self.reward_space:
new_env.reward_space = self.reward_space.name
# Copy over the mutable episode state.
new_env.episode_reward = self.episode_reward
new_env.episode_start_time = self.episode_start_time
new_env._actions = self.actions.copy()
return new_env
def close(self):
# Try and close out the episode, but errors are okay.
close_service = True
if self.in_episode:
try:
reply: EndSessionReply = self.service(
self.service.stub.EndSession,
EndSessionRequest(session_id=self._session_id),
)
# The service still has other sessions attached so we should
# not kill it.
if reply.remaining_sessions:
close_service = False
except ServiceIsClosed:
# This error can be safely ignored as it means that the service
# is already offline.
pass
except Exception as e:
logger.warning(
"Failed to end active compiler session on close(): %s (%s)",
e,
type(e).__name__,
)
self._session_id = None
if self.service and close_service:
self.service.close()
self.service = None
def __del__(self):
# Don't let the service be orphaned if user forgot to close(), or
# if an exception was thrown. The conditional guard is because this
# may be called in case of early error.
if hasattr(self, "service") and getattr(self, "service"):
self.close()
def reset(
self,
benchmark: Optional[Union[str, Benchmark]] = None,
action_space: Optional[str] = None,
reward_space: Union[
OptionalArgumentValue, str, Reward
] = OptionalArgumentValue.UNCHANGED,
observation_space: Union[
OptionalArgumentValue, str, ObservationSpaceSpec
] = OptionalArgumentValue.UNCHANGED,
timeout: float = 300,
) -> Optional[ObservationType]:
return self._reset(
benchmark=benchmark,
action_space=action_space,
observation_space=observation_space,
reward_space=reward_space,
timeout=timeout,
retry_count=0,
)
def _reset( # pylint: disable=arguments-differ
self,
benchmark: Optional[Union[str, Benchmark]],
action_space: Optional[str],
observation_space: Union[OptionalArgumentValue, str, ObservationSpaceSpec],
reward_space: Union[OptionalArgumentValue, str, Reward],
timeout: float,
retry_count: int,
) -> Optional[ObservationType]:
"""Private implementation detail. Call `reset()`, not this."""
if observation_space != OptionalArgumentValue.UNCHANGED:
self.observation_space = observation_space
if reward_space != OptionalArgumentValue.UNCHANGED:
self.reward_space = reward_space
def _retry(error) -> Optional[ObservationType]:
"""Abort and retry on error."""
# Log the error that we are recovering from, but treat
# ServiceIsClosed errors as unimportant since we know what causes
# them.
log_severity = (
logger.debug if isinstance(error, ServiceIsClosed) else logger.warning
)
log_severity("%s during reset(): %s", type(error).__name__, error)
if self.service:
try:
self.service.close()
except ServiceError as e:
# close() can raise ServiceError if the service exists with
# a non-zero return code. We swallow the error here as we
# are about to retry.
logger.debug(
"Ignoring service error during reset() attempt: %s (%s)",
e,
type(e).__name__,
)
self.service = None
if retry_count >= self._connection_settings.init_max_attempts:
raise OSError(
"Failed to reset environment using benchmark "
f"{self.benchmark} after {retry_count - 1} attempts.\n"
f"Last error ({type(error).__name__}): {error}"
) from error
else:
return self._reset(
benchmark=benchmark,
action_space=action_space,
observation_space=observation_space,
reward_space=reward_space,
timeout=timeout,
retry_count=retry_count + 1,
)
def _call_with_error(
stub_method, *args, **kwargs
) -> Tuple[Optional[Exception], Optional[Any]]:
"""Call the given stub method. And return an <error, return> tuple."""
try:
return None, self.service(stub_method, *args, **kwargs)
except (ServiceError, ServiceTransportError, TimeoutError) as e:
return e, None
if not self._next_benchmark:
raise TypeError(
"No benchmark set. Set a benchmark using "
"`env.reset(benchmark=benchmark)`. Use `env.datasets` to "
"access the available benchmarks."
)
# Start a new service if required.
if self.service is None:
self.service = CompilerGymServiceConnection(
self._service_endpoint, self._connection_settings
)
self.action_space_name = action_space or self.action_space_name
# Stop an existing episode.
if self.in_episode:
logger.debug("Ending session %d", self._session_id)
error, _ = _call_with_error(
self.service.stub.EndSession,
EndSessionRequest(session_id=self._session_id),
)
if error:
logger.warning(
"Failed to stop session %d with %s: %s",
self._session_id,
type(error).__name__,
error,
)
self._session_id = None
# Update the user requested benchmark, if provided.
if benchmark:
self.benchmark = benchmark
self._benchmark_in_use = self._next_benchmark
# When always_send_benchmark_on_reset option is enabled, the entire
# benchmark program is sent with every StartEpisode request. Otherwise
# only the URI of the benchmark is sent. In cases where benchmarks are
# reused between calls to reset(), sending the URI is more efficient as
# the service can cache the benchmark. In cases where reset() is always
# called with a different benchmark, this causes unnecessary roundtrips
# as every StartEpisodeRequest receives a FileNotFound response.
if self.service.opts.always_send_benchmark_on_reset:
self._benchmark_in_use_proto = self._benchmark_in_use.proto
else:
self._benchmark_in_use_proto.uri = str(self._benchmark_in_use.uri)
start_session_request = StartSessionRequest(
benchmark=self._benchmark_in_use_proto,
action_space=(
[a.name for a in self.action_spaces].index(self.action_space_name)
if self.action_space_name
else 0
),
observation_space=(
[self.observation_space_spec.index] if self.observation_space else None
),
)
try:
error, reply = _call_with_error(
self.service.stub.StartSession, start_session_request
)
if error:
return _retry(error)
except FileNotFoundError:
# The benchmark was not found, so try adding it and then repeating
# the request.
error, _ = _call_with_error(
self.service.stub.AddBenchmark,
AddBenchmarkRequest(benchmark=[self._benchmark_in_use.proto]),
)
if error:
return _retry(error)
error, reply = _call_with_error(
self.service.stub.StartSession, start_session_request
)
if error:
return _retry(error)
self._session_id = reply.session_id
self.observation.session_id = reply.session_id
self.reward.get_cost = self.observation.__getitem__
self.episode_start_time = time()
self._actions = []
# If the action space has changed, update it.
if reply.HasField("new_action_space"):
self._action_space = self.service_message_converters.action_space_converter(
reply.new_action_space
)
# Re-send any session parameters that we marked as needing to be
# re-sent on reset(). Do this before any other initialization as they
# may affect the behavior of subsequent service calls.
if self._params_to_send_on_reset:
self.send_params(*[(p.key, p.value) for p in self._params_to_send_on_reset])
self.reward.reset(benchmark=self.benchmark, observation_view=self.observation)
if self.reward_space:
self.episode_reward = 0.0
if self.observation_space:
if len(reply.observation) != 1:
raise OSError(
f"Expected one observation from service, received {len(reply.observation)}"
)
return self.observation.spaces[self.observation_space_spec.id].translate(
reply.observation[0]
)
def raw_step(
self,
actions: Iterable[ActionType],
observation_spaces: List[ObservationSpaceSpec],
reward_spaces: List[Reward],
timeout: float = 300,
) -> StepType:
"""Take a step.
:param actions: A list of actions to be applied.
:param observations: A list of observations spaces to compute
observations from. These are evaluated after the actions are
applied.
:param rewards: A list of reward spaces to compute rewards from. These
are evaluated after the actions are applied.
:return: A tuple of observations, rewards, done, and info. Observations
and rewards are lists.
:raises SessionNotFound: If :meth:`reset()
<compiler_gym.envs.ClientServiceCompilerEnv.reset>` has not been called.
.. warning::
Don't call this method directly, use :meth:`step()
<compiler_gym.envs.ClientServiceCompilerEnv.step>` or :meth:`multistep()
<compiler_gym.envs.ClientServiceCompilerEnv.multistep>` instead. The
:meth:`raw_step() <compiler_gym.envs.ClientServiceCompilerEnv.step>` method is an
implementation detail.
"""
if not self.in_episode:
raise SessionNotFound("Must call reset() before step()")
reward_observation_spaces: List[ObservationSpaceSpec] = []
for reward_space in reward_spaces:
reward_observation_spaces += [
self.observation.spaces[obs] for obs in reward_space.observation_spaces
]
observations_to_compute: List[ObservationSpaceSpec] = list(
set(observation_spaces).union(set(reward_observation_spaces))
)
observation_space_index_map: Dict[ObservationSpaceSpec, int] = {
observation_space: i
for i, observation_space in enumerate(observations_to_compute)
}
# Record the actions.
self._actions += actions
# Send the request to the backend service.
request = StepRequest(
session_id=self._session_id,
action=[
self.service_message_converters.action_converter(a) for a in actions
],
observation_space=[
observation_space.index for observation_space in observations_to_compute
],
)
try:
reply = _wrapped_step(self.service, request, timeout)
except (
ServiceError,
ServiceTransportError,
ServiceOSError,
TimeoutError,
SessionNotFound,
) as e:
# Gracefully handle "expected" error types. These non-fatal errors
# end the current episode and provide some diagnostic information to
# the user through the `info` dict.
info = {
"error_type": type(e).__name__,
"error_details": str(e),
}
try:
self.close()
except ServiceError as e:
# close() can raise ServiceError if the service exists with a
# non-zero return code. We swallow the error here but propagate
# the diagnostic message.
info[
"error_details"
] += f". Additional error during environment closing: {e}"
default_observations = [
observation_space.default_value
for observation_space in observation_spaces
]
default_rewards = [
float(reward_space.reward_on_error(self.episode_reward))
for reward_space in reward_spaces
]
return default_observations, default_rewards, True, info
# If the action space has changed, update it.
if reply.HasField("new_action_space"):
self._action_space = self.service_message_converters.action_space_converter(
reply.new_action_space
)
# Translate observations to python representations.
if len(reply.observation) != len(observations_to_compute):
raise ServiceError(
f"Requested {len(observations_to_compute)} observations "
f"but received {len(reply.observation)}"
)
computed_observations = [
observation_space.translate(value)
for observation_space, value in zip(
observations_to_compute, reply.observation
)
]
# Get the user-requested observation.
observations: List[ObservationType] = [
computed_observations[observation_space_index_map[observation_space]]
for observation_space in observation_spaces
]
# Update and compute the rewards.
rewards: List[RewardType] = []
for reward_space in reward_spaces:
reward_observations = [
computed_observations[
observation_space_index_map[
self.observation.spaces[observation_space]
]
]
for observation_space in reward_space.observation_spaces
]
rewards.append(
float(
reward_space.update(actions, reward_observations, self.observation)
)
)
info = {
"action_had_no_effect": reply.action_had_no_effect,
"new_action_space": reply.HasField("new_action_space"),
}
return observations, rewards, reply.end_of_session, info
def step(
self,
action: ActionType,
observation_spaces: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
reward_spaces: Optional[Iterable[Union[str, Reward]]] = None,
observations: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
rewards: Optional[Iterable[Union[str, Reward]]] = None,
timeout: float = 300,
) -> StepType:
""":raises SessionNotFound: If :meth:`reset()
<compiler_gym.envs.ClientServiceCompilerEnv.reset>` has not been called.
"""
if isinstance(action, IterableType):
warnings.warn(
"Argument `action` of ClientServiceCompilerEnv.step no longer accepts a list "
" of actions. Please use ClientServiceCompilerEnv.multistep instead",
category=DeprecationWarning,
)
return self.multistep(
action,
observation_spaces=observation_spaces,
reward_spaces=reward_spaces,
observations=observations,
rewards=rewards,
)
if observations is not None:
warnings.warn(
"Argument `observations` of ClientServiceCompilerEnv.step has been "
"renamed `observation_spaces`. Please update your code",
category=DeprecationWarning,
)
observation_spaces = observations
if rewards is not None:
warnings.warn(
"Argument `rewards` of ClientServiceCompilerEnv.step has been renamed "
"`reward_spaces`. Please update your code",
category=DeprecationWarning,
)
reward_spaces = rewards
return self.multistep(
actions=[action],
observation_spaces=observation_spaces,
reward_spaces=reward_spaces,
timeout=timeout,
)
def multistep(
self,
actions: Iterable[ActionType],
observation_spaces: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
reward_spaces: Optional[Iterable[Union[str, Reward]]] = None,
observations: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
rewards: Optional[Iterable[Union[str, Reward]]] = None,
timeout: float = 300,
):
""":raises SessionNotFound: If :meth:`reset()
<compiler_gym.envs.ClientServiceCompilerEnv.reset>` has not been called.
"""
if observations is not None:
warnings.warn(
"Argument `observations` of ClientServiceCompilerEnv.multistep has been "
"renamed `observation_spaces`. Please update your code",
category=DeprecationWarning,
)
observation_spaces = observations
if rewards is not None:
warnings.warn(
"Argument `rewards` of ClientServiceCompilerEnv.multistep has been renamed "
"`reward_spaces`. Please update your code",
category=DeprecationWarning,
)
reward_spaces = rewards
# Coerce observation spaces into a list of ObservationSpaceSpec instances.
if observation_spaces:
observation_spaces_to_compute: List[ObservationSpaceSpec] = [
obs
if isinstance(obs, ObservationSpaceSpec)
else self.observation.spaces[obs]
for obs in observation_spaces
]
elif self.observation_space_spec:
observation_spaces_to_compute: List[ObservationSpaceSpec] = [
self.observation_space_spec
]
else:
observation_spaces_to_compute: List[ObservationSpaceSpec] = []
# Coerce reward spaces into a list of Reward instances.
if reward_spaces:
reward_spaces_to_compute: List[Reward] = [
rew if isinstance(rew, Reward) else self.reward.spaces[rew]
for rew in reward_spaces
]
elif self.reward_space:
reward_spaces_to_compute: List[Reward] = [self.reward_space]
else:
reward_spaces_to_compute: List[Reward] = []
# Perform the underlying environment step.
observation_values, reward_values, done, info = self.raw_step(
actions,
observation_spaces_to_compute,
reward_spaces_to_compute,
timeout=timeout,
)
# Translate observations lists back to the appropriate types.
if observation_spaces is None and self.observation_space_spec:
observation_values = observation_values[0]
elif not observation_spaces_to_compute:
observation_values = None
# Translate reward lists back to the appropriate types.
if reward_spaces is None and self.reward_space:
reward_values = reward_values[0]
# Update the cumulative episode reward
self.episode_reward += reward_values
elif not reward_spaces_to_compute:
reward_values = None
return observation_values, reward_values, done, info
def render(
self,
mode="human",
) -> Optional[str]:
"""Render the environment.
ClientServiceCompilerEnv instances support two render modes: "human", which prints
the current environment state to the terminal and return nothing; and
"ansi", which returns a string representation of the current environment
state.
:param mode: The render mode to use.
:raises TypeError: If a default observation space is not set, or if the
requested render mode does not exist.
"""
if not self.observation_space:
raise ValueError("Cannot call render() when no observation space is used")
observation = self.observation[self.observation_space_spec.id]
if mode == "human":
print(observation)
elif mode == "ansi":
return str(observation)
else:
raise ValueError(f"Invalid mode: {mode}")
@property
def _observation_view_type(self):
"""Returns the type for observation views.
Subclasses may override this to extend the default observation view.
"""
return ObservationView
@property
def _reward_view_type(self):
"""Returns the type for reward views.
Subclasses may override this to extend the default reward view.
"""
return RewardView
def apply(self, state: CompilerEnvState) -> None: # noqa
if not self.in_episode:
self.reset(benchmark=state.benchmark)
# TODO(cummins): Does this behavior make sense? Take, for example:
#
# >>> env.apply(state)
# >>> env.benchmark == state.benchmark
# False
#
# I think most users would reasonable expect `env.apply(state)` to fully
# apply the state, not just the sequence of actions. And what about the
# choice of observation space, reward space, etc?
if self.benchmark != state.benchmark:
warnings.warn(
f"Applying state from environment for benchmark '{state.benchmark}' "
f"to environment for benchmark '{self.benchmark}'"
)
actions = self.action_space.from_string(state.commandline)
done = False
for action in actions:
_, _, done, info = self.step(action)
if done:
raise ValueError(
f"Environment terminated with error: `{info.get('error_details')}`"
)
def validate(self, state: Optional[CompilerEnvState] = None) -> ValidationResult:
if state:
self.reset(benchmark=state.benchmark)
in_place = False
benchmark: str = state.benchmark
else:
state = self.state
in_place = True
# Record the actual benchmark object to accommodate custom
# benchmarks.
benchmark: Benchmark = self.benchmark
assert self.in_episode
errors: ValidationError = []
validation = {
"state": state,
"actions_replay_failed": False,
"reward_validated": False,
"reward_validation_failed": False,
"benchmark_semantics_validated": False,
"benchmark_semantics_validation_failed": False,
}
fkd = self.fork()
try:
with Timer() as walltime:
replay_target = self if in_place else fkd
replay_target.reset(benchmark=benchmark)
# Use a while loop here so that we can `break` early out of the
# validation process in case a step fails.
while True:
try:
replay_target.apply(state)
except (ValueError, OSError) as e:
validation["actions_replay_failed"] = True
errors.append(
ValidationError(
type="Action replay failed",
data={
"exception": str(e),
"exception_type": type(e).__name__,
},
)
)
break
if state.reward is not None and self.reward_space is None:
warnings.warn(
"Validating state with reward, but "
"environment has no reward space set"
)
elif (
state.reward is not None
and self.reward_space
and self.reward_space.deterministic
):
validation["reward_validated"] = True
# If reward deviates from the expected amount record the
# error but continue with the remainder of the validation.
if not isclose(
state.reward,
replay_target.episode_reward,
rel_tol=1e-5,
abs_tol=1e-10,
):
validation["reward_validation_failed"] = True
errors.append(
ValidationError(
type=(
f"Expected reward {state.reward} but "
f"received reward {replay_target.episode_reward}"
),
data={
"expected_reward": state.reward,
"actual_reward": replay_target.episode_reward,
},
)
)
benchmark = replay_target.benchmark
if benchmark.is_validatable():
validation["benchmark_semantics_validated"] = True
semantics_errors = benchmark.validate(replay_target)
if semantics_errors:
validation["benchmark_semantics_validation_failed"] = True
errors += semantics_errors
# Finished all checks, break the loop.
break
finally:
fkd.close()
return ValidationResult.construct(
walltime=walltime.time,
errors=errors,
**validation,
)
def send_param(self, key: str, value: str, resend_on_reset: bool = False) -> str:
"""Send a single <key, value> parameter to the compiler service.
See :meth:`send_params() <compiler_gym.envs.ClientServiceCompilerEnv.send_params>`
for more information.
:param key: The parameter key.
:param value: The parameter value.
:param resend_on_reset: Whether to resend this parameter to the compiler
service on :code:`reset()`.
:return: The response from the compiler service.
:raises SessionNotFound: If called before :meth:`reset()
<compiler_gym.envs.ClientServiceCompilerEnv.reset>`.
"""
return self.send_params((key, value), resend_on_reset=resend_on_reset)[0]
def send_params(
self, *params: Iterable[Tuple[str, str]], resend_on_reset: bool = False
) -> List[str]:
"""Send a list of <key, value> parameters to the compiler service.
This provides a mechanism to send messages to the backend compilation
session in a way that doesn't conform to the normal communication
pattern. This can be useful for things like configuring runtime
debugging settings, or applying "meta actions" to the compiler that are
not exposed in the compiler's action space. Consult the documentation
for a specific compiler service to see what parameters, if any, are
supported.
Must have called :meth:`reset() <compiler_gym.envs.ClientServiceCompilerEnv.reset>`
first.
:param params: A list of parameters, where each parameter is a
:code:`(key, value)` tuple.
:param resend_on_reset: Whether to resend this parameter to the compiler
service on :code:`reset()`.
:return: A list of string responses, one per parameter.
:raises SessionNotFound: If called before :meth:`reset()
<compiler_gym.envs.ClientServiceCompilerEnv.reset>`.
"""
params_to_send = [SessionParameter(key=k, value=v) for (k, v) in params]
if resend_on_reset:
self._params_to_send_on_reset += params_to_send
if not self.in_episode:
raise SessionNotFound("Must call reset() before send_params()")
request = SendSessionParameterRequest(
session_id=self._session_id,
parameter=params_to_send,
)
reply: SendSessionParameterReply = self.service(
self.service.stub.SendSessionParameter, request
)
if len(params) != len(reply.reply):
raise OSError(
f"Sent {len(params)} {plural(len(params), 'parameter', 'parameters')} but received "
f"{len(reply.reply)} {plural(len(reply.reply), 'response', 'responses')} from the "
"service"
)
return list(reply.reply)
def __copy__(self) -> "ClientServiceCompilerEnv":
raise TypeError(
"ClientServiceCompilerEnv instances do not support shallow copies. Use deepcopy()"
)
def __deepcopy__(self, memo) -> "ClientServiceCompilerEnv":
del memo # unused
return self.fork()
|
CompilerGym-development
|
compiler_gym/service/client_service_compiler_env.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compiler_gym.service.compilation_session import CompilationSession
from compiler_gym.service.connection import (
CompilerGymServiceConnection,
ConnectionOpts,
EnvironmentNotSupported,
ServiceError,
ServiceInitError,
ServiceIsClosed,
ServiceOSError,
ServiceTransportError,
SessionNotFound,
)
__all__ = [
"CompilerGymServiceConnection",
"CompilationSession",
"ConnectionOpts",
"EnvironmentNotSupported",
"ServiceError",
"ServiceInitError",
"ServiceIsClosed",
"ServiceOSError",
"ServiceTransportError",
"SessionNotFound",
]
|
CompilerGym-development
|
compiler_gym/service/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains the logic for connecting to services."""
import logging
import os
import subprocess
import sys
from pathlib import Path
from signal import Signals
from time import sleep, time
from typing import Dict, Iterable, List, Optional, TypeVar, Union
import grpc
from deprecated.sphinx import deprecated
from pydantic import BaseModel
import compiler_gym.errors
from compiler_gym.service.proto import (
ActionSpace,
CompilerGymServiceStub,
GetSpacesReply,
GetSpacesRequest,
ObservationSpace,
)
from compiler_gym.service.service_cache import ServiceCache
from compiler_gym.util.debug_util import get_debug_level, logging_level_to_debug_level
from compiler_gym.util.runfiles_path import runfiles_path, site_data_path
from compiler_gym.util.shell_format import join_cmd, plural
from compiler_gym.util.truncate import truncate_lines
GRPC_CHANNEL_OPTIONS = [
# Disable the inbound message length filter to allow for large messages such
# as observations.
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
# Fix for "received initial metadata size exceeds limit"
("grpc.max_metadata_size", 512 * 1024),
# Spurious error UNAVAILABLE "Trying to connect an http1.x server".
# https://putridparrot.com/blog/the-unavailable-trying-to-connect-an-http1-x-server-grpc-error/
("grpc.enable_http_proxy", 0),
# Disable TCP port re-use to mitigate port conflict errors when starting
# many services in parallel. Context:
# https://github.com/facebookresearch/CompilerGym/issues/572
("grpc.so_reuseport", 0),
]
logger = logging.getLogger(__name__)
class ConnectionOpts(BaseModel):
"""The options used to configure a connection to a service."""
rpc_max_retries: int = 5
"""The maximum number of failed attempts to communicate with the RPC service
before raising an error. Retries are made only for communication errors.
Failures from other causes such as error signals raised by the service are
not retried."""
retry_wait_seconds: float = 0.1
"""The number of seconds to wait between successive attempts to communicate
with the RPC service."""
retry_wait_backoff_exponent: float = 1.5
"""The exponential backoff scaling between successive attempts to
communicate with the RPC service."""
init_max_seconds: float = 30
"""The maximum number of seconds to spend attempting to establish a
connection to the service before failing.
"""
init_max_attempts: int = 5
"""The maximum number of attempts to make to establish a connection to the
service before failing.
"""
local_service_port_init_max_seconds: float = 30
"""The maximum number of seconds to wait for a local service to write the port.txt file."""
local_service_exit_max_seconds: float = 30
"""The maximum number of seconds to wait for a local service to terminate on close."""
rpc_init_max_seconds: float = 3
"""The maximum number of seconds to wait for an RPC connection to establish."""
always_send_benchmark_on_reset: bool = False
"""Send the full benchmark program data to the compiler service on ever call
to :meth:`env.reset() <compiler_gym.envs.CompilerEnv.reset>`. This is more
efficient in cases where the majority of calls to
:meth:`env.reset() <compiler_gym.envs.CompilerEnv.reset>` uses a different
benchmark. In case of benchmark re-use, leave this :code:`False`.
"""
script_args: List[str] = []
"""If the service is started from a local script, this set of args is used
on the command line. No effect when used for existing sockets."""
script_env: Dict[str, str] = {}
"""If the service is started from a local script, this set of env vars is
used on the command line. No effect when used for existing sockets."""
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
ServiceError = compiler_gym.errors.ServiceError
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
SessionNotFound = compiler_gym.errors.SessionNotFound
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
ServiceOSError = compiler_gym.errors.ServiceOSError
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
ServiceInitError = compiler_gym.errors.ServiceInitError
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
EnvironmentNotSupported = compiler_gym.errors.EnvironmentNotSupported
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
ServiceTransportError = compiler_gym.errors.ServiceTransportError
# Deprecated since v0.2.4.
# This type is for backwards compatibility that will be removed in a future release.
# Please, use errors from `compiler_gym.errors`.
ServiceIsClosed = compiler_gym.errors.ServiceIsClosed
Request = TypeVar("Request")
Reply = TypeVar("Reply")
if sys.version_info > (3, 8, 0):
from typing import Protocol
class StubMethod(Protocol):
"""Type annotation for an RPC stub method that accepts a request message
and returns a reply.
"""
Request = TypeVar("Request")
Reply = TypeVar("Reply")
def __call__(
self, a: Request, timeout: float
) -> Reply: # pylint: disable=undefined-variable
...
else:
# Legacy support for Python < 3.8.
from typing import Callable
StubMethod = Callable[[Request], Reply]
class Connection:
"""Base class for service connections."""
def __init__(self, channel, url: str):
"""Constructor. Don't instantiate this directly, use the subclasses.
:param channel: The RPC channel to use.
:param url: The URL of the RPC service.
"""
self.channel = channel
self.url = url
self.stub = CompilerGymServiceStub(self.channel)
self.spaces: GetSpacesReply = self(self.stub.GetSpaces, GetSpacesRequest())
def close(self):
self.channel.close()
def __call__(
self,
stub_method: StubMethod,
request: Request,
timeout: float = 60,
max_retries=5,
retry_wait_seconds=0.1,
retry_wait_backoff_exponent=1.5,
) -> Reply:
"""Call the service with the given arguments."""
# pylint: disable=no-member
#
# House keeping note: if you modify the exceptions that this method
# raises, please update the CompilerGymServiceConnection.__call__()
# docstring.
attempt = 0
while True:
try:
return stub_method(request, timeout=timeout)
except ValueError as e:
if str(e) == "Cannot invoke RPC on closed channel!":
raise ServiceIsClosed(
"RPC communication failed because channel is closed"
) from None
raise e
except grpc.RpcError as e:
# We raise "from None" to discard the gRPC stack trace, with the
# remaining stack trace correctly pointing to the CompilerGym
# calling code.
if e.code() == grpc.StatusCode.INVALID_ARGUMENT:
raise ValueError(e.details()) from None
elif e.code() == grpc.StatusCode.UNIMPLEMENTED:
raise NotImplementedError(e.details()) from None
elif e.code() == grpc.StatusCode.NOT_FOUND:
raise FileNotFoundError(e.details()) from None
elif e.code() == grpc.StatusCode.RESOURCE_EXHAUSTED:
raise ServiceOSError(e.details()) from None
elif e.code() == grpc.StatusCode.FAILED_PRECONDITION:
raise TypeError(str(e.details())) from None
elif e.code() == grpc.StatusCode.UNAVAILABLE:
# For "unavailable" errors we retry with exponential
# backoff. This is because this error can be caused by an
# overloaded service, a flaky connection, etc.
# Early exit in case we can detect that the service is down
# and so there is no use in retrying the RPC call.
if self.service_is_down():
raise ServiceIsClosed("Service is offline")
attempt += 1
if attempt > max_retries:
raise ServiceTransportError(
f"{self.url} {e.details()} ({max_retries} retries)"
) from None
remaining = max_retries - attempt
logger.warning(
"%s %s (%d %s remaining)",
self.url,
e.details(),
remaining,
plural(remaining, "attempt", "attempts"),
)
sleep(retry_wait_seconds)
retry_wait_seconds *= retry_wait_backoff_exponent
elif (
e.code() == grpc.StatusCode.INTERNAL
and e.details() == "Exception serializing request!"
):
raise TypeError(
f"{e.details()} Request type: {type(request).__name__}"
) from None
elif e.code() == grpc.StatusCode.DEADLINE_EXCEEDED:
raise TimeoutError(
f"{e.details()} ({timeout:.1f} seconds)"
) from None
elif e.code() == grpc.StatusCode.DATA_LOSS:
raise ServiceError(e.details()) from None
elif e.code() == grpc.StatusCode.UNKNOWN:
# By default, GRPC provides no context if an exception is
# raised in an RPC handler as this could lead to an
# information leak. Unfortunately for us this makes
# debugging a little more difficult, so be verbose about the
# possible causes of this error.
raise ServiceError(
"Service returned an unknown error. Possibly an "
"unhandled exception in a C++ RPC handler, see "
"<https://github.com/grpc/grpc/issues/13706>."
) from None
else:
raise ServiceError(
f"RPC call returned status code {e.code()} and error `{e.details()}`"
) from None
def loglines(self) -> Iterable[str]:
"""Fetch any available log lines from the service backend.
:return: An iterator over lines of logs.
"""
yield from ()
def service_is_down(self) -> bool:
"""Return true if the service is known to be dead.
Subclasses can use this for fast checks that a service is down to avoid
retry loops.
"""
return False
class ManagedConnection(Connection):
"""A connection to a service using a managed subprocess."""
def __init__(
self,
local_service_binary: Path,
port_init_max_seconds: float,
rpc_init_max_seconds: float,
process_exit_max_seconds: float,
script_args: List[str],
script_env: Dict[str, str],
):
"""Constructor.
:param local_service_binary: The path of the service binary.
:raises TimeoutError: If fails to establish connection within a specified time limit.
"""
self.process_exit_max_seconds = process_exit_max_seconds
if not Path(local_service_binary).is_file():
raise FileNotFoundError(f"File not found: {local_service_binary}")
self.cache = ServiceCache()
# The command that will be executed. The working directory of this
# command will be set to the local_service_binary's parent, so we can
# use the relpath for a neater `ps aux` view.
cmd = [
f"./{local_service_binary.name}",
f"--working_dir={self.cache.path}",
]
# Add any custom arguments
cmd += script_args
# Set the root of the runfiles directory.
env = os.environ.copy()
env["COMPILER_GYM_RUNFILES"] = str(runfiles_path("."))
env["COMPILER_GYM_SITE_DATA"] = str(site_data_path("."))
# Set the pythonpath so that executable python scripts can use absolute
# import paths like `from compiler_gym.envs.foo import bar`.
if "PYTHONPATH" in env:
env["PYTHONPATH"] = f'{env["PYTHONPATH"]}:{env["COMPILER_GYM_RUNFILES"]}'
else:
env["PYTHONPATH"] = env["COMPILER_GYM_RUNFILES"]
# Set the verbosity of the service. The logging level of the service is
# the debug level - 1, so that COMPILER_GYM_DEBUG=3 will cause VLOG(2)
# and lower to be logged to stdout.
debug_level = max(
get_debug_level(), logging_level_to_debug_level(logger.getEffectiveLevel())
)
if debug_level > 0:
cmd.append("--alsologtostderr")
cmd.append(f"-v={debug_level - 1}")
# If we are debugging the backend, set the logbuflevel to a low
# value to disable buffering of logging messages. This removes any
# buffering between `LOG(INFO) << "..."` and the message being
# emited to stderr.
cmd.append("--logbuflevel=-1")
else:
# Silence the gRPC logs as we will do our own error reporting, but
# don't override any existing value so that the user may debug the
# gRPC backend by setting GRPC_VERBOSITY to ERROR, INFO, or DEBUG.
if not os.environ.get("GRPC_VERBOSITY"):
env["GRPC_VERBOSITY"] = "NONE"
# Set environment variable COMPILER_GYM_SERVICE_ARGS to pass
# additional arguments to the service.
args = os.environ.get("COMPILER_GYM_SERVICE_ARGS", "")
if args:
cmd.append(args)
# Add any custom environment variables
env.update(script_env)
logger.debug(
"Exec `%s%s`",
" ".join(f"{k}={v}" for k, v in script_env.items()) + " "
if script_env
else "",
join_cmd(cmd),
)
self.process = subprocess.Popen(
cmd,
env=env,
cwd=local_service_binary.parent,
)
self._process_returncode_exception_raised = False
# Read the port from a file generated by the service.
wait_secs = 0.1
port_path = self.cache / "port.txt"
end_time = time() + port_init_max_seconds
while time() < end_time:
returncode = self.process.poll()
if returncode is not None:
try:
# Try and decode the name of a signal. Signal returncodes
# are negative.
returncode = f"{returncode} ({Signals(abs(returncode)).name})"
except ValueError:
pass
msg = f"Service terminated with returncode: {returncode}"
# Attach any logs from the service if available.
logs = truncate_lines(
self.loglines(), max_line_len=100, max_lines=25, tail=True
)
if logs:
msg = f"{msg}\nService logs:\n{logs}"
self.cache.close()
raise ServiceError(msg)
if port_path.is_file():
try:
with open(port_path) as f:
self.port = int(f.read().rstrip())
break
except ValueError:
# ValueError is raised by int(...) on invalid input. In that
# case, wait for longer.
pass
sleep(wait_secs)
wait_secs *= 1.2
else:
# kill() was added in Python 3.7.
if sys.version_info >= (3, 7, 0):
self.process.kill()
else:
self.process.terminate()
self.process.communicate(timeout=rpc_init_max_seconds)
self.cache.close()
raise TimeoutError(
"Service failed to produce port file after "
f"{port_init_max_seconds:.1f} seconds"
)
url = f"localhost:{self.port}"
wait_secs = 0.1
attempts = 0
end_time = time() + rpc_init_max_seconds
while time() < end_time:
try:
channel = grpc.insecure_channel(
url,
options=GRPC_CHANNEL_OPTIONS,
)
channel_ready = grpc.channel_ready_future(channel)
attempts += 1
channel_ready.result(timeout=wait_secs)
break
except (grpc.FutureTimeoutError, grpc.RpcError) as e:
logger.debug(
"Connection attempt %d = %s %s", attempts, type(e).__name__, str(e)
)
wait_secs *= 1.2
else:
# kill() was added in Python 3.7.
if sys.version_info >= (3, 7, 0):
self.process.kill()
else:
self.process.terminate()
self.process.communicate(timeout=process_exit_max_seconds)
# Include the last few lines of logs generated by the compiler
# service, if any.
logs = truncate_lines(
self.loglines(), max_line_len=100, max_lines=25, tail=True
)
logs_message = f" Service logs:\n{logs}" if logs else ""
self.cache.close()
raise TimeoutError(
"Failed to connect to RPC service after "
f"{rpc_init_max_seconds:.1f} seconds.{logs_message}"
)
super().__init__(channel, url)
@property
@deprecated(version="0.2.4", reason="Replace `working_directory` with `cache.path`")
def working_dir(self) -> Path:
return self.cache.path
def service_is_down(self) -> bool:
"""Return true if the service subprocess has terminated."""
return self.process.poll() is not None
def loglines(self) -> Iterable[str]:
"""Fetch any available log lines from the service backend.
:return: An iterator over lines of logs.
"""
# Compiler services write log files in the logs directory. Iterate over
# them and return their contents.
if not (self.cache / "logs").is_dir():
return ()
for path in sorted((self.cache / "logs").iterdir()):
if not path.is_file():
continue
with open(path) as f:
yield from f.readlines()
def close(self):
"""Terminate a local subprocess and close the connection."""
try:
self.process.terminate()
self.process.communicate(timeout=self.process_exit_max_seconds)
if (
self.process.returncode
and not self._process_returncode_exception_raised
):
# You can call close() multiple times but we only want to emit
# the exception once.
self._process_returncode_exception_raised = True
raise ServiceError(
f"Service exited with returncode {self.process.returncode}"
)
except ServiceIsClosed:
# The service has already been closed, nothing to do.
pass
except ProcessLookupError:
logger.warning("Service process not found at %s", self.cache)
except subprocess.TimeoutExpired:
# Try and kill it and then walk away.
try:
# kill() was added in Python 3.7.
if sys.version_info >= (3, 7, 0):
self.process.kill()
else:
self.process.terminate()
self.process.communicate(timeout=60)
except: # noqa
pass
logger.warning("Abandoning orphan service at %s", self.cache)
finally:
self.cache.close()
super().close()
def __repr__(self):
if self.process.poll() is None:
return (
f"Connection to service at {self.url} running on PID {self.process.pid}"
)
return f"Connection to dead service at {self.url}"
class UnmanagedConnection(Connection):
"""A connection to a service that is not managed by this process."""
def __init__(self, url: str, rpc_init_max_seconds: float):
"""Constructor.
:param url: The URL of the service to connect to.
:raises TimeoutError: If fails to establish connection within a specified time limit.
"""
wait_secs = 0.1
attempts = 0
end_time = time() + rpc_init_max_seconds
while time() < end_time:
try:
channel = grpc.insecure_channel(
url,
options=GRPC_CHANNEL_OPTIONS,
)
channel_ready = grpc.channel_ready_future(channel)
attempts += 1
channel_ready.result(timeout=wait_secs)
break
except (grpc.FutureTimeoutError, grpc.RpcError) as e:
logger.debug(
"Connection attempt %d = %s %s", attempts, type(e).__name__, str(e)
)
wait_secs *= 1.2
else:
raise TimeoutError(
f"Failed to connect to {url} after "
f"{rpc_init_max_seconds:.1f} seconds"
)
super().__init__(channel, url)
def __repr__(self):
return f"Connection to unmanaged service {self.url}"
class CompilerGymServiceConnection:
"""A connection to a compiler gym service.
There are two types of service connections: managed and unmanaged. The type
of connection is determined by the endpoint. If a "host:port" URL is provided,
an unmanaged connection is created. If the path of a file is provided, a
managed connection is used. The difference between a managed and unmanaged
connection is that with a managed connection, the lifecycle of the service
if controlled by the client connection. That is, when a managed connection
is created, a service subprocess is started by executing the specified path.
When the connection is closed, the subprocess is terminated. With an
unmanaged connection, if the service fails is goes offline, the client will
fail.
This class provides a common abstraction between the two types of connection,
and provides a call method for invoking remote procedures on the service.
Example usage of an unmanaged service connection:
.. code-block:: python
# Connect to a service running on localhost:8080. The user must
# started a process running on port 8080.
connection = CompilerGymServiceConnection("localhost:8080")
# Invoke an RPC method.
connection(connection.stub.StartSession, StartSessionRequest())
# Close the connection. The service running on port 8080 is
# left running.
connection.close()
Example usage of a managed service connection:
.. code-block:: python
# Start a subprocess using the binary located at /path/to/my/service.
connection = CompilerGymServiceConnection(Path("/path/to/my/service"))
# Invoke an RPC method.
connection(connection.stub.StartSession, StartSessionRequest())
# Close the connection. The subprocess is terminated.
connection.close()
:ivar stub: A CompilerGymServiceStub that can be used as the first argument
to :py:meth:`__call__()` to specify an RPC
method to call.
:ivar action_spaces: A list of action spaces provided by the service.
:ivar observation_spaces: A list of observation spaces provided by the
service.
"""
def __init__(
self,
endpoint: Union[str, Path],
opts: ConnectionOpts = None,
):
"""Constructor.
:param endpoint: The connection endpoint. Either the URL of a service,
e.g. "localhost:8080", or the path of a local service binary.
:param opts: The connection options.
:raises ValueError: If the provided options are invalid.
:raises FileNotFoundError: In case opts.local_service_binary is not found.
:raises TimeoutError: In case the service failed to start within
opts.init_max_seconds seconds.
"""
self.endpoint = endpoint
self.opts = opts or ConnectionOpts()
self.connection = None
self.stub = None
self._establish_connection()
self.action_spaces: List[ActionSpace] = list(
self.connection.spaces.action_space_list
)
self.observation_spaces: List[ObservationSpace] = list(
self.connection.spaces.observation_space_list
)
def _establish_connection(self) -> None:
"""Create and establish a connection."""
self.connection = self._create_connection(self.endpoint, self.opts)
self.stub = self.connection.stub
@classmethod
def _create_connection(
cls,
endpoint: Union[str, Path],
opts: ConnectionOpts,
) -> Connection:
"""Initialize the service connection, either by connecting to an RPC
service or by starting a locally-managed subprocess.
:param endpoint: The connection endpoint. Either the URL of a service,
e.g. "localhost:8080", or the path of a local service binary.
:param opts: The connection options.
:raises ValueError: If the provided options are invalid.
:raises FileNotFoundError: In case opts.local_service_binary is not found.
:raises ServiceError: In case opts.init_max_attempts failures are made
without successfully starting the connection.
:raises TimeoutError: In case the service failed to start within
opts.init_max_seconds seconds.
"""
if not endpoint:
raise TypeError("No endpoint provided for service connection")
start_time = time()
end_time = start_time + opts.init_max_seconds
attempts = 0
last_exception = None
while time() < end_time and attempts < opts.init_max_attempts:
attempts += 1
try:
if isinstance(endpoint, Path):
endpoint_name = endpoint.name
return ManagedConnection(
local_service_binary=endpoint,
process_exit_max_seconds=opts.local_service_exit_max_seconds,
rpc_init_max_seconds=opts.rpc_init_max_seconds,
port_init_max_seconds=opts.local_service_port_init_max_seconds,
script_args=opts.script_args,
script_env=opts.script_env,
)
else:
endpoint_name = endpoint
return UnmanagedConnection(
url=endpoint,
rpc_init_max_seconds=opts.rpc_init_max_seconds,
)
except (TimeoutError, ServiceError, NotImplementedError) as e:
# Catch preventable errors so that we can retry:
# TimeoutError: raised if a service does not produce a port file establish a
# connection without a deadline.
# ServiceError: raised by an RPC method returning an error status.
# NotImplementedError: raised if an RPC method is accessed before the RPC service
# has initialized.
last_exception = e
logger.warning("%s %s (attempt %d)", type(e).__name__, e, attempts)
exception_class = (
ServiceError if attempts >= opts.init_max_attempts else TimeoutError
)
raise exception_class(
f"Failed to create connection to {endpoint_name} after "
f"{time() - start_time:.1f} seconds "
f"({attempts} {plural(attempts, 'attempt', 'attempts')} made).\n"
f"Last error ({type(last_exception).__name__}): {last_exception}"
)
def __repr__(self):
if self.connection is None:
return f"Closed connection to {self.endpoint}"
return str(self.endpoint)
@property
def closed(self) -> bool:
"""Whether the connection is closed."""
return self.connection is None
def close(self):
if self.closed:
return
self.connection.close()
self.connection = None
def __del__(self):
# Don't let the subprocess be orphaned if user forgot to close(), or
# if an exception was thrown.
self.close()
def restart(self):
"""Restart a connection a service. If the service is managed by this
connection (i.e. it is a local binary), the existing service process
will be killed and replaced. Else, only the connection to the unmanaged
service process is replaced.
"""
if self.connection:
self.connection.close()
self._establish_connection()
def __call__(
self,
stub_method: StubMethod,
request: Request,
timeout: Optional[float] = 300,
max_retries: Optional[int] = None,
retry_wait_seconds: Optional[float] = None,
retry_wait_backoff_exponent: Optional[float] = None,
) -> Reply:
"""Invoke an RPC method on the service and return its response. All
RPC methods accept a single `request` message, and respond with a
response message.
Example usage:
.. code-block:: python
connection = CompilerGymServiceConnection("localhost:8080")
request = compiler_gym.service.proto.GetSpacesRequest()
reply = connection(connection.stub.GetSpaces, request)
In the above example, the `GetSpaces` RPC method is invoked on a
connection, yielding a `GetSpacesReply` message.
:param stub_method: An RPC method attribute on `CompilerGymServiceStub`.
:param request: A request message.
:param timeout: The maximum number of seconds to await a reply.
:param max_retries: The maximum number of failed attempts to communicate
with the RPC service before raising an error. Retries are made only
for communication errors. Failures from other causes such as error
signals raised by the service are not retried.
:param retry_wait_seconds: The number of seconds to wait between
successive attempts to communicate with the RPC service.
:param retry_wait_backoff_exponent: The exponential backoff scaling
between successive attempts to communicate with the RPC service.
:raises ValueError: If the service responds with an error indicating an
invalid argument.
:raises NotImplementedError: If the service responds with an error
indicating that the requested functionality is not implemented.
:raises FileNotFoundError: If the service responds with an error
indicating that a requested resource was not found.
:raises OSError: If the service responds with an error indicating that
it ran out of resources.
:raises TypeError: If the provided `request` parameter is of
incorrect type or cannot be serialized, or if the service responds
with an error indicating that a precondition failed.
:raises TimeoutError: If the service failed to respond to the query
within the specified `timeout`.
:raises ServiceTransportError: If the client failed to communicate with
the service.
:raises ServiceIsClosed: If the connection to the service is closed.
:raises ServiceError: If the service raised an error not covered by
any of the above conditions.
:return: A reply message.
"""
if self.closed:
self._establish_connection()
return self.connection(
stub_method,
request,
timeout=timeout,
max_retries=max_retries or self.opts.rpc_max_retries,
retry_wait_seconds=retry_wait_seconds or self.opts.retry_wait_seconds,
retry_wait_backoff_exponent=(
retry_wait_backoff_exponent or self.opts.retry_wait_backoff_exponent
),
)
|
CompilerGym-development
|
compiler_gym/service/connection.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
from typing import List, Optional, Tuple
from compiler_gym.service.proto import ActionSpace, Benchmark
from compiler_gym.service.proto import Event as Action
from compiler_gym.service.proto import Event as Observation
from compiler_gym.service.proto import ObservationSpace
class CompilationSession:
"""Base class for encapsulating an incremental compilation session.
To add support for a new compiler, subclass from this base and provide
implementations of the abstract methods, then call
:func:`create_and_run_compiler_service
<compiler_gym.service.runtime.create_and_run_compiler_service>` and pass in
your class type:
.. code-block:: python
from compiler_gym.service import CompilationSession
from compiler_gym.service import runtime
class MyCompilationSession(CompilationSession):
...
if __name__ == "__main__":
runtime.create_and_run_compiler_service(MyCompilationSession)
"""
compiler_version: str = ""
"""The compiler version."""
action_spaces: List[ActionSpace] = []
"""A list of action spaces describing the capabilities of the compiler."""
observation_spaces: List[ObservationSpace] = []
"""A list of feature vectors that this compiler provides."""
def __init__(
self, working_dir: Path, action_space: ActionSpace, benchmark: Benchmark
):
"""Start a CompilationSession.
Subclasses should initialize the parent class first.
:param working_dir: A directory on the local filesystem that can be used
to store temporary files such as build artifacts.
:param action_space: The action space to use.
:param benchmark: The benchmark to use.
"""
del action_space # Subclasses must use this.
del benchmark # Subclasses must use this.
self.working_dir = working_dir
def apply_action(self, action: Action) -> Tuple[bool, Optional[ActionSpace], bool]:
"""Apply an action.
:param action: The action to apply.
:return: A tuple: :code:`(end_of_session, new_action_space,
action_had_no_effect)`.
"""
raise NotImplementedError
def get_observation(self, observation_space: ObservationSpace) -> Observation:
"""Compute an observation.
:param observation_space: The observation space.
:return: An observation.
"""
raise NotImplementedError
def fork(self) -> "CompilationSession":
"""Create a copy of current session state.
Implementing this method is optional.
:return: A new CompilationSession with the same state.
"""
# No need to override this if you are not adding support to fork().
raise NotImplementedError("CompilationSession.fork() not supported")
def handle_session_parameter(self, key: str, value: str) -> Optional[str]:
"""Handle a session parameter send by the frontend.
Session parameters provide a method to send ad-hoc key-value messages to
a compilation session through the :meth:`env.send_session_parameter()
<compiler_gym.envs.ClientServiceCompilerEnv.send_session_parameter>` method. It us up
to the client/service to agree on a common schema for encoding and
decoding these parameters.
Implementing this method is optional.
:param key: The parameter key.
:param value: The parameter value.
:return: A string response message if the parameter was understood. Else
:code:`None` to indicate that the message could not be interpretted.
"""
pass
|
CompilerGym-development
|
compiler_gym/service/compilation_session.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines a filesystem cache for services."""
import os
import random
import shutil
from datetime import datetime
from pathlib import Path
from compiler_gym.util.filesystem import is_in_memory
from compiler_gym.util.runfiles_path import cache_path, transient_cache_path
MAX_CACHE_CONFLICT_RETIRES: int = 1000
def _create_timestamped_unique_service_dir(root: Path) -> Path:
for _ in range(MAX_CACHE_CONFLICT_RETIRES):
random_hash = random.getrandbits(16)
service_name = datetime.now().strftime(f"s/%m%dT%H%M%S-%f-{random_hash:04x}")
path: Path = root / service_name
# Guard against the unlikely scenario that there is a collision between
# the randomly generated working directories of multiple ServiceCache
# constructors.
try:
path.mkdir(parents=True, exist_ok=False)
break
except FileExistsError:
pass
else:
raise OSError(
"Could not create a unique cache directory "
f"after {MAX_CACHE_CONFLICT_RETIRES} retries."
)
return path
class ServiceCache:
"""A filesystem cache for use by managed services.
This provides a directory in which a service can store temporary files and
artifacts. A service can assume exclusive use of this cache. When supported,
the cache will be in an in-memory filesystem.
The cache contains two subdirectories: "logs", which may be used for storing
log files, and "disk", which may be used for storing files that require
being stored on a traditional filesystem. On some Linux distributions,
in-memory filesystems do not permit executing files. See:
<github.com/facebookresearch/CompilerGym/issues/465>
"""
def __init__(self):
self.path = _create_timestamped_unique_service_dir(transient_cache_path("."))
(self.path / "logs").mkdir()
self._directories_to_remove = [self.path]
if is_in_memory(self.path):
disk = _create_timestamped_unique_service_dir(cache_path("."))
self._directories_to_remove.append(disk)
os.symlink(disk, self.path / "disk")
else:
(self.path / "disk").mkdir()
def __truediv__(self, rhs) -> Path:
"""Supports 'cache / "path"' syntax."""
return self.path / rhs
def close(self):
"""Remove the cache directory. This must be called."""
for directory in self._directories_to_remove:
shutil.rmtree(directory, ignore_errors=True)
def __repr__(self) -> str:
return str(self.path)
|
CompilerGym-development
|
compiler_gym/service/service_cache.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compiler_gym.service.proto.compiler_gym_service_pb2 import (
ActionSpace,
AddBenchmarkReply,
AddBenchmarkRequest,
Benchmark,
BenchmarkDynamicConfig,
BooleanBox,
BooleanRange,
BooleanSequenceSpace,
BooleanTensor,
ByteBox,
ByteSequenceSpace,
BytesSequenceSpace,
ByteTensor,
Command,
CommandlineSpace,
DictEvent,
DictSpace,
DiscreteSpace,
DoubleBox,
DoubleRange,
DoubleSequenceSpace,
DoubleTensor,
EndSessionReply,
EndSessionRequest,
Event,
File,
FloatBox,
FloatRange,
FloatSequenceSpace,
FloatTensor,
ForkSessionReply,
ForkSessionRequest,
GetSpacesReply,
GetSpacesRequest,
GetVersionReply,
GetVersionRequest,
Int64Box,
Int64Range,
Int64SequenceSpace,
Int64Tensor,
ListEvent,
ListSpace,
NamedDiscreteSpace,
ObservationSpace,
Opaque,
SendSessionParameterReply,
SendSessionParameterRequest,
SessionParameter,
Space,
SpaceSequenceSpace,
StartSessionReply,
StartSessionRequest,
StepReply,
StepRequest,
StringSequenceSpace,
StringSpace,
StringTensor,
)
from compiler_gym.service.proto.compiler_gym_service_pb2_grpc import (
CompilerGymServiceServicer,
CompilerGymServiceStub,
)
__all__ = [
"ActionSpace",
"AddBenchmarkReply",
"AddBenchmarkRequest",
"Benchmark",
"BenchmarkDynamicConfig",
"BooleanBox",
"BooleanRange",
"BooleanSequenceSpace",
"BooleanTensor",
"ByteBox",
"ByteSequenceSpace",
"ByteTensor",
"BytesSequenceSpace",
"Command",
"CommandlineSpace",
"CompilerGymServiceConnection",
"CompilerGymServiceServicer",
"CompilerGymServiceStub",
"ConnectionOpts",
"DictEvent",
"DictSpace",
"DiscreteSpace",
"DoubleBox",
"DoubleRange",
"DoubleRange",
"DoubleSequenceSpace",
"DoubleTensor",
"EndSessionReply",
"EndSessionRequest",
"Event",
"File",
"FloatBox",
"FloatRange",
"FloatSequenceSpace",
"FloatTensor",
"ForkSessionReply",
"ForkSessionRequest",
"GetSpacesReply",
"GetSpacesRequest",
"GetVersionReply",
"GetVersionRequest",
"Int64Box",
"Int64Range",
"Int64SequenceSpace",
"Int64Tensor",
"ListEvent",
"ListSpace",
"NamedDiscreteSpace",
"NamedDiscreteSpace",
"ObservationSpace",
"Opaque",
"SendSessionParameterReply",
"SendSessionParameterRequest",
"SessionParameter",
"Space",
"SpaceSequenceSpace",
"StartSessionReply",
"StartSessionRequest",
"StepReply",
"StepRequest",
"StringSequenceSpace",
"StringSpace",
"StringTensor",
]
|
CompilerGym-development
|
compiler_gym/service/proto/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains converters to/from protobuf messages.
For example <compiler_gym.servie.proto.ActionSpace>/<compiler_gym.servie.proto.ObservationSpace> <-> <compiler_gym.spaces>,
or <compiler_gym.servie.proto.Event> <-> actions/observation.
When defining new environments <compiler_gym.service.proto.py_convertes.make_message_default_converter>
and <compiler_gym.service.proto.py_convertes.to_event_message_default_converter>
can be used as a starting point for custom converters.
"""
import json
from builtins import getattr
from collections import OrderedDict
from typing import Any, Callable
from typing import Dict as DictType
from typing import List, Type, Union
import google.protobuf.any_pb2 as any_pb2
import networkx as nx
import numpy as np
from google.protobuf.message import Message
from gym.spaces import Space as GymSpace
from compiler_gym.service.proto.compiler_gym_service_pb2 import (
ActionSpace as ActionSpaceProto,
)
from compiler_gym.service.proto.compiler_gym_service_pb2 import (
BooleanBox,
BooleanRange,
BooleanSequenceSpace,
BooleanTensor,
ByteBox,
ByteSequenceSpace,
BytesSequenceSpace,
ByteTensor,
CommandlineSpace,
DictEvent,
DictSpace,
DiscreteSpace,
DoubleBox,
DoubleRange,
DoubleSequenceSpace,
DoubleTensor,
Event,
FloatBox,
FloatRange,
FloatSequenceSpace,
FloatTensor,
Int64Box,
Int64Range,
Int64SequenceSpace,
Int64Tensor,
ListEvent,
ListSpace,
NamedDiscreteSpace,
ObservationSpace,
Opaque,
Space,
SpaceSequenceSpace,
StringSequenceSpace,
StringSpace,
StringTensor,
)
from compiler_gym.spaces.action_space import ActionSpace
from compiler_gym.spaces.box import Box
from compiler_gym.spaces.commandline import Commandline, CommandlineFlag
from compiler_gym.spaces.dict import Dict
from compiler_gym.spaces.discrete import Discrete
from compiler_gym.spaces.named_discrete import NamedDiscrete
from compiler_gym.spaces.permutation import Permutation
from compiler_gym.spaces.scalar import Scalar
from compiler_gym.spaces.sequence import Sequence
from compiler_gym.spaces.space_sequence import SpaceSequence
from compiler_gym.spaces.tuple import Tuple
class TypeBasedConverter:
"""Converter that dispatches based on the exact type of the parameter.
>>> converter = TypeBasedConverter({ int: lambda x: float(x)})
>>> val: float = converter(5)
"""
conversion_map: DictType[Type, Callable[[Any], Any]]
def __init__(self, conversion_map: DictType[Type, Callable[[Any], Any]] = None):
self.conversion_map = {} if conversion_map is None else conversion_map
def __call__(self, val: Any) -> Any:
return self.conversion_map[type(val)](val)
class TypeIdDispatchConverter:
"""Dispatches conversion of a <google.protobuf.message.Message>
based on the value of its field "type_id".
If the "type_id" filed is not present the conversion falls back on `default_converter`.
Example:
.. code-block:: python
from compiler_gym.service.proto import Event, py_converters
def default_converter(msg):
return msg.string_value + "_default"
conversion_map = {
"type_1": lambda msg: msg.string_value + "_type_1",
"type_2": lambda msg: msg.string_value + "_type_2",
}
type_id_converter = py_converters.TypeIdDispatchConverter(
default_converter=default_converter, conversion_map=conversion_map
)
assert type_id_converter(Event(string_value="msg_val")) == "msg_val_default"
assert (
type_id_converter(Event(string_value="msg_val", type_id="type_1"))
== "msg_val_type_1"
)
assert (
type_id_converter(Event(string_value="msg_val", type_id="type_2"))
== "msg_val_type_2"
)
"""
conversion_map: DictType[str, Callable[[Message], Any]]
default_converter: Callable[[Message], Any]
def __init__(
self,
default_converter: Callable[[Message], Any],
conversion_map: DictType[str, Callable[[Message], Any]] = None,
):
self.conversion_map = {} if conversion_map is None else conversion_map
self.default_converter = default_converter
def __call__(self, message: Message) -> Any:
if message.HasField("type_id"):
return self.conversion_map[message.type_id](message)
else:
return self.default_converter(message)
proto_type_to_dtype_map = {
BooleanTensor: bool,
ByteTensor: np.int8,
Int64Tensor: np.int64,
FloatTensor: np.float32,
DoubleTensor: np.float64,
StringTensor: object,
BooleanBox: bool,
ByteBox: np.int8,
Int64Box: np.int64,
FloatBox: np.float32,
DoubleBox: float,
BooleanRange: bool,
Int64Range: np.int64,
FloatRange: np.float32,
DoubleRange: float,
BooleanSequenceSpace: bool,
BytesSequenceSpace: bytes,
ByteSequenceSpace: np.int8,
Int64SequenceSpace: np.int64,
FloatSequenceSpace: np.float32,
DoubleSequenceSpace: float,
StringSpace: str,
}
def convert_standard_tensor_message_to_numpy(
tensor: Union[BooleanTensor, Int64Tensor, FloatTensor, DoubleTensor, StringTensor]
):
res = np.array(tensor.value, dtype=proto_type_to_dtype_map[type(tensor)])
res = res.reshape(tensor.shape)
return res
def convert_numpy_to_boolean_tensor_message(tensor: np.ndarray):
return BooleanTensor(value=tensor.flatten().tolist(), shape=tensor.shape)
def convert_byte_tensor_message_to_numpy(tensor: ByteTensor):
res = np.frombuffer(tensor.value, dtype=np.byte)
res = res.reshape(tensor.shape)
return res
def convert_numpy_to_byte_tensor_message(tensor: np.ndarray):
return ByteTensor(value=tensor.tobytes(), shape=tensor.shape)
def convert_numpy_to_int64_tensor_message(tensor: np.ndarray):
return Int64Tensor(value=tensor.flatten(), shape=tensor.shape)
def convert_numpy_to_float_tensor_message(tensor: np.ndarray):
return FloatTensor(value=tensor.flatten(), shape=tensor.shape)
def convert_numpy_to_double_tensor_message(tensor: np.ndarray):
return DoubleTensor(value=tensor.flatten(), shape=tensor.shape)
def convert_numpy_to_string_tensor_message(tensor: np.ndarray):
return StringTensor(value=tensor.flatten(), shape=tensor.shape)
convert_tensor_message_to_numpy = TypeBasedConverter(
conversion_map={
BooleanTensor: convert_standard_tensor_message_to_numpy,
ByteTensor: convert_byte_tensor_message_to_numpy,
Int64Tensor: convert_standard_tensor_message_to_numpy,
FloatTensor: convert_standard_tensor_message_to_numpy,
DoubleTensor: convert_standard_tensor_message_to_numpy,
StringTensor: convert_standard_tensor_message_to_numpy,
}
)
def convert_bytes_to_numpy(arr: bytes) -> np.ndarray:
return np.frombuffer(arr, dtype=np.int8)
def convert_permutation_space_message(space: Space) -> Permutation:
if (
space.int64_sequence.scalar_range.max
- space.int64_sequence.scalar_range.min
+ 1
!= space.int64_sequence.length_range.min
or space.int64_sequence.length_range.min
!= space.int64_sequence.length_range.max
):
raise ValueError(
f"Invalid permutation space message:\n{space}."
" Variable sequence length is not allowed."
" A permutation must also include all integers in its range "
"[min, min + length)."
)
return Permutation(
name=None,
scalar_range=convert_range_message(space.int64_sequence.scalar_range),
)
class NumpyToTensorMessageConverter:
dtype_conversion_map: DictType[Type, Callable[[Any], Message]]
def __init__(self):
self.dtype_conversion_map = {
np.bool_: convert_numpy_to_boolean_tensor_message,
np.int8: convert_numpy_to_byte_tensor_message,
np.int64: convert_numpy_to_int64_tensor_message,
np.float32: convert_numpy_to_float_tensor_message,
np.float64: convert_numpy_to_double_tensor_message,
np.dtype(object): convert_numpy_to_string_tensor_message,
}
def __call__(
self, tensor: np.ndarray
) -> Union[
BooleanTensor, ByteTensor, Int64Tensor, FloatTensor, DoubleTensor, StringTensor
]:
return self.dtype_conversion_map[tensor.dtype.type](tensor)
convert_numpy_to_tensor_message = NumpyToTensorMessageConverter()
def convert_trivial(val: Any):
return val
class FromMessageConverter:
"""Convert a protobuf message to an object.
The conversion function is chosen based on the message descriptor.
"""
conversion_map: DictType[str, Callable[[Message], Any]]
def __init__(self, conversion_map: DictType[str, Callable[[Message], Any]] = None):
self.conversion_map = {} if conversion_map is None else conversion_map
def __call__(self, message: Message) -> Any:
return self.conversion_map[message.DESCRIPTOR.full_name](message)
class EventMessageDefaultConverter:
message_converter: Callable[[Any], Any]
def __init__(self, message_converter: Callable[[Any], Any]):
self.message_converter = message_converter
def __call__(self, event: Event):
field = event.WhichOneof("value")
if field is None:
return None
return self.message_converter(getattr(event, field))
class ToEventMessageConverter:
converter: TypeBasedConverter
type_field_map: DictType[Type, str]
def __init__(self, converter: TypeBasedConverter):
self.converter = converter
self.type_field_map = {
ListEvent: "event_list",
DictEvent: "event_dict",
bool: "boolean_value",
int: "int64_value",
np.int32: "int64_value",
np.float32: "float_value",
float: "double_value",
str: "string_value",
BooleanTensor: "boolean_tensor",
ByteTensor: "byte_tensor",
Int64Tensor: "int64_tensor",
FloatTensor: "float_tensor",
DoubleTensor: "double_tensor",
StringTensor: "string_tensor",
any_pb2.Any: "any_value",
}
def __call__(self, val: Any) -> Event:
converted_val = self.converter(val)
res = Event()
if isinstance(converted_val, Message):
getattr(res, self.type_field_map[type(converted_val)]).CopyFrom(
converted_val
)
else:
setattr(res, self.type_field_map[type(converted_val)], converted_val)
return res
class ListEventMessageConverter:
event_message_converter: Callable[[Event], Any]
def __init__(self, event_message_converter: Callable[[Event], Any]):
self.event_message_converter = event_message_converter
def __call__(self, list_event: ListEvent) -> List[Any]:
return [self.event_message_converter(event) for event in list_event.event]
class ToListEventMessageConverter:
to_event_converter: ToEventMessageConverter
def __init__(self, to_event_converter: ToEventMessageConverter):
self.to_event_converter = to_event_converter
def __call__(self, event_list: List) -> ListEvent:
return ListEvent(event=[self.to_event_converter(event) for event in event_list])
class DictEventMessageConverter:
event_message_converter: Callable[[Event], Any]
def __init__(self, event_message_converter: Callable[[Event], Any]):
self.event_message_converter = event_message_converter
def __call__(self, dict_event: DictEvent) -> DictType[str, Any]:
return {
key: self.event_message_converter(event)
for key, event in dict_event.event.items()
}
class ToDictEventMessageConverter:
to_event_converter: ToEventMessageConverter
def __init__(self, to_event_converter: ToEventMessageConverter):
self.to_event_converter = to_event_converter
def __call__(self, d: DictType) -> DictEvent:
return DictEvent(
event={key: self.to_event_converter(val) for key, val in d.items()}
)
class ProtobufAnyUnpacker:
# message type string to message class map
type_str_to_class_map: DictType[str, Type]
def __init__(self, type_str_to_class_map: DictType[str, Type] = None):
self.type_str_to_class_map = (
{
"compiler_gym.Opaque": Opaque,
"compiler_gym.CommandlineSpace": CommandlineSpace,
}
if type_str_to_class_map is None
else type_str_to_class_map
)
def __call__(self, msg: any_pb2.Any) -> Message:
message_cls = self.type_str_to_class_map[msg.TypeName()]
unpacked_message = message_cls()
status = msg.Unpack(unpacked_message)
if not status:
raise ValueError(
f'Failed unpacking prtobuf Any message with type url "{msg.TypeName()}".'
)
return unpacked_message
class ProtobufAnyConverter:
unpacker: ProtobufAnyUnpacker
message_converter: Callable[[Message], Any]
def __init__(
self, unpacker: ProtobufAnyUnpacker, message_converter: Callable[[Message], Any]
):
self.unpacker = unpacker
self.message_converter = message_converter
def __call__(self, msg: any_pb2.Any) -> Any:
unpacked_message = self.unpacker(msg)
return self.message_converter(unpacked_message)
class ActionSpaceMessageConverter:
message_converter: Callable[[Any], Any]
def __init__(self, message_converter: Callable[[Any], Any]):
self.message_converter = message_converter
def __call__(self, message: ActionSpace) -> GymSpace:
res = self.message_converter(message.space)
res.name = message.name
return res
class ObservationSpaceMessageConverter:
message_converter: Callable[[Any], Any]
def __init__(self, message_converter: Callable[[Any], Any]):
self.message_converter = message_converter
def __call__(self, message: ObservationSpace) -> GymSpace:
res = self.message_converter(message.space)
res.name = message.name
return res
def make_action_space_wrapper(
converter: Callable[[Any], Any]
) -> Callable[[Any], ActionSpace]:
return lambda msg: ActionSpace(space=converter(msg))
def make_message_default_converter() -> Callable[[Any], Any]:
conversion_map = {
bool: convert_trivial,
int: convert_trivial,
np.int32: convert_trivial,
float: convert_trivial,
np.float32: convert_trivial,
str: convert_trivial,
bytes: convert_bytes_to_numpy,
BooleanTensor: convert_tensor_message_to_numpy,
ByteTensor: convert_tensor_message_to_numpy,
Int64Tensor: convert_tensor_message_to_numpy,
FloatTensor: convert_tensor_message_to_numpy,
DoubleTensor: convert_tensor_message_to_numpy,
StringTensor: convert_tensor_message_to_numpy,
DiscreteSpace: convert_discrete_space_message,
NamedDiscreteSpace: convert_named_discrete_space_message,
CommandlineSpace: convert_commandline_space_message,
BooleanRange: convert_range_message,
Int64Range: convert_range_message,
FloatRange: convert_range_message,
DoubleRange: convert_range_message,
StringSpace: convert_string_space,
BooleanSequenceSpace: convert_sequence_space,
ByteSequenceSpace: convert_sequence_space,
BytesSequenceSpace: convert_sequence_space,
Int64SequenceSpace: convert_sequence_space,
FloatSequenceSpace: convert_sequence_space,
DoubleSequenceSpace: convert_sequence_space,
StringSequenceSpace: convert_sequence_space,
BooleanBox: convert_box_message,
ByteBox: convert_box_message,
Int64Box: convert_box_message,
FloatBox: convert_box_message,
DoubleBox: convert_box_message,
}
res = TypeBasedConverter(conversion_map)
conversion_map[Event] = TypeIdDispatchConverter(
default_converter=EventMessageDefaultConverter(res)
)
conversion_map[ListEvent] = ListEventMessageConverter(conversion_map[Event])
conversion_map[DictEvent] = DictEventMessageConverter(conversion_map[Event])
conversion_map[Space] = TypeIdDispatchConverter(
default_converter=SpaceMessageDefaultConverter(res),
conversion_map={"permutation": convert_permutation_space_message},
)
conversion_map[ListSpace] = ListSpaceMessageConverter(conversion_map[Space])
conversion_map[DictSpace] = DictSpaceMessageConverter(conversion_map[Space])
conversion_map[SpaceSequenceSpace] = SpaceSequenceSpaceMessageConverter(res)
conversion_map[ActionSpaceProto] = ActionSpaceMessageConverter(res)
conversion_map[ObservationSpace] = ObservationSpaceMessageConverter(res)
conversion_map[any_pb2.Any] = ProtobufAnyConverter(
unpacker=ProtobufAnyUnpacker(), message_converter=res
)
conversion_map[Opaque] = make_opaque_message_default_converter()
return res
def to_event_message_default_converter() -> ToEventMessageConverter:
conversion_map = {
bool: convert_trivial,
int: convert_trivial,
np.int32: convert_trivial,
float: convert_trivial,
np.float32: convert_trivial,
str: convert_trivial,
np.int32: convert_trivial,
np.ndarray: NumpyToTensorMessageConverter(),
}
type_based_converter = TypeBasedConverter(conversion_map)
res = ToEventMessageConverter(type_based_converter)
conversion_map[list] = ToListEventMessageConverter(res)
conversion_map[dict] = ToDictEventMessageConverter(res)
conversion_map[OrderedDict] = ToDictEventMessageConverter(res)
return res
range_type_default_min_map: DictType[Type, Any] = {
BooleanRange: False,
Int64Range: np.iinfo(np.int64).min,
FloatRange: np.float32(np.NINF),
DoubleRange: np.float64(np.NINF),
}
range_type_default_max_map: DictType[Type, Any] = {
BooleanRange: True,
Int64Range: np.iinfo(np.int64).max,
FloatRange: np.float32(np.PINF),
DoubleRange: np.float64(np.PINF),
}
def convert_range_message(
range: Union[BooleanRange, Int64Range, FloatRange, DoubleRange]
) -> Scalar:
range_type = type(range)
min = range.min if range.HasField("min") else range_type_default_min_map[range_type]
max = range.max if range.HasField("max") else range_type_default_max_map[range_type]
return Scalar(
name=None, min=min, max=max, dtype=proto_type_to_dtype_map[range_type]
)
class ToRangeMessageConverter:
dtype_to_type_map: DictType[Type, Type]
def __init__(self):
self.dtype_to_type_map = {
np.bool_: BooleanRange,
np.int8: Int64Range,
np.int64: Int64Range,
np.float32: FloatRange,
np.float64: DoubleRange,
}
def __call__(
self, scalar: Scalar
) -> Union[BooleanRange, Int64Range, FloatRange, DoubleRange]:
return self.dtype_to_type_map[np.dtype(scalar.dtype).type](
min=scalar.min, max=scalar.max
)
convert_to_range_message = ToRangeMessageConverter()
def convert_box_message(
box: Union[BooleanBox, ByteBox, Int64Box, FloatBox, DoubleBox]
) -> Box:
return Box(
low=convert_tensor_message_to_numpy(box.low),
high=convert_tensor_message_to_numpy(box.high),
name=None,
dtype=proto_type_to_dtype_map[type(box)],
)
class ToBoxMessageConverter:
dtype_to_type_map: DictType[Type, Type]
def __init__(self):
self.dtype_to_type_map = {
np.bool_: BooleanBox,
np.int8: ByteBox,
np.int64: Int64Box,
np.float32: FloatBox,
np.float64: DoubleBox,
}
def __call__(
self, box: Box
) -> Union[BooleanBox, ByteBox, Int64Box, FloatBox, DoubleBox]:
return self.dtype_to_type_map[np.dtype(box.dtype).type](
low=convert_numpy_to_tensor_message(box.low),
high=convert_numpy_to_tensor_message(box.high),
)
convert_to_box_message = ToBoxMessageConverter()
def convert_discrete_space_message(message: DiscreteSpace) -> Discrete:
return Discrete(n=message.n, name=None)
def convert_to_discrete_space_message(space: Discrete) -> DiscreteSpace:
return DiscreteSpace(n=space.n)
def convert_named_discrete_space_message(message: NamedDiscreteSpace) -> NamedDiscrete:
return NamedDiscrete(items=message.name, name=None)
def convert_commandline_space_message(message: CommandlineSpace) -> Commandline:
return Commandline(
items=[
CommandlineFlag(name=name, flag=name, description="")
for name in message.name
],
name=None,
)
def convert_to_named_discrete_space_message(space: NamedDiscrete) -> NamedDiscreteSpace:
return NamedDiscreteSpace(name=space.names)
def convert_sequence_space(
seq: Union[
BooleanSequenceSpace,
Int64SequenceSpace,
FloatSequenceSpace,
DoubleSequenceSpace,
BytesSequenceSpace,
StringSequenceSpace,
]
) -> Sequence:
scalar_range = (
convert_range_message(seq.scalar_range)
if hasattr(seq, "scalar_range")
else None
)
length_range = convert_range_message(seq.length_range)
return Sequence(
name=None,
size_range=(length_range.min, length_range.max),
dtype=proto_type_to_dtype_map[type(seq)],
scalar_range=scalar_range,
)
class ToRangedSequenceMessageConverter:
dtype_to_type_map: DictType[Type, Type]
def __init__(self):
self.dtype_to_type_map = {
np.bool_: BooleanSequenceSpace,
np.int8: ByteSequenceSpace,
np.int64: Int64SequenceSpace,
np.float32: FloatSequenceSpace,
np.float64: DoubleSequenceSpace,
}
def __call__(
self, seq: Sequence
) -> Union[
BooleanSequenceSpace,
Int64SequenceSpace,
FloatSequenceSpace,
DoubleSequenceSpace,
]:
return self.dtype_to_type_map[np.dtype(seq.dtype).type](
length_range=Int64Range(min=seq.size_range[0], max=seq.size_range[1]),
scalar_range=convert_to_range_message(seq.scalar_range),
)
convert_to_ranged_sequence_space = ToRangedSequenceMessageConverter()
def convert_to_string_sequence_space(seq: Sequence) -> StringSequenceSpace:
return StringSpace(
length_range=Int64Range(min=seq.size_range[0], max=seq.size_range[1])
)
def convert_to_bytes_sequence_space(seq: Sequence) -> BytesSequenceSpace:
return BytesSequenceSpace(
length_range=Int64Range(min=seq.size_range[0], max=seq.size_range[1])
)
def convert_string_space(s: StringSpace) -> Sequence:
return convert_sequence_space(s)
def convert_to_string_space(s: Sequence) -> StringSpace:
return StringSpace(
length_range=Int64Range(min=s.size_range[0], max=s.size_range[1])
)
class ToSequenceSpaceMessageConverter:
dtype_map: DictType[
Type,
Callable[
[Sequence],
Union[
BooleanSequenceSpace,
BytesSequenceSpace,
Int64SequenceSpace,
FloatSequenceSpace,
DoubleSequenceSpace,
StringSequenceSpace,
],
],
]
def __init__(self):
self.dtype_map = {
bool: convert_to_ranged_sequence_space,
np.bool_: convert_to_ranged_sequence_space,
np.int8: convert_to_bytes_sequence_space,
np.int64: convert_to_ranged_sequence_space,
int: convert_to_ranged_sequence_space,
np.float32: convert_to_ranged_sequence_space,
np.float64: convert_to_ranged_sequence_space,
float: convert_to_ranged_sequence_space,
str: convert_to_string_space,
}
def __call__(
self, seq: Sequence
) -> Union[
BooleanSequenceSpace,
BytesSequenceSpace,
Int64SequenceSpace,
FloatSequenceSpace,
DoubleSequenceSpace,
StringSequenceSpace,
]:
return self.dtype_map[seq.dtype](seq)
convert_to_sequence_space_message = ToSequenceSpaceMessageConverter()
class SpaceSequenceSpaceMessageConverter:
space_message_converter: Callable[[Space], GymSpace]
def __init__(self, space_message_converter):
self.space_message_converter = space_message_converter
def __call__(self, seq: SpaceSequenceSpace) -> GymSpace:
return SpaceSequence(
name=None,
space=self.space_message_converter(seq.space),
size_range=(seq.length_range.min, seq.length_range.max),
)
class SpaceMessageDefaultConverter:
message_converter: TypeBasedConverter
def __init__(self, message_converter: TypeBasedConverter):
self.message_converter = message_converter
def __call__(
self, space: Space
) -> Union[Dict, Discrete, NamedDiscrete, Scalar, Tuple, Box, Sequence]:
field = space.WhichOneof("value")
if field is None:
return None
res = self.message_converter(getattr(space, field))
return res
class ToSpaceMessageConverter:
converter: TypeBasedConverter
type_field_map: DictType[Type, str]
def __init__(self, converter: TypeBasedConverter):
self.converter = converter
self.type_field_map = {
ListSpace: "space_list",
DictSpace: "space_dict",
DiscreteSpace: "discrete",
NamedDiscreteSpace: "named_discrete",
BooleanRange: "boolean_value",
Int64Range: "int64_value",
FloatRange: "float_value",
DoubleRange: "double_value",
StringSpace: "string_value",
BooleanSequenceSpace: "boolean_sequence",
BytesSequenceSpace: "bytes_sequence",
ByteSequenceSpace: "byte_sequence",
Int64SequenceSpace: "int64_sequence",
FloatSequenceSpace: "float_sequence",
DoubleSequenceSpace: "double_sequence",
StringSequenceSpace: "string_sequence",
BooleanBox: "boolean_box",
ByteBox: "byte_box",
Int64Box: "int64_box",
FloatBox: "float_box",
DoubleBox: "double_box",
any_pb2.Any: "any_value",
}
def __call__(
self, space: Union[Tuple, Dict, Discrete, NamedDiscrete, Sequence, Box, Scalar]
) -> Space:
converted_space = self.converter(space)
res = Space()
if isinstance(converted_space, Message):
getattr(res, self.type_field_map[type(converted_space)]).CopyFrom(
converted_space
)
else:
setattr(res, self.type_field_map[type(converted_space)], converted_space)
return res
class ListSpaceMessageConverter:
space_message_converter: Callable[[Space], Any]
def __init__(self, space_message_converter: Callable[[Space], Any]):
self.space_message_converter = space_message_converter
def __call__(self, list_space: ListSpace) -> Tuple:
return Tuple(
spaces=[self.space_message_converter(space) for space in list_space.space],
name=None,
)
class ToListSpaceMessageConverter:
to_space_converter: ToSpaceMessageConverter
def __init__(self, to_space_converter: ToSpaceMessageConverter):
self.to_space_converter = to_space_converter
def __call__(self, spaces: Tuple) -> ListSpace:
return ListSpace(
space=[self.to_space_converter(space) for space in spaces.spaces]
)
class DictSpaceMessageConverter:
space_message_converter: Callable[[Space], Any]
def __init__(self, space_message_converter: Callable[[Space], Any]):
self.space_message_converter = space_message_converter
def __call__(self, dict_space: DictSpace) -> Dict:
return Dict(
spaces={
key: self.space_message_converter(space)
for key, space in dict_space.space.items()
},
name=None,
)
class ToDictSpaceMessageConverter:
to_space_converter: ToSpaceMessageConverter
def __init__(self, to_space_converter: ToSpaceMessageConverter):
self.to_space_converter = to_space_converter
def __call__(self, d: Dict) -> DictSpace:
return DictSpace(
space={key: self.to_space_converter(val) for key, val in d.spaces.items()}
)
def to_space_message_default_converter() -> ToSpaceMessageConverter:
conversion_map = {
Discrete: convert_to_discrete_space_message,
NamedDiscrete: convert_to_named_discrete_space_message,
Scalar: convert_to_range_message,
Sequence: convert_to_sequence_space_message,
Box: convert_to_box_message,
}
type_based_converter = TypeBasedConverter(conversion_map)
res = ToSpaceMessageConverter(type_based_converter)
conversion_map[Tuple] = ToListSpaceMessageConverter(res)
conversion_map[Dict] = ToDictSpaceMessageConverter(res)
return res
class OpaqueMessageConverter:
"""Converts <compiler_gym.service.proto.Opaque> message based on its format descriptor."""
format_coverter_map: DictType[str, Callable[[bytes], Any]]
def __init__(self, format_coverter_map=None):
self.format_coverter_map = (
{} if format_coverter_map is None else format_coverter_map
)
def __call__(self, message: Opaque) -> Any:
return self.format_coverter_map[message.format](message.data)
def make_opaque_message_default_converter():
return OpaqueMessageConverter(
{"json://networkx/MultiDiGraph": _json2nx, "json://": bytes_to_json}
)
def bytes_to_json(data: bytes):
return json.loads(data.decode("utf-8"))
def _json2nx(data: bytes):
json_data = json.loads(data.decode("utf-8"))
return nx.readwrite.json_graph.node_link_graph(
json_data, multigraph=True, directed=True
)
message_default_converter: TypeBasedConverter = make_message_default_converter()
|
CompilerGym-development
|
compiler_gym/service/proto/py_converters.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Dict, Optional
import numpy as np
from compiler_gym.service.proto import Benchmark
MAX_SIZE_IN_BYTES = 512 * 104 * 1024
logger = logging.getLogger(__name__)
class BenchmarkCache:
"""An in-memory cache of Benchmark messages.
This object caches Benchmark messages by URI. Once the cache reaches a
predetermined size, benchmarks are evicted randomly until the capacity is
reduced to 50%.
"""
def __init__(
self,
max_size_in_bytes: int = MAX_SIZE_IN_BYTES,
rng: Optional[np.random.Generator] = None,
):
self._max_size_in_bytes = max_size_in_bytes
self.rng = rng or np.random.default_rng()
self._benchmarks: Dict[str, Benchmark] = {}
self._size_in_bytes = 0
def __getitem__(self, uri: str) -> Benchmark:
"""Get a benchmark by URI. Raises KeyError."""
item = self._benchmarks.get(uri)
if item is None:
raise KeyError(uri)
return item
def __contains__(self, uri: str):
"""Whether URI is in cache."""
return uri in self._benchmarks
def __setitem__(self, uri: str, benchmark: Benchmark):
"""Add benchmark to cache."""
# Remove any existing value to keep the cache size consistent.
if uri in self._benchmarks:
self._size_in_bytes -= self._benchmarks[uri].ByteSize()
del self._benchmarks[uri]
size = benchmark.ByteSize()
if self.size_in_bytes + size > self.max_size_in_bytes:
if size > self.max_size_in_bytes:
logger.warning(
"Adding new benchmark with size %d bytes exceeds total "
"target cache size of %d bytes",
size,
self.max_size_in_bytes,
)
else:
logger.debug(
"Adding new benchmark with size %d bytes "
"exceeds maximum size %d bytes, %d items",
size,
self.max_size_in_bytes,
self.size,
)
self.evict_to_capacity()
self._benchmarks[uri] = benchmark
self._size_in_bytes += size
logger.debug(
"Cached benchmark %s. Cache size = %d bytes, %d items",
uri,
self.size_in_bytes,
self.size,
)
def evict_to_capacity(self, target_size_in_bytes: Optional[int] = None) -> None:
"""Evict benchmarks randomly to reduce the capacity below 50%."""
evicted = 0
target_size_in_bytes = (
self.max_size_in_bytes // 2
if target_size_in_bytes is None
else target_size_in_bytes
)
while self.size and self.size_in_bytes > target_size_in_bytes:
evicted += 1
key = self.rng.choice(list(self._benchmarks.keys()))
self._size_in_bytes -= self._benchmarks[key].ByteSize()
del self._benchmarks[key]
if evicted:
logger.info(
"Evicted %d benchmarks from cache. "
"Benchmark cache size now %d bytes, %d items",
evicted,
self.size_in_bytes,
self.size,
)
@property
def size(self) -> int:
"""The number of items in the cache."""
return len(self._benchmarks)
@property
def size_in_bytes(self) -> int:
"""The combined size of the elements in the cache, excluding the
cache overhead.
"""
return self._size_in_bytes
@property
def max_size_in_bytes(self) -> int:
"""The maximum size of the cache."""
return self._max_size_in_bytes
@max_size_in_bytes.setter
def max_size_in_bytes(self, value: int) -> None:
"""Set a new maximum cache size."""
self._max_size_in_bytes = value
self.evict_to_capacity(target_size_in_bytes=value)
|
CompilerGym-development
|
compiler_gym/service/runtime/benchmark_cache.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compiler_gym.service.runtime.create_and_run_compiler_gym_service import (
create_and_run_compiler_gym_service,
)
__all__ = [
"create_and_run_compiler_gym_service",
]
|
CompilerGym-development
|
compiler_gym/service/runtime/__init__.py
|
#! /usr/bin/env python3
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""An example CompilerGym service in python."""
import os
import sys
from concurrent import futures
from multiprocessing import cpu_count
from pathlib import Path
from signal import SIGTERM, signal
from tempfile import mkdtemp
from threading import Event, Thread
from typing import Type
import grpc
from absl import app, flags, logging
from compiler_gym.service import connection
from compiler_gym.service.compilation_session import CompilationSession
from compiler_gym.service.proto import compiler_gym_service_pb2_grpc
from compiler_gym.service.runtime.compiler_gym_service import CompilerGymService
from compiler_gym.util import debug_util as dbg
from compiler_gym.util.filesystem import atomic_file_write
from compiler_gym.util.shell_format import plural
flags.DEFINE_string("working_dir", "", "Path to use as service working directory")
flags.DEFINE_integer("port", 0, "The service listening port")
flags.DEFINE_integer(
"rpc_service_threads", cpu_count(), "The number of server worker threads"
)
flags.DEFINE_integer("logbuflevel", 0, "Flag for compatability with C++ service.")
FLAGS = flags.FLAGS
MAX_MESSAGE_SIZE_IN_BYTES = 512 * 1024 * 1024
shutdown_signal = Event()
# NOTE(cummins): This script is executed in a subprocess, so code coverage
# tracking does not work. As such we use "# pragma: no cover" annotation for all
# functions.
def _shutdown_handler(signal_number, stack_frame): # pragma: no cover
del stack_frame # Unused
logging.info("Service received signal: %d", signal_number)
shutdown_signal.set()
def create_and_run_compiler_gym_service(
compilation_session_type: Type[CompilationSession],
): # pragma: no cover
"""Create and run an RPC service for the given compilation session.
This should be called on its own in a self contained script to implement a
compilation service. Example:
.. code-block:: python
from compiler_gym.service import runtime
from my_compiler_service import MyCompilationSession
if __name__ == "__main__":
runtime.create_and_run_compiler_gym_service(MyCompilationSession)
This function never returns.
:param compilation_session_type: A sublass of :class:`CompilationSession
<compiler_gym.service.CompilationSession>` that provides implementations
of the abstract methods.
"""
def main(argv):
# Register a signal handler for SIGTERM that will set the shutdownSignal
# future value.
signal(SIGTERM, _shutdown_handler)
argv = [x for x in argv if x.strip()]
if len(argv) > 1:
print(
f"ERROR: Unrecognized command line argument '{argv[1]}'",
file=sys.stderr,
)
sys.exit(1)
working_dir = Path(FLAGS.working_dir or mkdtemp(prefix="compiler_gym-service-"))
(working_dir / "logs").mkdir(exist_ok=True, parents=True)
FLAGS.log_dir = str(working_dir / "logs")
logging.get_absl_handler().use_absl_log_file()
logging.set_verbosity(dbg.get_logging_level())
# Create the service.
server = grpc.server(
futures.ThreadPoolExecutor(max_workers=FLAGS.rpc_service_threads),
options=connection.GRPC_CHANNEL_OPTIONS,
)
service = CompilerGymService(
working_directory=working_dir,
compilation_session_type=compilation_session_type,
)
compiler_gym_service_pb2_grpc.add_CompilerGymServiceServicer_to_server(
service, server
)
address = f"0.0.0.0:{FLAGS.port}" if FLAGS.port else "0.0.0.0:0"
port = server.add_insecure_port(address)
with atomic_file_write(working_dir / "port.txt", fileobj=True, mode="w") as f:
f.write(str(port))
with atomic_file_write(working_dir / "pid.txt", fileobj=True, mode="w") as f:
f.write(str(os.getpid()))
logging.info(
"Service %s listening on %d, PID = %d", working_dir, port, os.getpid()
)
server.start()
# Block on the RPC service in a separate thread. This enables the
# current thread to handle the shutdown routine.
server_thread = Thread(target=server.wait_for_termination)
server_thread.start()
# Block until the shutdown signal is received.
shutdown_signal.wait()
logging.info("Shutting down the RPC service")
server.stop(60).wait()
server_thread.join()
logging.info("Service closed")
if len(service.sessions):
print(
"ERROR: Killing a service with",
plural(len(service.session), "active session", "active sessions"),
file=sys.stderr,
)
sys.exit(6)
app.run(main)
|
CompilerGym-development
|
compiler_gym/service/runtime/create_and_run_compiler_gym_service.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import traceback
from contextlib import contextmanager
from pathlib import Path
from threading import Lock
from typing import Dict, Optional
from grpc import StatusCode
from compiler_gym.service.compilation_session import CompilationSession
from compiler_gym.service.proto import AddBenchmarkReply, AddBenchmarkRequest
from compiler_gym.service.proto import (
CompilerGymServiceServicer as CompilerGymServiceServicerStub,
)
from compiler_gym.service.proto import (
EndSessionReply,
EndSessionRequest,
ForkSessionReply,
ForkSessionRequest,
GetSpacesReply,
GetSpacesRequest,
GetVersionReply,
GetVersionRequest,
SendSessionParameterReply,
SendSessionParameterRequest,
StartSessionReply,
StartSessionRequest,
StepReply,
StepRequest,
)
from compiler_gym.service.runtime.benchmark_cache import BenchmarkCache
from compiler_gym.util.version import __version__
logger = logging.getLogger(__name__)
# NOTE(cummins): The CompilerGymService class is used in a subprocess by a
# compiler service, so code coverage tracking does not work. As such we use "#
# pragma: no cover" annotation for all definitions in this file.
@contextmanager
def exception_to_grpc_status(context): # pragma: no cover
def handle_exception_as(exception, code):
exception_trace = "".join(
traceback.TracebackException.from_exception(exception).format()
)
logger.warning("%s", exception_trace)
context.set_code(code)
context.set_details(str(exception))
try:
yield
except ValueError as e:
handle_exception_as(e, StatusCode.INVALID_ARGUMENT)
except LookupError as e:
handle_exception_as(e, StatusCode.NOT_FOUND)
except NotImplementedError as e:
handle_exception_as(e, StatusCode.UNIMPLEMENTED)
except FileNotFoundError as e:
handle_exception_as(e, StatusCode.UNIMPLEMENTED)
except TypeError as e:
handle_exception_as(e, StatusCode.FAILED_PRECONDITION)
except TimeoutError as e:
handle_exception_as(e, StatusCode.DEADLINE_EXCEEDED)
except Exception as e: # pylint: disable=broad-except
handle_exception_as(e, StatusCode.INTERNAL)
class CompilerGymService(CompilerGymServiceServicerStub): # pragma: no cover
def __init__(self, working_directory: Path, compilation_session_type):
"""Constructor.
:param working_directory: The working directory for this service.
:param compilation_session_type: The :class:`CompilationSession
<compiler_gym.service.CompilationSession>` type that this service
implements.
"""
self.working_directory = working_directory
self.benchmarks = BenchmarkCache()
self.compilation_session_type = compilation_session_type
self.sessions: Dict[int, CompilationSession] = {}
self.sessions_lock = Lock()
self.next_session_id: int = 0
self.action_spaces = compilation_session_type.action_spaces
self.observation_spaces = compilation_session_type.observation_spaces
def GetVersion(self, request: GetVersionRequest, context) -> GetVersionReply:
del context # Unused
del request # Unused
logger.debug("GetVersion()")
return GetVersionReply(
service_version=__version__,
compiler_version=self.compilation_session_type.compiler_version,
)
def GetSpaces(self, request: GetSpacesRequest, context) -> GetSpacesReply:
del request # Unused
logger.debug("GetSpaces()")
with exception_to_grpc_status(context):
return GetSpacesReply(
action_space_list=self.action_spaces,
observation_space_list=self.observation_spaces,
)
def StartSession(self, request: StartSessionRequest, context) -> StartSessionReply:
"""Create a new compilation session."""
logger.debug(
"StartSession(id=%d, benchmark=%s), %d active sessions",
self.next_session_id,
request.benchmark.uri,
len(self.sessions) + 1,
)
reply = StartSessionReply()
if not request.benchmark:
context.set_code(StatusCode.INVALID_ARGUMENT)
context.set_details("No benchmark URI set for StartSession()")
return reply
with self.sessions_lock, exception_to_grpc_status(context):
# If a benchmark definition was provided, add it.
if request.benchmark.HasField("program"):
self.benchmarks[request.benchmark.uri] = request.benchmark
# Lookup the requested benchmark.
if request.benchmark.uri not in self.benchmarks:
context.set_code(StatusCode.NOT_FOUND)
context.set_details("Benchmark not found")
return reply
session = self.compilation_session_type(
working_directory=self.working_directory,
action_space=self.action_spaces[request.action_space],
benchmark=self.benchmarks[request.benchmark.uri],
)
# Generate the initial observations.
reply.observation.extend(
[
session.get_observation(self.observation_spaces[obs])
for obs in request.observation_space
]
)
reply.session_id = self.next_session_id
self.sessions[reply.session_id] = session
self.next_session_id += 1
return reply
def ForkSession(self, request: ForkSessionRequest, context) -> ForkSessionReply:
logger.debug(
"ForkSession(id=%d), [%s]",
request.session_id,
self.next_session_id,
)
reply = ForkSessionReply()
with exception_to_grpc_status(context):
session = self.sessions[request.session_id]
self.sessions[reply.session_id] = session.fork()
reply.session_id = self.next_session_id
self.next_session_id += 1
return reply
def EndSession(self, request: EndSessionRequest, context) -> EndSessionReply:
del context # Unused
logger.debug(
"EndSession(id=%d), %d sessions remaining",
request.session_id,
len(self.sessions) - 1,
)
with self.sessions_lock:
if request.session_id in self.sessions:
del self.sessions[request.session_id]
return EndSessionReply(remaining_sessions=len(self.sessions))
def Step(self, request: StepRequest, context) -> StepReply:
logger.debug("Step()")
reply = StepReply()
if request.session_id not in self.sessions:
context.set_code(StatusCode.NOT_FOUND)
context.set_details(f"Session not found: {request.session_id}")
return reply
reply.action_had_no_effect = True
with exception_to_grpc_status(context):
session = self.sessions[request.session_id]
for action in request.action:
reply.end_of_session, nas, ahne = session.apply_action(action)
reply.action_had_no_effect &= ahne
if nas:
reply.new_action_space.CopyFrom(nas)
reply.observation.extend(
[
session.get_observation(self.observation_spaces[obs])
for obs in request.observation_space
]
)
return reply
def AddBenchmark(self, request: AddBenchmarkRequest, context) -> AddBenchmarkReply:
del context # Unused
reply = AddBenchmarkReply()
with self.sessions_lock:
for benchmark in request.benchmark:
self.benchmarks[benchmark.uri] = benchmark
return reply
def SendSessionParameter(
self, request: SendSessionParameterRequest, context
) -> SendSessionParameterReply:
reply = SendSessionParameterReply()
if request.session_id not in self.sessions:
context.set_code(StatusCode.NOT_FOUND)
context.set_details(f"Session not found: {request.session_id}")
return reply
session = self.sessions[request.session_id]
with exception_to_grpc_status(context):
for param in request.parameter:
# Handle each parameter in the session and generate a response.
message = session.handle_session_parameter(param.key, param.value)
# Use the builtin parameter handlers if not handled by a session.
if message is None:
message = self._handle_builtin_session_parameter(
param.key, param.value
)
if message is None:
context.set_code(StatusCode.INVALID_ARGUMENT)
context.set_details(f"Unknown parameter: {param.key}")
return reply
reply.reply.append(message)
return reply
def _handle_builtin_session_parameter(self, key: str, value: str) -> Optional[str]:
"""Handle a built-in session parameter.
:param key: The parameter key.
:param value: The parameter value.
:return: The response message, or :code:`None` if the key is not
understood.
"""
if key == "service.benchmark_cache.set_max_size_in_bytes":
self.benchmarks.set_max_size_in_bytes = int(value)
return value
elif key == "service.benchmark_cache.get_max_size_in_bytes":
return str(self.benchmarks.max_size_in_bytes)
elif key == "service.benchmark_cache.get_size_in_bytes":
return str(self.benchmarks.size_in_bytes)
return None
|
CompilerGym-development
|
compiler_gym/service/runtime/compiler_gym_service.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import compiler_gym.envs.loop_tool # noqa
from compiler_gym import config
from compiler_gym.envs.compiler_env import CompilerEnv
from compiler_gym.envs.gcc import GccEnv
if config.enable_llvm_env:
from compiler_gym.envs.llvm.llvm_env import LlvmEnv # noqa: F401
if config.enable_mlir_env:
from compiler_gym.envs.mlir.mlir_env import MlirEnv # noqa: F401
from compiler_gym.util.registration import COMPILER_GYM_ENVS
__all__ = [
"COMPILER_GYM_ENVS",
"CompilerEnv",
"GccEnv",
]
if config.enable_llvm_env:
__all__.append("LlvmEnv")
if config.enable_mlir_env:
__all__.append("MlirEnv")
|
CompilerGym-development
|
compiler_gym/envs/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines the OpenAI gym interface for compilers."""
from abc import ABC, abstractmethod
from typing import Iterable, List, Optional, Tuple, Union
import gym
from deprecated.sphinx import deprecated
from gym.spaces import Space
from compiler_gym.compiler_env_state import CompilerEnvState
from compiler_gym.datasets import Benchmark, BenchmarkUri, Dataset
from compiler_gym.spaces import ActionSpace, Reward
from compiler_gym.util.gym_type_hints import (
ActionType,
ObservationType,
OptionalArgumentValue,
StepType,
)
from compiler_gym.validation_result import ValidationResult
from compiler_gym.views import ObservationSpaceSpec, ObservationView, RewardView
class CompilerEnv(gym.Env, ABC):
"""An OpenAI gym environment for compiler optimizations.
The easiest way to create a CompilerGym environment is to call
:code:`gym.make()` on one of the registered environments:
>>> env = gym.make("llvm-v0")
See :code:`compiler_gym.COMPILER_GYM_ENVS` for a list of registered
environment names.
Alternatively, an environment can be constructed directly, such as by
connecting to a running compiler service at :code:`localhost:8080` (see
:doc:`this document </compiler_gym/service>` for more details):
>>> env = ClientServiceCompilerEnv(
... service="localhost:8080",
... observation_space="features",
... reward_space="runtime",
... rewards=[env_reward_spaces],
... )
Once constructed, an environment can be used in exactly the same way as a
regular :code:`gym.Env`, e.g.
>>> observation = env.reset()
>>> cumulative_reward = 0
>>> for i in range(100):
>>> action = env.action_space.sample()
>>> observation, reward, done, info = env.step(action)
>>> cumulative_reward += reward
>>> if done:
>>> break
>>> print(f"Reward after {i} steps: {cumulative_reward}")
Reward after 100 steps: -0.32123
"""
@abstractmethod
def __init__(self):
"""Construct an environment.
Do not construct an environment directly. Use :code:`gym.make()` on one
of the registered environments:
>>> with gym.make("llvm-v0") as env:
... pass # Use environment
"""
raise NotImplementedError("abstract class")
@abstractmethod
def close(self):
"""Close the environment.
Once closed, :func:`reset` must be called before the environment is used
again.
.. note::
You must make sure to call :code:`env.close()` on a CompilerGym
environment when you are done with it. This is needed to perform
manual tidying up of temporary files and processes. See :ref:`the
FAQ <faq:Do I need to call env.close()?>` for more details.
"""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def observation_space_spec(self) -> ObservationSpaceSpec:
raise NotImplementedError("abstract method")
@observation_space_spec.setter
@abstractmethod
def observation_space_spec(
self, observation_space_spec: Optional[ObservationSpaceSpec]
):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def reward_space_spec(self) -> Optional[Reward]:
raise NotImplementedError("abstract method")
@reward_space_spec.setter
@abstractmethod
def reward_space_spec(self, val: Optional[Reward]):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def benchmark(self) -> Benchmark:
"""Get or set the benchmark to use.
:getter: Get :class:`Benchmark <compiler_gym.datasets.Benchmark>` that
is currently in use.
:setter: Set the benchmark to use. Either a :class:`Benchmark
<compiler_gym.datasets.Benchmark>` instance, or the URI of a
benchmark as in :meth:`env.datasets.benchmark_uris()
<compiler_gym.datasets.Datasets.benchmark_uris>`.
.. note::
Setting a new benchmark has no effect until
:func:`env.reset() <compiler_gym.envs.CompilerEnv.reset>` is called.
"""
raise NotImplementedError("abstract method")
@benchmark.setter
@abstractmethod
def benchmark(self, benchmark: Optional[Union[str, Benchmark, BenchmarkUri]]):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def datasets(self) -> Iterable[Dataset]:
raise NotImplementedError("abstract method")
@datasets.setter
@abstractmethod
def datasets(self, datasets: Iterable[Dataset]):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def episode_walltime(self) -> float:
"""Return the amount of time in seconds since the last call to
:meth:`reset() <compiler_gym.envs.CompilerEnv.reset>`.
"""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def in_episode(self) -> bool:
"""Whether the service is ready for :func:`step` to be called,
i.e. :func:`reset` has been called and :func:`close` has not.
:return: :code:`True` if in an episode, else :code:`False`.
"""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def episode_reward(self) -> Optional[float]:
"""If :func:`CompilerEnv.reward_space
<compiler_gym.envs.CompilerGym.reward_space>` is set, this value is the
sum of all rewards for the current episode.
"""
raise NotImplementedError("abstract method")
@episode_reward.setter
@abstractmethod
def episode_reward(self, episode_reward: Optional[float]):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def actions(self) -> List[ActionType]:
raise NotImplementedError("abstract method")
@property
@abstractmethod
def version(self) -> str:
"""The version string of the compiler service."""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def compiler_version(self) -> str:
"""The version string of the underlying compiler that this service supports."""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def state(self) -> CompilerEnvState:
"""The tuple representation of the current environment state."""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def action_space(self) -> ActionSpace:
"""The current action space.
:getter: Get the current action space.
:setter: Set the action space to use. Must be an entry in
:code:`action_spaces`. If :code:`None`, the default action space is
selected.
"""
raise NotImplementedError("abstract method")
@action_space.setter
@abstractmethod
def action_space(self, action_space: Optional[str]):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def action_spaces(self) -> List[ActionSpace]:
"""A list of supported action space names."""
raise NotImplementedError("abstract method")
@action_spaces.setter
@abstractmethod
def action_spaces(self, action_spaces: List[str]):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def reward_space(self) -> Optional[Reward]:
"""The default reward space that is used to return a reward value from
:func:`~step()`.
:getter: Returns a :class:`Reward <compiler_gym.spaces.Reward>`,
or :code:`None` if not set.
:setter: Set the default reward space.
"""
raise NotImplementedError("abstract method")
@reward_space.setter
@abstractmethod
def reward_space(self, reward_space: Optional[Union[str, Reward]]) -> None:
raise NotImplementedError("abstract method")
@property
@abstractmethod
def observation_space(self) -> Optional[Space]:
"""The observation space that is used to return an observation value in
:func:`~step()`.
:getter: Returns the underlying observation space, or :code:`None` if
not set.
:setter: Set the default observation space.
"""
raise NotImplementedError("abstract method")
@observation_space.setter
@abstractmethod
def observation_space(
self, observation_space: Optional[Union[str, ObservationSpaceSpec]]
) -> None:
raise NotImplementedError("abstract method")
@property
@abstractmethod
def observation(self) -> ObservationView:
"""A view of the available observation spaces that permits
on-demand computation of observations.
"""
raise NotImplementedError("abstract method")
@observation.setter
@abstractmethod
def observation(self, observation: ObservationView) -> None:
raise NotImplementedError("abstract method")
@property
@abstractmethod
def reward_range(self) -> Tuple[float, float]:
"""A tuple indicating the range of reward values.
Default range is (-inf, +inf).
"""
raise NotImplementedError("abstract method")
@property
@abstractmethod
def reward(self) -> RewardView:
"""A view of the available reward spaces that permits on-demand
computation of rewards.
"""
raise NotImplementedError("abstract method")
@reward.setter
@abstractmethod
def reward(self, reward: RewardView) -> None:
raise NotImplementedError("abstract method")
@abstractmethod
def fork(self) -> "CompilerEnv":
"""Fork a new environment with exactly the same state.
This creates a duplicate environment instance with the current state.
The new environment is entirely independently of the source environment.
The user must call :meth:`close() <compiler_gym.envs.CompilerEnv.close>`
on the original and new environments.
If not already in an episode, :meth:`reset()
<compiler_gym.envs.CompilerEnv.reset>` is called.
Example usage:
>>> env = gym.make("llvm-v0")
>>> env.reset()
# ... use env
>>> new_env = env.fork()
>>> new_env.state == env.state
True
>>> new_env.step(1) == env.step(1)
True
.. note::
The client/service implementation of CompilerGym means that the
forked and base environments share a common backend resource. This
means that if either of them crash, such as due to a compiler
assertion, both environments must be reset.
:return: A new environment instance.
"""
raise NotImplementedError("abstract method")
@abstractmethod
def reset( # pylint: disable=arguments-differ
self,
benchmark: Optional[Union[str, Benchmark]] = None,
action_space: Optional[str] = None,
observation_space: Union[
OptionalArgumentValue, str, ObservationSpaceSpec
] = OptionalArgumentValue.UNCHANGED,
reward_space: Union[
OptionalArgumentValue, str, Reward
] = OptionalArgumentValue.UNCHANGED,
timeout: float = 300,
) -> Optional[ObservationType]:
"""Reset the environment state.
This method must be called before :func:`step()`.
:param benchmark: The name of the benchmark to use. If provided, it
overrides any value that was set during :func:`__init__`, and
becomes subsequent calls to :code:`reset()` will use this benchmark.
If no benchmark is provided, and no benchmark was provided to
:func:`__init___`, the service will randomly select a benchmark to
use.
:param action_space: The name of the action space to use. If provided,
it overrides any value that set during :func:`__init__`, and
subsequent calls to :code:`reset()` will use this action space. If
no action space is provided, the default action space is used.
:param observation_space: Compute and return observations at each
:func:`step()` from this space. Accepts a string name or an
:class:`ObservationSpaceSpec
<compiler_gym.views.ObservationSpaceSpec>`. If :code:`None`,
:func:`step()` returns :code:`None` for the observation value. If
:code:`OptionalArgumentValue.UNCHANGED` (the default value), the
observation space remains unchanged from the previous episode. For
available spaces, see :class:`env.observation.spaces
<compiler_gym.views.ObservationView>`.
:param reward_space: Compute and return reward at each :func:`step()`
from this space. Accepts a string name or a :class:`Reward
<compiler_gym.spaces.Reward>`. If :code:`None`, :func:`step()`
returns :code:`None` for the reward value. If
:code:`OptionalArgumentValue.UNCHANGED` (the default value), the
observation space remains unchanged from the previous episode. For
available spaces, see :class:`env.reward.spaces
<compiler_gym.views.RewardView>`.
:param timeout: The maximum number of seconds to wait for reset to
succeed.
:return: The initial observation.
:raises BenchmarkInitError: If the benchmark is invalid. This can happen
if the benchmark contains code that the compiler does not support,
or because of some internal error within the compiler. In this case,
another benchmark must be used.
:raises TypeError: If no benchmark has been set, and the environment
does not have a default benchmark to select from.
"""
raise NotImplementedError("abstract method")
@abstractmethod
def step(
self,
action: ActionType,
observation_spaces: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
reward_spaces: Optional[Iterable[Union[str, Reward]]] = None,
observations: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
rewards: Optional[Iterable[Union[str, Reward]]] = None,
timeout: float = 300,
) -> StepType:
"""Take a step.
:param action: An action.
:param observation_spaces: A list of observation spaces to compute
observations from. If provided, this changes the :code:`observation`
element of the return tuple to be a list of observations from the
requested spaces. The default :code:`env.observation_space` is not
returned.
:param reward_spaces: A list of reward spaces to compute rewards from.
If provided, this changes the :code:`reward` element of the return
tuple to be a list of rewards from the requested spaces. The default
:code:`env.reward_space` is not returned.
:param timeout: The maximum number of seconds to wait for the step to
succeed. Accepts a float value. The default is 300 seconds.
:return: A tuple of observation, reward, done, and info. Observation and
reward are None if default observation/reward is not set.
"""
raise NotImplementedError("abstract method")
@abstractmethod
def multistep(
self,
actions: Iterable[ActionType],
observation_spaces: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
reward_spaces: Optional[Iterable[Union[str, Reward]]] = None,
observations: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
rewards: Optional[Iterable[Union[str, Reward]]] = None,
timeout: float = 300,
):
"""Take a sequence of steps and return the final observation and reward.
:param action: A sequence of actions to apply in order.
:param observation_spaces: A list of observation spaces to compute
observations from. If provided, this changes the :code:`observation`
element of the return tuple to be a list of observations from the
requested spaces. The default :code:`env.observation_space` is not
returned.
:param reward_spaces: A list of reward spaces to compute rewards from.
If provided, this changes the :code:`reward` element of the return
tuple to be a list of rewards from the requested spaces. The default
:code:`env.reward_space` is not returned.
:param timeout: The maximum number of seconds to wait for the steps to
succeed. Accepts a float value. The default is 300 seconds.
:return: A tuple of observation, reward, done, and info. Observation and
reward are None if default observation/reward is not set.
"""
raise NotImplementedError("abstract method")
@abstractmethod
def render(
self,
mode="human",
) -> Optional[str]:
"""Render the environment.
:param mode: The render mode to use.
:raises TypeError: If a default observation space is not set, or if the
requested render mode does not exist.
"""
raise NotImplementedError("abstract method")
@deprecated(
version="0.2.5", reason="Use env.action_space.to_string(env.actions) instead"
)
def commandline(self) -> str:
"""Interface for :class:`CompilerEnv <compiler_gym.envs.CompilerEnv>`
subclasses to provide an equivalent commandline invocation to the
current environment state.
See also :meth:`commandline_to_actions()
<compiler_gym.envs.CompilerEnv.commandline_to_actions>`.
:return: A string commandline invocation.
"""
raise NotImplementedError("abstract method")
@deprecated(
version="0.2.5", reason='Use env.action_space.from_string("...") instead'
)
def commandline_to_actions(self, commandline: str) -> List[ActionType]:
"""Interface for :class:`CompilerEnv <compiler_gym.envs.CompilerEnv>`
subclasses to convert from a commandline invocation to a sequence of
actions.
See also :meth:`commandline()
<compiler_gym.envs.CompilerEnv.commandline>`.
:return: A list of actions.
"""
raise NotImplementedError("abstract method")
@abstractmethod
def apply(self, state: CompilerEnvState) -> None: # noqa
"""Replay this state on the given environment.
:param state: A :class:`CompilerEnvState <compiler_gym.CompilerEnvState>`
instance.
:raises ValueError: If this state cannot be applied.
"""
raise NotImplementedError("abstract method")
@abstractmethod
def validate(self, state: Optional[CompilerEnvState] = None) -> ValidationResult:
"""Validate an environment's state.
:param state: A state to environment. If not provided, the current state
is validated.
:returns: A :class:`ValidationResult <compiler_gym.ValidationResult>`.
"""
raise NotImplementedError("abstract method")
|
CompilerGym-development
|
compiler_gym/envs/compiler_env.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Register the loop_tool environment and reward."""
from pathlib import Path
from typing import Iterable
from compiler_gym.datasets import Benchmark, Dataset, benchmark
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.spaces import Reward
from compiler_gym.util.registration import register
from compiler_gym.util.runfiles_path import runfiles_path
LOOP_TOOL_SERVICE_BINARY: Path = runfiles_path(
"compiler_gym/envs/loop_tool/service/compiler_gym-loop_tool-service"
)
class FLOPSReward(Reward):
"""
`loop_tool` uses "floating point operations per second"
as its default reward space.
"""
def __init__(self):
super().__init__(
name="flops",
observation_spaces=["flops"],
default_value=0,
default_negates_returns=True,
deterministic=False,
platform_dependent=True,
)
self.previous_flops = None
def reset(self, benchmark: str, observation_view):
del benchmark # unused
self.previous_flops = observation_view["flops"]
def update(self, action, observations, observation_view):
del action
del observation_view
if self.previous_flops is None:
self.previous_flops = observations[0]
return self.previous_flops
reward = float(observations[0] - self.previous_flops)
self.previous_flops = observations[0]
return reward
class LoopToolCUDADataset(Dataset):
def __init__(self, *args, **kwargs):
super().__init__(
name="benchmark://loop_tool-cuda-v0",
license="MIT",
description="loop_tool dataset",
)
def benchmark_uris(self) -> Iterable[str]:
return (f"loop_tool-cuda-v0/{i}" for i in range(1, 1024 * 1024 * 8))
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
return Benchmark(proto=benchmark.BenchmarkProto(uri=str(uri)))
class LoopToolCPUDataset(Dataset):
def __init__(self, *args, **kwargs):
super().__init__(
name="benchmark://loop_tool-cpu-v0",
license="MIT",
description="loop_tool dataset",
)
def benchmark_uris(self) -> Iterable[str]:
return (f"loop_tool-cpu-v0/{i}" for i in range(1, 1024 * 1024 * 8))
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
return Benchmark(proto=benchmark.BenchmarkProto(uri=str(uri)))
register(
id="loop_tool-v0",
entry_point="compiler_gym.service.client_service_compiler_env:ClientServiceCompilerEnv",
kwargs={
"datasets": [LoopToolCPUDataset(), LoopToolCUDADataset()],
"observation_space": "action_state",
"reward_space": "flops",
"rewards": [FLOPSReward()],
"service": LOOP_TOOL_SERVICE_BINARY,
},
)
|
CompilerGym-development
|
compiler_gym/envs/loop_tool/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Define the loop_tool environment."""
import logging
import time
from functools import reduce
from pathlib import Path
from typing import Optional, Tuple
import loop_tool_py as lt
import numpy as np
import pkg_resources
from compiler_gym.errors import EnvironmentNotSupported
from compiler_gym.service import CompilationSession
from compiler_gym.service.proto import (
ActionSpace,
Benchmark,
DoubleRange,
Event,
Int64Box,
Int64Range,
Int64Tensor,
NamedDiscreteSpace,
ObservationSpace,
Space,
StringSpace,
)
logger = logging.getLogger(__name__)
class LoopToolCompilationSession(CompilationSession):
"""Represents an instance of an interactive loop_tool session."""
compiler_version: str = pkg_resources.get_distribution("loop-tool-py").version
# keep it simple for now: 1 variable, 1 nest
action_spaces = [
ActionSpace(
name="simple",
space=Space(
# shift around a single pre-split order, changing the size of splits
named_discrete=NamedDiscreteSpace(
name=["toggle_mode", "up", "down", "toggle_thread"],
),
),
),
ActionSpace(
name="split",
space=Space(
# potentially define new splits
named_discrete=NamedDiscreteSpace(
name=["toggle_mode", "up", "down", "toggle_thread", "split"],
),
),
),
]
observation_spaces = [
ObservationSpace(
name="flops",
space=Space(double_value=DoubleRange()),
deterministic=False,
platform_dependent=True,
default_observation=Event(
double_value=0,
),
),
ObservationSpace(
name="loop_tree",
space=Space(
string_value=StringSpace(length_range=Int64Range(min=0)),
),
deterministic=True,
platform_dependent=False,
default_observation=Event(
string_value="",
),
),
ObservationSpace(
name="action_state",
space=Space(
int64_box=Int64Box(
low=Int64Tensor(shape=[1], value=[0]),
high=Int64Tensor(shape=[1], value=[2**36]),
),
),
deterministic=True,
platform_dependent=False,
default_observation=Event(
int64_tensor=Int64Tensor(shape=[1], value=[0]),
),
),
]
def __init__(
self, working_directory: Path, action_space: ActionSpace, benchmark: Benchmark
):
super().__init__(working_directory, action_space, benchmark)
self.action_space = action_space
if "cuda" in benchmark.uri:
self.backend = "cuda"
lt.set_default_hardware("cuda")
else:
self.backend = "cpu"
if self.backend not in lt.backends():
raise EnvironmentNotSupported(
f"Failed to load {self.backend} dataset for loop_tool. Have you installed all required dependecies? See <https://facebookresearch.github.io/CompilerGym/envs/loop_tool.html#installation> for details. "
)
self.ir = lt.IR()
self.var = self.ir.create_var("a")
r0 = self.ir.create_node("read", [], [self.var])
r1 = self.ir.create_node("read", [], [self.var])
add = self.ir.create_node("add", [r0, r1], [self.var])
w = self.ir.create_node("write", [add], [self.var])
self.ir.set_inputs([r0, r1])
self.ir.set_outputs([w])
self.size = int(benchmark.uri.split("/")[-1])
self.Ap = np.random.randn(self.size)
self.Bp = np.random.randn(self.size)
self.order = [(self.size, 0), (1, 0), (1, 0)]
self.thread = [1, 0, 0]
self.cursor = 0
self.mode = "size"
logger.info("Started a compilation session for %s", benchmark.uri)
def resize(self, increment):
"""
The idea is pull from or add to the parent loop.
Three mutations possible to any size:
A) x, y -> x + 1, 0
remove the tail, increase loop size, shrink parent
B) x, y -> x, 0
only remove the tail, add to parent
C) x, 0 -> x - 1, 0
if no tail, shrink the loop size, increase parent
note: this means tails can never exist on innermost loops. this makes good sense :)
A)
[(a, b), (x, y), ...k] -> [(a', b'), (x + 1, 0), ...k]
a * (x * k + y) + b = a' * (x + 1) * k + b'
a' = (a * (x * k + y) + b) // ((x + 1) * k)
b' = " " % " "
B)
[(a, b), (x, y), ...k] -> [(a', b'), (x, 0), ...k]
a * (x * k + y) + b = a' * (x) * k + b'
a' = (a * (x * k + y) + b) // ((x) * k)
b' = " " % " "
C)
[(a, b), (x, y), ...k] -> [(a', b'), (x - 1, 0), ...k]
a * (x * k + y) + b = a' * (x - 1) * k + b'
a' = (a * (x * k + y) + b) // ((x - 1) * k)
b' = " " % " "
example interaction model:
1. cursor = 1 [1024, 1, 1]
2. up [512, 2, 1]
3. up [(341,1), 3, 1]
4. up [256, 4, 1]
5. cursor = 2, up [256, 2, 2]
6. up [256, (1, 1), 3]
7. cursor = 1, down [(341, 1), 1, 3]
8. cursor = 2, down [(341, 1), (1, 1), 2]
9. cursor = 1, down [512, 1, 2]"""
if self.cursor == 0:
return
parent_size = self.order[self.cursor - 1]
a = parent_size[0]
b = parent_size[1]
size = self.order[self.cursor]
x = size[0]
y = size[1]
def lam(v, x):
return v * x[0] + x[1]
k = reduce(lam, self.order[self.cursor + 1 :][::-1], 1)
if increment == -1 and y:
increment = 0
if (x + increment) < 1:
return
if (x + increment) > self.size:
return
n = a * x * k + b
d = (x + increment) * k
a_ = n // d
b_ = n % d
if a_ < 1:
return
if a_ > self.size:
return
self.order[self.cursor - 1] = (a_, b_)
self.order[self.cursor] = (x + increment, 0)
end_size = reduce(lam, self.order[::-1], 1)
assert (
end_size == self.size
), f"{end_size} != {self.size} ({a}, {b}), ({x}, {y}) -> ({a_}, {b_}), ({x + increment}, 0)"
def apply_action(self, action: Event) -> Tuple[bool, Optional[ActionSpace], bool]:
if not action.HasField("int64_value"):
raise ValueError("Invalid action. int64_value expected.")
choice_index = action.int64_value
if choice_index < 0 or choice_index >= len(
self.action_space.space.named_discrete.name
):
raise ValueError("Out-of-range")
logger.info("Applied action %d", choice_index)
act = self.action_space.space.named_discrete.name[choice_index]
if self.mode not in ["size", "select"]:
raise RuntimeError("Invalid mode set: {}".format(self.mode))
if act == "toggle_mode":
if self.mode == "size":
self.mode = "select"
elif self.mode == "select":
self.mode = "size"
if act == "toggle_thread":
self.thread[self.cursor] = not self.thread[self.cursor]
if act == "down":
# always loop around
if self.mode == "size":
self.resize(-1)
elif self.mode == "select":
next_cursor = (self.cursor - 1) % len(self.order)
self.cursor = next_cursor
if act == "up":
# always loop around
if self.mode == "size":
self.resize(1)
elif self.mode == "select":
next_cursor = (self.cursor + 1) % len(self.order)
self.cursor = next_cursor
return False, None, False
def lower(self):
for n in self.ir.nodes:
o = [(self.var, k) for k in self.order]
self.ir.set_order(n, o)
# always disable innermost
self.ir.disable_reuse(n, len(o) - 1)
loop_tree = lt.LoopTree(self.ir)
parallel = set()
t = loop_tree.roots[0]
for b in self.thread:
if b:
parallel.add(t)
if self.backend == "cpu":
loop_tree.annotate(t, "cpu_parallel")
t = loop_tree.children(t)[0]
return loop_tree, parallel
def flops(self):
loop_tree, parallel = self.lower()
if self.backend == "cuda":
c = lt.cuda(loop_tree, parallel)
else:
c = lt.cpu(loop_tree)
A = lt.Tensor(self.size)
B = lt.Tensor(self.size)
C = lt.Tensor(self.size)
A.set(self.Ap)
B.set(self.Bp)
iters = 1000
warmup = 50
for i in range(warmup):
c([A, B, C])
t = time.time()
for i in range(iters - 1):
c([A, B, C], False)
c([A, B, C])
t_ = time.time()
flops = self.size * iters / (t_ - t) / 1e9
return flops
def get_observation(self, observation_space: ObservationSpace) -> Event:
if observation_space.name == "action_state":
# cursor, (size, tail)
o = self.order[self.cursor]
return Event(
int64_tensor=Int64Tensor(shape=[3], value=[self.cursor, o[0], o[1]])
)
elif observation_space.name == "flops":
return Event(double_value=self.flops())
elif observation_space.name == "loop_tree":
loop_tree, parallel = self.lower()
return Event(
string_value=loop_tree.dump(
lambda x: "[thread]" if x in parallel else ""
)
)
else:
raise KeyError(observation_space.name)
|
CompilerGym-development
|
compiler_gym/envs/loop_tool/service/loop_tool_compilation_session.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
class observation_spaces(Enum):
Ir = "Ir"
IrSha1 = "IrSha1"
Bitcode = "Bitcode"
BitcodeFile = "BitcodeFile"
InstCount = "InstCount"
Autophase = "Autophase"
Programl = "Programl"
ProgramlJson = "ProgramlJson"
CpuInfo = "CpuInfo"
IrInstructionCount = "IrInstructionCount"
IrInstructionCountO0 = "IrInstructionCountO0"
IrInstructionCountO3 = "IrInstructionCountO3"
IrInstructionCountOz = "IrInstructionCountOz"
ObjectTextSizeBytes = "ObjectTextSizeBytes"
ObjectTextSizeO0 = "ObjectTextSizeO0"
ObjectTextSizeO3 = "ObjectTextSizeO3"
ObjectTextSizeOz = "ObjectTextSizeOz"
TextSizeBytes = "TextSizeBytes"
TextSizeO0 = "TextSizeO0"
TextSizeO3 = "TextSizeO3"
TextSizeOz = "TextSizeOz"
IsBuildable = "IsBuildable"
IsRunnable = "IsRunnable"
Runtime = "Runtime"
Buildtime = "Buildtime"
Inst2vecPreprocessedText = "Inst2vecPreprocessedText"
Inst2vecEmbeddingIndices = "Inst2vecEmbeddingIndices"
Inst2vec = "Inst2vec"
InstCountDict = "InstCountDict"
InstCountNorm = "InstCountNorm"
InstCountNormDict = "InstCountNormDict"
AutophaseDict = "AutophaseDict"
LexedIr = "LexedIr"
class reward_spaces(Enum):
IrInstructionCount = "IrInstructionCount"
IrInstructionCountNorm = "IrInstructionCountNorm"
IrInstructionCountO3 = "IrInstructionCountO3"
IrInstructionCountOz = "IrInstructionCountOz"
ObjectTextSizeBytes = "ObjectTextSizeBytes"
ObjectTextSizeNorm = "ObjectTextSizeNorm"
ObjectTextSizeO3 = "ObjectTextSizeO3"
ObjectTextSizeOz = "ObjectTextSizeOz"
TextSizeBytes = "TextSizeBytes"
TextSizeNorm = "TextSizeNorm"
TextSizeO3 = "TextSizeO3"
TextSizeOz = "TextSizeOz"
class actions(Enum):
AddDiscriminators = "-add-discriminators"
Adce = "-adce"
AggressiveInstcombine = "-aggressive-instcombine"
AlignmentFromAssumptions = "-alignment-from-assumptions"
AlwaysInline = "-always-inline"
Argpromotion = "-argpromotion"
Attributor = "-attributor"
Barrier = "-barrier"
Bdce = "-bdce"
BreakCritEdges = "-break-crit-edges"
Simplifycfg = "-simplifycfg"
CallsiteSplitting = "-callsite-splitting"
CalledValuePropagation = "-called-value-propagation"
CanonicalizeAliases = "-canonicalize-aliases"
Consthoist = "-consthoist"
Constmerge = "-constmerge"
Constprop = "-constprop"
CoroCleanup = "-coro-cleanup"
CoroEarly = "-coro-early"
CoroElide = "-coro-elide"
CoroSplit = "-coro-split"
CorrelatedPropagation = "-correlated-propagation"
CrossDsoCfi = "-cross-dso-cfi"
Deadargelim = "-deadargelim"
Dce = "-dce"
Die = "-die"
Dse = "-dse"
Reg2mem = "-reg2mem"
DivRemPairs = "-div-rem-pairs"
EarlyCseMemssa = "-early-cse-memssa"
EarlyCse = "-early-cse"
ElimAvailExtern = "-elim-avail-extern"
EeInstrument = "-ee-instrument"
Flattencfg = "-flattencfg"
Float2int = "-float2int"
Forceattrs = "-forceattrs"
Inline = "-inline"
InsertGcovProfiling = "-insert-gcov-profiling"
GvnHoist = "-gvn-hoist"
Gvn = "-gvn"
Globaldce = "-globaldce"
Globalopt = "-globalopt"
Globalsplit = "-globalsplit"
GuardWidening = "-guard-widening"
Hotcoldsplit = "-hotcoldsplit"
Ipconstprop = "-ipconstprop"
Ipsccp = "-ipsccp"
Indvars = "-indvars"
Irce = "-irce"
InferAddressSpaces = "-infer-address-spaces"
Inferattrs = "-inferattrs"
InjectTliMappings = "-inject-tli-mappings"
Instsimplify = "-instsimplify"
Instcombine = "-instcombine"
Instnamer = "-instnamer"
JumpThreading = "-jump-threading"
Lcssa = "-lcssa"
Licm = "-licm"
LibcallsShrinkwrap = "-libcalls-shrinkwrap"
LoadStoreVectorizer = "-load-store-vectorizer"
LoopDataPrefetch = "-loop-data-prefetch"
LoopDeletion = "-loop-deletion"
LoopDistribute = "-loop-distribute"
LoopFusion = "-loop-fusion"
LoopGuardWidening = "-loop-guard-widening"
LoopIdiom = "-loop-idiom"
LoopInstsimplify = "-loop-instsimplify"
LoopInterchange = "-loop-interchange"
LoopLoadElim = "-loop-load-elim"
LoopPredication = "-loop-predication"
LoopReroll = "-loop-reroll"
LoopRotate = "-loop-rotate"
LoopSimplifycfg = "-loop-simplifycfg"
LoopSimplify = "-loop-simplify"
LoopSink = "-loop-sink"
LoopReduce = "-loop-reduce"
LoopUnrollAndJam = "-loop-unroll-and-jam"
LoopUnroll = "-loop-unroll"
LoopUnswitch = "-loop-unswitch"
LoopVectorize = "-loop-vectorize"
LoopVersioningLicm = "-loop-versioning-licm"
LoopVersioning = "-loop-versioning"
Loweratomic = "-loweratomic"
LowerConstantIntrinsics = "-lower-constant-intrinsics"
LowerExpect = "-lower-expect"
LowerGuardIntrinsic = "-lower-guard-intrinsic"
Lowerinvoke = "-lowerinvoke"
LowerMatrixIntrinsics = "-lower-matrix-intrinsics"
Lowerswitch = "-lowerswitch"
LowerWidenableCondition = "-lower-widenable-condition"
Memcpyopt = "-memcpyopt"
Mergefunc = "-mergefunc"
Mergeicmps = "-mergeicmps"
MldstMotion = "-mldst-motion"
Sancov = "-sancov"
NameAnonGlobals = "-name-anon-globals"
NaryReassociate = "-nary-reassociate"
Newgvn = "-newgvn"
PgoMemopOpt = "-pgo-memop-opt"
PartialInliner = "-partial-inliner"
PartiallyInlineLibcalls = "-partially-inline-libcalls"
PostInlineEeInstrument = "-post-inline-ee-instrument"
Functionattrs = "-functionattrs"
Mem2reg = "-mem2reg"
PruneEh = "-prune-eh"
Reassociate = "-reassociate"
RedundantDbgInstElim = "-redundant-dbg-inst-elim"
RpoFunctionattrs = "-rpo-functionattrs"
RewriteStatepointsForGc = "-rewrite-statepoints-for-gc"
Sccp = "-sccp"
SlpVectorizer = "-slp-vectorizer"
Sroa = "-sroa"
Scalarizer = "-scalarizer"
SeparateConstOffsetFromGep = "-separate-const-offset-from-gep"
SimpleLoopUnswitch = "-simple-loop-unswitch"
Sink = "-sink"
SpeculativeExecution = "-speculative-execution"
Slsr = "-slsr"
StripDeadPrototypes = "-strip-dead-prototypes"
StripDebugDeclare = "-strip-debug-declare"
StripNondebug = "-strip-nondebug"
Strip = "-strip"
Tailcallelim = "-tailcallelim"
Mergereturn = "-mergereturn"
class action_descriptions(Enum):
AddDiscriminators = "Add DWARF path discriminators"
Adce = "Aggressive Dead Code Elimination"
AggressiveInstcombine = "Combine pattern based expressions"
AlignmentFromAssumptions = "Alignment from assumptions"
AlwaysInline = "Inliner for always_inline functions"
Argpromotion = "Promote 'by reference' arguments to scalars"
Attributor = "Deduce and propagate attributes"
Barrier = "A No-Op Barrier Pass"
Bdce = "Bit-Tracking Dead Code Elimination"
BreakCritEdges = "Break critical edges in CFG"
Simplifycfg = "Simplify the CFG"
CallsiteSplitting = "Call-site splitting"
CalledValuePropagation = "Called Value Propagation"
CanonicalizeAliases = "Canonicalize aliases"
Consthoist = "Constant Hoisting"
Constmerge = "Merge Duplicate Global Constants"
Constprop = "Simple constant propagation"
CoroCleanup = "Lower all coroutine related intrinsics"
CoroEarly = "Lower early coroutine intrinsics"
CoroElide = "Coroutine frame allocation elision and indirect calls replacement"
CoroSplit = "Split coroutine into a set of functions driving its state machine"
CorrelatedPropagation = "Value Propagation"
CrossDsoCfi = "Cross-DSO CFI"
Deadargelim = "Dead Argument Elimination"
Dce = "Dead Code Elimination"
Die = "Dead Instruction Elimination"
Dse = "Dead Store Elimination"
Reg2mem = "Demote all values to stack slots"
DivRemPairs = "Hoist/decompose integer division and remainder"
EarlyCseMemssa = "Early CSE w/ MemorySSA"
EarlyCse = "Early CSE"
ElimAvailExtern = "Eliminate Available Externally Globals"
EeInstrument = (
"Instrument function entry/exit with calls to e.g. mcount()(pre inlining)"
)
Flattencfg = "Flatten the CFG"
Float2int = "Float to int"
Forceattrs = "Force set function attributes"
Inline = "Function Integration/Inlining"
InsertGcovProfiling = "Insert instrumentation for GCOV profiling"
GvnHoist = "Early GVN Hoisting of Expressions"
Gvn = "Global Value Numbering"
Globaldce = "Dead Global Elimination"
Globalopt = "Global Variable Optimizer"
Globalsplit = "Global splitter"
GuardWidening = "Widen guards"
Hotcoldsplit = "Hot Cold Splitting"
Ipconstprop = "Interprocedural constant propagation"
Ipsccp = "Interprocedural Sparse Conditional Constant Propagation"
Indvars = "Induction Variable Simplification"
Irce = "Inductive range check elimination"
InferAddressSpaces = "Infer address spaces"
Inferattrs = "Infer set function attributes"
InjectTliMappings = "Inject TLI Mappings"
Instsimplify = "Remove redundant instructions"
Instcombine = "Combine redundant instructions"
Instnamer = "Assign names to anonymous instructions"
JumpThreading = "Jump Threading"
Lcssa = "Loop-Closed SSA Form Pass"
Licm = "Loop Invariant Code Motion"
LibcallsShrinkwrap = "Conditionally eliminate dead library calls"
LoadStoreVectorizer = "Vectorize load and Store instructions"
LoopDataPrefetch = "Loop Data Prefetch"
LoopDeletion = "Delete dead loops"
LoopDistribute = "Loop Distribution"
LoopFusion = "Loop Fusion"
LoopGuardWidening = "Widen guards (within a single loop, as a loop pass)"
LoopIdiom = "Recognize loop idioms"
LoopInstsimplify = "Simplify instructions in loops"
LoopInterchange = "Interchanges loops for cache reuse"
LoopLoadElim = "Loop Load Elimination"
LoopPredication = "Loop predication"
LoopReroll = "Reroll loops"
LoopRotate = "Rotate Loops"
LoopSimplifycfg = "Simplify loop CFG"
LoopSimplify = "Canonicalize natural loops"
LoopSink = "Loop Sink"
LoopReduce = "Loop Strength Reduction"
LoopUnrollAndJam = "Unroll and Jam loops"
LoopUnroll = "Unroll loops"
LoopUnswitch = "Unswitch loops"
LoopVectorize = "Loop Vectorization"
LoopVersioningLicm = "Loop Versioning For LICM"
LoopVersioning = "Loop Versioning"
Loweratomic = "Lower atomic intrinsics to non-atomic form"
LowerConstantIntrinsics = "Lower constant intrinsics"
LowerExpect = "Lower 'expect' Intrinsics"
LowerGuardIntrinsic = "Lower the guard intrinsic to normal control flow"
Lowerinvoke = "Lower invoke and unwind, for unwindless code generators"
LowerMatrixIntrinsics = "Lower the matrix intrinsics"
Lowerswitch = "Lower SwitchInst's to branches"
LowerWidenableCondition = "Lower the widenable condition to default true value"
Memcpyopt = "MemCpy Optimization"
Mergefunc = "Merge Functions"
Mergeicmps = "Merge contiguous icmps into a memcmp"
MldstMotion = "MergedLoadStoreMotion"
Sancov = "Pass for instrumenting coverage on functions"
NameAnonGlobals = "Provide a name to nameless globals"
NaryReassociate = "Nary reassociation"
Newgvn = "Global Value Numbering"
PgoMemopOpt = "Optimize memory intrinsic using its size value profile"
PartialInliner = "Partial Inliner"
PartiallyInlineLibcalls = "Partially inline calls to library functions"
PostInlineEeInstrument = (
"Instrument function entry/exit with calls to e.g. mcount()(post inlining)"
)
Functionattrs = "Deduce function attributes"
Mem2reg = "Promote Memory to Register"
PruneEh = "Remove unused exception handling info"
Reassociate = "Reassociate expressions"
RedundantDbgInstElim = "Redundant Dbg Instruction Elimination"
RpoFunctionattrs = "Deduce function attributes in RPO"
RewriteStatepointsForGc = "Make relocations explicit at statepoints"
Sccp = "Sparse Conditional Constant Propagation"
SlpVectorizer = "SLP Vectorizer"
Sroa = "Scalar Replacement Of Aggregates"
Scalarizer = "Scalarize vector operations"
SeparateConstOffsetFromGep = (
"Split GEPs to a variadic base and a constant offset for better CSE"
)
SimpleLoopUnswitch = "Simple unswitch loops"
Sink = "Code sinking"
SpeculativeExecution = "Speculatively execute instructions"
Slsr = "Straight line strength reduction"
StripDeadPrototypes = "Strip Unused Function Prototypes"
StripDebugDeclare = "Strip all llvm.dbg.declare intrinsics"
StripNondebug = "Strip all symbols, except dbg symbols, from a module"
Strip = "Strip all symbols from a module"
Tailcallelim = "Tail Call Elimination"
Mergereturn = "Unify function exit nodes"
|
CompilerGym-development
|
compiler_gym/envs/llvm/specs.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines reward spaces used by the LLVM environment."""
from typing import List, Optional
from compiler_gym.datasets import Benchmark
from compiler_gym.spaces.reward import Reward
from compiler_gym.util.gym_type_hints import ActionType, ObservationType, RewardType
from compiler_gym.views.observation import ObservationView
class CostFunctionReward(Reward):
"""A reward function that uses a scalar observation space as a cost
function.
"""
def __init__(self, cost_function: str, init_cost_function: str, **kwargs):
"""Constructor.
:param cost_function: The ID of the observation space used to produce
scalar costs.
:param init_cost_function: The ID of an observation space that produces
a scalar cost equivalent to cost_function before any actions are
made.
"""
super().__init__(observation_spaces=[cost_function], **kwargs)
self.cost_function: str = cost_function
self.init_cost_function: str = init_cost_function
self.previous_cost: Optional[ObservationType] = None
def reset(self, benchmark: Benchmark, observation_view: ObservationView) -> None:
"""Called on env.reset(). Reset incremental progress."""
del benchmark # unused
del observation_view # unused
self.previous_cost = None
def update(
self,
actions: List[ActionType],
observations: List[ObservationType],
observation_view: ObservationView,
) -> RewardType:
"""Called on env.step(). Compute and return new reward."""
del actions # unused
cost: RewardType = observations[0]
if self.previous_cost is None:
self.previous_cost = observation_view[self.init_cost_function]
reward = RewardType(self.previous_cost - cost)
self.previous_cost = cost
return reward
class NormalizedReward(CostFunctionReward):
"""A cost function reward that is normalized to the initial value."""
def __init__(self, **kwargs):
"""Constructor."""
super().__init__(**kwargs)
self.cost_norm: Optional[ObservationType] = None
self.benchmark: Benchmark = None
def reset(self, benchmark: str, observation_view: ObservationView) -> None:
"""Called on env.reset(). Reset incremental progress."""
super().reset(benchmark, observation_view)
# The benchmark has changed so we must compute a new cost normalization
# value. If the benchmark has not changed then the previously computed
# value is still valid.
if self.benchmark != benchmark:
self.cost_norm = None
self.benchmark = benchmark
def update(
self,
actions: List[ActionType],
observations: List[ObservationType],
observation_view: ObservationView,
) -> RewardType:
"""Called on env.step(). Compute and return new reward."""
if self.cost_norm is None:
self.cost_norm = self.get_cost_norm(observation_view)
return super().update(actions, observations, observation_view) / self.cost_norm
def get_cost_norm(self, observation_view: ObservationView) -> RewardType:
"""Return the value used to normalize costs."""
return observation_view[self.init_cost_function]
class BaselineImprovementNormalizedReward(NormalizedReward):
"""A cost function reward that is normalized to improvement made by a
baseline approach.
"""
def __init__(self, baseline_cost_function: str, **kwargs):
super().__init__(**kwargs)
self.baseline_cost_function: str = baseline_cost_function
def get_cost_norm(self, observation_view: ObservationView) -> RewardType:
"""Return the value used to normalize costs."""
init_cost = observation_view[self.init_cost_function]
baseline_cost = observation_view[self.baseline_cost_function]
return max(init_cost - baseline_cost, 1)
|
CompilerGym-development
|
compiler_gym/envs/llvm/llvm_rewards.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import subprocess
import tempfile
import urllib.parse
from compiler_gym.datasets import Benchmark, BenchmarkInitError
from compiler_gym.service.proto import Benchmark as BenchmarkProto
from compiler_gym.service.proto import File
from compiler_gym.third_party.gccinvocation.gccinvocation import GccInvocation
from compiler_gym.util.commands import Popen
from compiler_gym.util.runfiles_path import transient_cache_path
from compiler_gym.util.shell_format import join_cmd
logger = logging.getLogger(__name__)
class BenchmarkFromCommandLine(Benchmark):
"""A benchmark that has been constructed from a command line invocation.
See :meth:`env.make_benchmark_from_command_line()
<compiler_gym.envs.LlvmEnv.make_benchmark_from_command_line>`.
"""
def __init__(self, invocation: GccInvocation, bitcode: bytes, timeout: int):
uri = f"benchmark://clang-v0/{urllib.parse.quote_plus(join_cmd(invocation.original_argv))}"
super().__init__(
proto=BenchmarkProto(uri=str(uri), program=File(contents=bitcode))
)
self.command_line = invocation.original_argv
# Modify the commandline so that it takes the bitcode file as input.
#
# Strip the original sources from the build command, but leave any
# object file inputs.
sources = set(s for s in invocation.sources if not s.endswith(".o"))
build_command = [arg for arg in invocation.original_argv if arg not in sources]
# Convert any object file inputs to absolute paths since the backend
# service will have a different working directory.
#
# TODO(github.com/facebookresearch/CompilerGym/issues/325): To support
# distributed execution, we should embed the contents of these object
# files in the benchmark proto.
object_files = set(s for s in invocation.sources if s.endswith(".o"))
build_command = [
os.path.abspath(arg) if arg in object_files else arg
for arg in build_command
]
# Append the new source to the build command and specify the absolute path
# to the output.
for i in range(len(build_command) - 2, -1, -1):
if build_command[i] == "-o":
del build_command[i + 1]
del build_command[i]
build_command += ["-xir", "$IN", "-o", str(invocation.output_path)]
self.proto.dynamic_config.build_cmd.argument[:] = build_command
self.proto.dynamic_config.build_cmd.outfile[:] = [str(invocation.output_path)]
self.proto.dynamic_config.build_cmd.timeout_seconds = timeout
def compile(self, env, timeout: int = 60) -> None:
"""This completes the compilation and linking of the final executable
specified by the original command line.
"""
with tempfile.NamedTemporaryFile(
dir=transient_cache_path("."), prefix="benchmark-", suffix=".bc"
) as f:
bitcode_path = f.name
env.write_bitcode(bitcode_path)
# Set the placeholder for input path.
cmd = list(self.proto.dynamic_config.build_cmd.argument).copy()
cmd = [bitcode_path if c == "$IN" else c for c in cmd]
logger.debug(f"$ {join_cmd(cmd)}")
with Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) as lower:
stdout, _ = lower.communicate(timeout=timeout)
if lower.returncode:
raise BenchmarkInitError(
f"Failed to lower LLVM bitcode with error:\n"
f"{stdout.decode('utf-8').rstrip()}\n"
f"Running command: {join_cmd(cmd)}"
)
|
CompilerGym-development
|
compiler_gym/envs/llvm/benchmark_from_command_line.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from compiler_gym.spaces import ActionSpace
from compiler_gym.util.gym_type_hints import ActionType
class LlvmCommandLine(ActionSpace):
"""An action space for LLVM that supports serializing / deserializing to
opt command line.
"""
def to_string(self, actions: List[ActionType]) -> str:
"""Returns an LLVM :code:`opt` command line invocation for the given actions.
:param actions: A list of actions to serialize.
:returns: A command line string.
"""
return f"opt {self.wrapped.to_string(actions)} input.bc -o output.bc"
def from_string(self, string: str) -> List[ActionType]:
"""Returns a list of actions from the given command line.
:param commandline: A command line invocation.
:return: A list of actions.
:raises ValueError: In case the command line string is malformed.
"""
if string.startswith("opt "):
string = string[len("opt ") :]
if string.endswith(" input.bc -o output.bc"):
string = string[: -len(" input.bc -o output.bc")]
return self.wrapped.from_string(string)
|
CompilerGym-development
|
compiler_gym/envs/llvm/llvm_command_line.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Register the LLVM environments."""
import sys
from itertools import product
from compiler_gym.envs.llvm.benchmark_from_command_line import BenchmarkFromCommandLine
from compiler_gym.envs.llvm.compute_observation import compute_observation
from compiler_gym.envs.llvm.llvm_benchmark import (
ClangInvocation,
get_system_library_flags,
make_benchmark,
make_benchmark_from_source,
merge_benchmarks,
split_benchmark_by_function,
)
from compiler_gym.envs.llvm.llvm_command_line import LlvmCommandLine
from compiler_gym.envs.llvm.llvm_env import LlvmEnv
# TODO(github.com/facebookresearch/CompilerGym/issues/506): Tidy up.
if "compiler_gym.envs.llvm.is_making_specs" not in sys.modules:
from compiler_gym.envs.llvm.specs import observation_spaces, reward_spaces
from compiler_gym.util.registration import register
from compiler_gym.util.runfiles_path import runfiles_path
__all__ = [
"BenchmarkFromCommandLine",
"LlvmCommandLine",
"ClangInvocation",
"compute_observation",
"get_system_library_flags",
"LLVM_SERVICE_BINARY",
"LlvmEnv",
"make_benchmark",
"make_benchmark_from_source",
"merge_benchmarks",
"observation_spaces",
"reward_spaces",
"split_benchmark_by_function",
]
LLVM_SERVICE_BINARY = runfiles_path(
"compiler_gym/envs/llvm/service/compiler_gym-llvm-service"
)
def _register_llvm_gym_service():
"""Register an environment for each combination of LLVM
observation/reward/benchmark."""
observation_spaces = {"autophase": "Autophase", "ir": "Ir"}
reward_spaces = {"ic": "IrInstructionCountOz", "codesize": "ObjectTextSizeOz"}
register(
id="llvm-v0",
entry_point="compiler_gym.envs.llvm:LlvmEnv",
kwargs={
"service": LLVM_SERVICE_BINARY,
},
)
for reward_space in reward_spaces:
register(
id=f"llvm-{reward_space}-v0",
entry_point="compiler_gym.envs.llvm:LlvmEnv",
kwargs={
"service": LLVM_SERVICE_BINARY,
"reward_space": reward_spaces[reward_space],
},
)
for observation_space, reward_space in product(observation_spaces, reward_spaces):
register(
id=f"llvm-{observation_space}-{reward_space}-v0",
entry_point="compiler_gym.envs.llvm:LlvmEnv",
kwargs={
"service": LLVM_SERVICE_BINARY,
"observation_space": observation_spaces[observation_space],
"reward_space": reward_spaces[reward_space],
},
)
_register_llvm_gym_service()
|
CompilerGym-development
|
compiler_gym/envs/llvm/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines a utility function for computing LLVM observations."""
import subprocess
from pathlib import Path
from typing import List
import google.protobuf.text_format
from compiler_gym.service.proto import Event
from compiler_gym.util.commands import Popen
from compiler_gym.util.gym_type_hints import ObservationType
from compiler_gym.util.runfiles_path import runfiles_path
from compiler_gym.util.shell_format import plural
from compiler_gym.views.observation_space_spec import ObservationSpaceSpec
_COMPUTE_OBSERVATION_BIN = runfiles_path(
"compiler_gym/envs/llvm/service/compute_observation"
)
def pascal_case_to_enum(pascal_case: str) -> str:
"""Convert PascalCase to ENUM_CASE."""
word_arrays: List[List[str]] = [[]]
for c in pascal_case:
if c.isupper() and word_arrays[-1]:
word_arrays.append([c])
else:
word_arrays[-1].append(c.upper())
return "_".join(["".join(word) for word in word_arrays])
def compute_observation(
observation_space: ObservationSpaceSpec, bitcode: Path, timeout: float = 300
) -> ObservationType:
"""Compute an LLVM observation.
This is a utility function that uses a standalone C++ binary to compute an
observation from an LLVM bitcode file. It is intended for use cases where
you want to compute an observation without the overhead of initializing a
full environment.
Example usage:
>>> env = compiler_gym.make("llvm-v0")
>>> space = env.observation.spaces["Ir"]
>>> bitcode = Path("bitcode.bc")
>>> observation = llvm.compute_observation(space, bitcode, timeout=30)
.. warning::
This is not part of the core CompilerGym API and may change in a future
release.
:param observation_space: The observation that is to be computed.
:param bitcode: The path of an LLVM bitcode file.
:param timeout: The maximum number of seconds to allow the computation to
run before timing out.
:raises ValueError: If computing the observation fails.
:raises TimeoutError: If computing the observation times out.
:raises FileNotFoundError: If the given bitcode does not exist.
"""
if not Path(bitcode).is_file():
raise FileNotFoundError(bitcode)
observation_space_name = pascal_case_to_enum(observation_space.id)
try:
with Popen(
[str(_COMPUTE_OBSERVATION_BIN), observation_space_name, str(bitcode)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as process:
stdout, stderr = process.communicate(timeout=timeout)
if process.returncode:
try:
stderr = stderr.decode("utf-8")
raise ValueError(
f"Failed to compute {observation_space.id} observation: {stderr}"
)
except UnicodeDecodeError as e:
raise ValueError(
f"Failed to compute {observation_space.id} observation"
) from e
except subprocess.TimeoutExpired as e:
raise TimeoutError(
f"Failed to compute {observation_space.id} observation in "
f"{timeout:.1f} {plural(int(round(timeout)), 'second', 'seconds')}"
) from e
try:
stdout = stdout.decode("utf-8")
except UnicodeDecodeError as e:
raise ValueError(
f"Failed to parse {observation_space.id} observation: {e}"
) from e
observation = Event()
try:
google.protobuf.text_format.Parse(stdout, observation)
except google.protobuf.text_format.ParseError as e:
raise ValueError(f"Failed to parse {observation_space.id} observation") from e
return observation_space.translate(observation)
|
CompilerGym-development
|
compiler_gym/envs/llvm/compute_observation.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module defines a utility function for constructing LLVM benchmarks."""
import logging
import os
import random
import subprocess
import sys
import tempfile
from concurrent.futures import as_completed
from copy import deepcopy
from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Iterable, List, Optional, Union
from compiler_gym.datasets import Benchmark
from compiler_gym.errors import BenchmarkInitError
from compiler_gym.third_party import llvm
from compiler_gym.util.commands import Popen, communicate, run_command
from compiler_gym.util.runfiles_path import transient_cache_path
from compiler_gym.util.shell_format import join_cmd
from compiler_gym.util.thread_pool import get_thread_pool_executor
logger = logging.getLogger(__name__)
class HostCompilerFailure(OSError):
"""Exception raised when the system compiler fails."""
class UnableToParseHostCompilerOutput(HostCompilerFailure):
"""Exception raised if unable to parse the verbose output of the host
compiler."""
def _get_system_library_flags(compiler: str) -> Iterable[str]:
"""Private implementation function."""
# Create a temporary file to write the compiled binary to, since GNU
# assembler does not support piping to stdout.
transient_cache = transient_cache_path(".")
transient_cache.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=transient_cache) as f:
cmd = [compiler, "-xc++", "-v", "-", "-o", f.name]
# On macOS we need to compile a binary to invoke the linker.
if sys.platform != "darwin":
cmd.append("-c")
# Retry loop to permit timeouts, though unlikely, in case of a
# heavily overloaded system (I have observed CI failures because
# of this).
for _ in range(3):
try:
with Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
universal_newlines=True,
) as process:
_, stderr = communicate(
process=process, input="int main(){return 0;}", timeout=30
)
if process.returncode:
raise HostCompilerFailure(
f"Failed to invoke '{compiler}'. "
f"Is there a working system compiler?\n"
f"Error: {stderr.strip()}"
)
break
except subprocess.TimeoutExpired:
continue
except FileNotFoundError as e:
raise HostCompilerFailure(
f"Failed to invoke '{compiler}'. "
f"Is there a working system compiler?\n"
f"Error: {e}"
) from e
else:
raise HostCompilerFailure(
f"Compiler invocation '{join_cmd(cmd)}' timed out after 3 attempts."
)
# Parse the compiler output that matches the conventional output format
# used by clang and GCC:
#
# #include <...> search starts here:
# /path/1
# /path/2
# End of search list
in_search_list = False
lines = stderr.split("\n")
for line in lines:
if in_search_list and line.startswith("End of search list"):
break
elif in_search_list:
# We have an include path to return.
path = Path(line.strip())
yield "-isystem"
yield str(path)
# Compatibility fix for compiling benchmark sources which use the
# '#include <endian.h>' header, which on macOS is located in a
# 'machine/endian.h' directory.
if (path / "machine").is_dir():
yield "-isystem"
yield str(path / "machine")
elif line.startswith("#include <...> search starts here:"):
in_search_list = True
else:
msg = f"Failed to parse '#include <...>' search paths from '{compiler}'"
stderr = stderr.strip()
if stderr:
msg += f":\n{stderr}"
raise UnableToParseHostCompilerOutput(msg)
if sys.platform == "darwin":
yield "-L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
@lru_cache(maxsize=32)
def _get_cached_system_library_flags(compiler: str) -> List[str]:
"""Private implementation detail."""
return list(_get_system_library_flags(compiler))
def get_system_library_flags(compiler: Optional[str] = None) -> List[str]:
"""Determine the set of compilation flags needed to use the host system
libraries.
This uses the system compiler to determine the search paths for C/C++ system
headers, and on macOS, the location of libclang_rt.osx.a. By default,
:code:`c++` is invoked. This can be overridden by setting
:code:`os.environ["CXX"]` prior to calling this function.
:return: A list of command line flags for a compiler.
:raises HostCompilerFailure: If the host compiler cannot be determined, or
fails to compile a trivial piece of code.
:raises UnableToParseHostCompilerOutput: If the output of the compiler
cannot be understood.
"""
compiler = compiler or (os.environ.get("CXX") or "c++")
# We want to cache the results of this expensive query after resolving the
# default value for the compiler argument, as it can changed based on
# environment variables.
return _get_cached_system_library_flags(compiler)
class ClangInvocation:
"""Class to represent a single invocation of the clang compiler."""
def __init__(
self, args: List[str], system_includes: bool = True, timeout: int = 600
):
"""Create a clang invocation.
:param args: The list of arguments to pass to clang.
:param system_includes: Whether to include the system standard libraries
during compilation jobs. This requires a system toolchain. See
:func:`get_system_library_flags`.
:param timeout: The maximum number of seconds to allow clang to run
before terminating.
"""
self.args = args
self.system_includes = system_includes
self.timeout = timeout
def command(self, outpath: Path) -> List[str]:
cmd = [str(llvm.clang_path()), "-c", "-emit-llvm", "-o", str(outpath)]
if self.system_includes:
cmd += get_system_library_flags()
cmd += [str(s) for s in self.args]
return cmd
# NOTE(cummins): There is some discussion about the best way to create a
# bitcode that is unoptimized yet does not hinder downstream
# optimization opportunities. Here we are using a configuration based on
# -O1 in which we prevent the -O1 optimization passes from running. This
# is because LLVM produces different function attributes dependening on
# the optimization level. E.g. "-O0 -Xclang -disable-llvm-optzns -Xclang
# -disable-O0-optnone" will generate code with "noinline" attributes set
# on the functions, wheras "-Oz -Xclang -disable-llvm-optzns" will
# generate functions with "minsize" and "optsize" attributes set.
#
# See also:
# <https://lists.llvm.org/pipermail/llvm-dev/2018-August/thread.html#125365>
# <https://github.com/facebookresearch/CompilerGym/issues/110>
DEFAULT_COPT = [
"-O1",
"-Xclang",
"-disable-llvm-passes",
"-Xclang",
"-disable-llvm-optzns",
]
@classmethod
def from_c_file(
cls,
path: Path,
copt: Optional[List[str]] = None,
system_includes: bool = True,
timeout: int = 600,
) -> "ClangInvocation":
copt = copt or []
return cls(
cls.DEFAULT_COPT + copt + [str(path)],
system_includes=system_includes,
timeout=timeout,
)
def make_benchmark(
inputs: Union[str, Path, ClangInvocation, List[Union[str, Path, ClangInvocation]]],
copt: Optional[List[str]] = None,
system_includes: bool = True,
timeout: int = 600,
) -> Benchmark:
"""Create a benchmark for use by LLVM environments.
This function takes one or more inputs and uses them to create an LLVM
bitcode benchmark that can be passed to
:meth:`compiler_gym.envs.LlvmEnv.reset`.
The following input types are supported:
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| **File Suffix** | **Treated as** | **Converted using** |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| :code:`.bc` | LLVM IR bitcode | No conversion required. |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| :code:`.ll` | LLVM IR text format | Assembled to bitcode using llvm-as. |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| :code:`.c`, :code:`.cc`, :code:`.cpp`, :code:`.cxx` | C / C++ source | Compiled to bitcode using clang and the given :code:`copt`. |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
.. note::
The LLVM IR format has no compatability guarantees between versions (see
`LLVM docs
<https://llvm.org/docs/DeveloperPolicy.html#ir-backwards-compatibility>`_).
You must ensure that any :code:`.bc` and :code:`.ll` files are
compatible with the LLVM version used by CompilerGym, which can be
reported using :func:`env.compiler_version
<compiler_gym.envs.CompilerEnv.compiler_version>`.
E.g. for single-source C/C++ programs, you can pass the path of the source
file:
>>> benchmark = make_benchmark('my_app.c')
>>> env = gym.make("llvm-v0")
>>> env.reset(benchmark=benchmark)
The clang invocation used is roughly equivalent to:
.. code-block::
$ clang my_app.c -O0 -c -emit-llvm -o benchmark.bc
Additional compile-time arguments to clang can be provided using the
:code:`copt` argument:
>>> benchmark = make_benchmark('/path/to/my_app.cpp', copt=['-O2'])
If you need more fine-grained control over the options, you can directly
construct a :class:`ClangInvocation
<compiler_gym.envs.llvm.ClangInvocation>` to pass a list of arguments to
clang:
>>> benchmark = make_benchmark(
ClangInvocation(['/path/to/my_app.c'], system_includes=False, timeout=10)
)
For multi-file programs, pass a list of inputs that will be compiled
separately and then linked to a single module:
>>> benchmark = make_benchmark([
'main.c',
'lib.cpp',
'lib2.bc',
'foo/input.bc'
])
:param inputs: An input, or list of inputs.
:param copt: A list of command line options to pass to clang when compiling
source files.
:param system_includes: Whether to include the system standard libraries
during compilation jobs. This requires a system toolchain. See
:func:`get_system_library_flags`.
:param timeout: The maximum number of seconds to allow clang to run before
terminating.
:return: A :code:`Benchmark` instance.
:raises FileNotFoundError: If any input sources are not found.
:raises TypeError: If the inputs are of unsupported types.
:raises OSError: If a suitable compiler cannot be found.
:raises BenchmarkInitError: If a compilation job fails.
:raises TimeoutExpired: If a compilation job exceeds :code:`timeout`
seconds.
"""
copt = copt or []
bitcodes: List[Path] = []
clang_jobs: List[ClangInvocation] = []
ll_paths: List[Path] = []
def _add_path(path: Path):
if not path.is_file():
raise FileNotFoundError(path)
if path.suffix == ".bc":
bitcodes.append(path.absolute())
elif path.suffix in {".c", ".cc", ".cpp", ".cxx"}:
clang_jobs.append(
ClangInvocation.from_c_file(
path, copt=copt, system_includes=system_includes, timeout=timeout
)
)
elif path.suffix == ".ll":
ll_paths.append(path)
else:
raise ValueError(f"Unrecognized file type: {path.name}")
# Determine from inputs the list of pre-compiled bitcodes and the clang
# invocations required to compile the bitcodes.
if isinstance(inputs, str) or isinstance(inputs, Path):
_add_path(Path(inputs))
elif isinstance(inputs, ClangInvocation):
clang_jobs.append(inputs)
else:
for input in inputs:
if isinstance(input, str) or isinstance(input, Path):
_add_path(Path(input))
elif isinstance(input, ClangInvocation):
clang_jobs.append(input)
else:
raise TypeError(f"Invalid input type: {type(input).__name__}")
# Shortcut if we only have a single pre-compiled bitcode.
if len(bitcodes) == 1 and not clang_jobs and not ll_paths:
bitcode = bitcodes[0]
return Benchmark.from_file(uri=f"benchmark://file-v0{bitcode}", path=bitcode)
tmpdir_root = transient_cache_path(".")
tmpdir_root.mkdir(exist_ok=True, parents=True)
with tempfile.TemporaryDirectory(
dir=tmpdir_root, prefix="llvm-make_benchmark-"
) as d:
working_dir = Path(d)
clang_outs = [
working_dir / f"clang-out-{i}.bc" for i in range(1, len(clang_jobs) + 1)
]
llvm_as_outs = [
working_dir / f"llvm-as-out-{i}.bc" for i in range(1, len(ll_paths) + 1)
]
# Run the clang and llvm-as invocations in parallel. Avoid running this
# code path if possible as get_thread_pool_executor() requires locking.
if clang_jobs or ll_paths:
llvm_as_path = str(llvm.llvm_as_path())
executor = get_thread_pool_executor()
llvm_as_commands = [
[llvm_as_path, str(ll_path), "-o", bc_path]
for ll_path, bc_path in zip(ll_paths, llvm_as_outs)
]
# Fire off the clang and llvm-as jobs.
futures = [
executor.submit(run_command, job.command(out), job.timeout)
for job, out in zip(clang_jobs, clang_outs)
] + [
executor.submit(run_command, command, timeout)
for command in llvm_as_commands
]
# Block until finished.
list(future.result() for future in as_completed(futures))
# Check that the expected files were generated.
for clang_job, bc_path in zip(clang_jobs, clang_outs):
if not bc_path.is_file():
raise BenchmarkInitError(
f"clang failed: {' '.join(clang_job.command(bc_path))}"
)
for command, bc_path in zip(llvm_as_commands, llvm_as_outs):
if not bc_path.is_file():
raise BenchmarkInitError(f"llvm-as failed: {command}")
all_outs = bitcodes + clang_outs + llvm_as_outs
if not all_outs:
raise ValueError("No inputs")
elif len(all_outs) == 1:
# We only have a single bitcode so read it.
with open(str(all_outs[0]), "rb") as f:
bitcode = f.read()
else:
# Link all of the bitcodes into a single module.
llvm_link_cmd = [str(llvm.llvm_link_path()), "-o", "-"] + [
str(path) for path in bitcodes + clang_outs
]
with Popen(
llvm_link_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as llvm_link:
bitcode, stderr = llvm_link.communicate(timeout=timeout)
if llvm_link.returncode:
raise BenchmarkInitError(
f"Failed to link LLVM bitcodes with error: {stderr.decode('utf-8')}"
)
timestamp = datetime.now().strftime("%Y%m%HT%H%M%S")
uri = f"benchmark://user-v0/{timestamp}-{random.randrange(16**4):04x}"
return Benchmark.from_file_contents(uri, bitcode)
def make_benchmark_from_source(
source: str,
copt: Optional[List[str]] = None,
lang: str = "c++",
system_includes: bool = True,
timeout: int = 600,
) -> Benchmark:
"""Create a benchmark from a string of source code.
This function takes a string of source code and generates a benchmark that
can be passed to :meth:`compiler_gym.envs.LlvmEnv.reset`.
Example usage:
>>> benchmark = make_benchmark_from_source("int A() {return 0;}")
>>> env = gym.make("llvm-v0")
>>> env.reset(benchmark=benchmark)
The clang invocation used is roughly equivalent to:
.. code-block::
$ clang - -O0 -c -emit-llvm -o benchmark.bc
Additional compile-time arguments to clang can be provided using the
:code:`copt` argument:
>>> benchmark = make_benchmark_from_source("...", copt=['-O2'])
:param source: A string of source code.
:param copt: A list of command line options to pass to clang when compiling
source files.
:param lang: The source language, passed to clang via the :code:`-x`
argument. Defaults to C++.
:param system_includes: Whether to include the system standard libraries
during compilation jobs. This requires a system toolchain. See
:func:`get_system_library_flags`.
:param timeout: The maximum number of seconds to allow clang to run before
terminating.
:return: A :code:`Benchmark` instance.
:raises FileNotFoundError: If any input sources are not found.
:raises TypeError: If the inputs are of unsupported types.
:raises OSError: If a suitable compiler cannot be found.
:raises BenchmarkInitError: If a compilation job fails.
:raises TimeoutExpired: If a compilation job exceeds :code:`timeout`
seconds.
"""
cmd = [
str(llvm.clang_path()),
f"-x{lang}",
"-",
"-o",
"-",
"-c",
"-emit-llvm",
*ClangInvocation.DEFAULT_COPT,
]
if system_includes:
cmd += get_system_library_flags()
cmd += copt or []
with Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE
) as clang:
bitcode, stderr = clang.communicate(source.encode("utf-8"), timeout=timeout)
if clang.returncode:
raise BenchmarkInitError(
f"Failed to make benchmark with compiler error: {stderr.decode('utf-8')}"
)
timestamp = datetime.now().strftime("%Y%m%HT%H%M%S")
uri = f"benchmark://user-v0/{timestamp}-{random.randrange(16**4):04x}"
return Benchmark.from_file_contents(uri, bitcode)
def split_benchmark_by_function(
benchmark: Benchmark, maximum_function_count: int = 0, timeout: float = 300
) -> List[Benchmark]:
"""Split a benchmark into single-function benchmarks.
This function takes a benchmark as input and divides it into a set of
independent benchmarks, where each benchmark contains a single function from
the input.
Under the hood, this uses an extension to `llvm-extract
<https://llvm.org/docs/CommandGuide/llvm-extract.html>`__ to pull out
individual parts of programs.
In pseudo code, this is roughly equivalent to:
.. code-block::py
for i in number_of_functions_in_benchmark(benchmark):
yield llvm_extract(benchmark, function_number=i)
:param benchmark: A benchmark to split.
:param maximum_function_count: If a positive integer, this specifies the
maximum number of single-function benchmarks to extract from the input.
If the input contains more than this number of functions, the remainder
are ignored.
:param timeout: The maximum number of seconds to allow llvm-extract to run
before terminating.
:return: A list of :code:`Benchmark` instances.
:raises ValueError: If the input benchmark contains no functions, or if
llvm-extract fails.
:raises TimeoutExpired: If any llvm-extract job exceeds :code:`timeout`
seconds.
"""
original_uri = deepcopy(benchmark.uri)
original_bitcode = benchmark.proto.program.contents
# Count the number of functions in the benchmark.
with Popen(
[str(llvm.llvm_extract_one_path()), "-", "-count-only", "-o", "-"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
) as p:
stdout, stderr = p.communicate(original_bitcode, timeout=timeout)
if p.returncode:
raise ValueError(
"Failed to count number of functions in benchmark: "
f"{stderr.decode('utf-8')}"
)
number_of_functions = int(stdout.decode("utf-8"))
if number_of_functions <= 0:
raise ValueError("No functions found!")
split_benchmarks: List[Benchmark] = []
# Extract all of the global initializers into a standalone benchmark.
with Popen(
[str(llvm.llvm_extract_one_path()), "-", "-const-inits", "-o", "-"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
) as p:
stdout, stderr = p.communicate(original_bitcode, timeout=timeout)
if p.returncode:
raise ValueError(
"Failed to extract constant initializers: " f"{stderr.decode('utf-8')}"
)
original_uri.params["function"] = "<constant initializers>"
split_benchmarks.append(
Benchmark.from_file_contents(uri=original_uri, data=stdout)
)
logger.debug("Extracted %s", original_uri)
# Iterate over the number of functions, extracting each one in turn.
n = min(number_of_functions, maximum_function_count or number_of_functions)
for i in range(n):
with Popen(
[str(llvm.llvm_extract_one_path()), "-", "-n", str(i), "-o", "-"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
) as p:
stdout, stderr = p.communicate(original_bitcode, timeout=timeout)
if p.returncode:
raise ValueError(
"Failed to extract function {i}: " f"{stderr.decode('utf-8')}"
)
original_uri.params["function"] = str(i)
split_benchmarks.append(
Benchmark.from_file_contents(uri=original_uri, data=stdout)
)
logger.debug("Extracted %s", original_uri)
return split_benchmarks
def merge_benchmarks(benchmarks: List[Benchmark], timeout: float = 300) -> Benchmark:
"""Merge a list of benchmarks into a single benchmark.
Under the hood, this `llvm-link
<https://llvm.org/docs/CommandGuide/llvm-link.html>`__ to combine each of
the bitcodes of the input benchmarks into a single bitcode.
:param benchmarks: A list of benchmarks to merge.
:param timeout: The maximum number of seconds to allow llvm-link to run
before terminating.
:return: A :code:`Benchmark` instance.
:raises ValueError: If the input contains no benchmarks, or if llvm-link
fails.
:raises TimeoutExpired: If llvm-link exceeds :code:`timeout` seconds.
"""
if not benchmarks:
raise ValueError("No benchmarks!")
transient_cache = transient_cache_path(".")
transient_cache.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=transient_cache, prefix="llvm-link") as d:
tmpdir = Path(d)
# Write each of the benchmark bitcodes to a temporary file.
cmd = [str(llvm.llvm_link_path()), "-o", "-", "-f"]
for i, benchmark in enumerate(benchmarks):
bitcode_path = tmpdir / f"{i}.bc"
with open(bitcode_path, "wb") as f:
f.write(benchmark.proto.program.contents)
cmd.append(str(bitcode_path))
# Run llvm-link on the temporary files.
with Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
stdout, stderr = p.communicate(timeout=timeout)
if p.returncode:
raise ValueError(
f"Failed to merge benchmarks: {stderr.decode('utf-8')}"
)
timestamp = datetime.now().strftime("%Y%m%HT%H%M%S")
uri = f"benchmark://llvm-link-v0/{timestamp}-{random.randrange(16**4):04x}"
return Benchmark.from_file_contents(uri=uri, data=stdout)
|
CompilerGym-development
|
compiler_gym/envs/llvm/llvm_benchmark.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Extensions to the ClientServiceCompilerEnv environment for LLVM."""
import logging
import os
import shlex
import shutil
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Callable, Iterable, List, Optional, Union
import numpy as np
from compiler_gym.datasets import Benchmark, Dataset
from compiler_gym.envs.llvm.benchmark_from_command_line import BenchmarkFromCommandLine
from compiler_gym.envs.llvm.datasets import get_llvm_datasets
from compiler_gym.envs.llvm.lexed_ir import LexedToken
from compiler_gym.envs.llvm.llvm_benchmark import (
ClangInvocation,
get_system_library_flags,
make_benchmark,
)
from compiler_gym.envs.llvm.llvm_command_line import LlvmCommandLine
from compiler_gym.envs.llvm.llvm_rewards import (
BaselineImprovementNormalizedReward,
CostFunctionReward,
NormalizedReward,
)
from compiler_gym.errors import BenchmarkInitError, SessionNotFound
from compiler_gym.service.client_service_compiler_env import (
ClientServiceCompilerEnv,
ServiceMessageConverters,
)
from compiler_gym.service.proto.py_converters import make_message_default_converter
from compiler_gym.spaces import Box
from compiler_gym.spaces import Dict as DictSpace
from compiler_gym.spaces import Scalar, Sequence
from compiler_gym.third_party.autophase import AUTOPHASE_FEATURE_NAMES
from compiler_gym.third_party.gccinvocation.gccinvocation import GccInvocation
from compiler_gym.third_party.inst2vec import Inst2vecEncoder
from compiler_gym.third_party.llvm import (
clang_path,
download_llvm_files,
llvm_link_path,
)
from compiler_gym.third_party.llvm.instcount import INST_COUNT_FEATURE_NAMES
from compiler_gym.util.commands import Popen
from compiler_gym.util.runfiles_path import transient_cache_path
from compiler_gym.util.shell_format import join_cmd
_INST2VEC_ENCODER = Inst2vecEncoder()
_LLVM_DATASETS: Optional[List[Dataset]] = None
logger = logging.getLogger(__name__)
def _get_llvm_datasets(site_data_base: Optional[Path] = None) -> Iterable[Dataset]:
"""Get the LLVM datasets. Use a singleton value when site_data_base is the
default value.
"""
global _LLVM_DATASETS
if site_data_base is None:
if _LLVM_DATASETS is None:
_LLVM_DATASETS = list(get_llvm_datasets(site_data_base=site_data_base))
return _LLVM_DATASETS
return get_llvm_datasets(site_data_base=site_data_base)
def make_llvm_action_space_converter() -> Callable[[Any], LlvmCommandLine]:
return lambda msg: LlvmCommandLine(space=make_message_default_converter()(msg))
class LlvmEnv(ClientServiceCompilerEnv):
"""A specialized ClientServiceCompilerEnv for LLVM.
This extends the default :class:`ClientServiceCompilerEnv
<compiler_gym.envs.ClientServiceCompilerEnv>` environment, adding extra LLVM
functionality. Specifically, the actions use the :class:`CommandlineFlag
<compiler_gym.spaces.CommandlineFlag>` space, which is a type of
:code:`Discrete` space that provides additional documentation about each
action, and the :meth:`env.action_space.to_string(...)
<compiler_gym.envs.LlvmEnv.LlvmCommandLine.to_string>` method can be used to
produce an equivalent LLVM opt invocation for the given actions.
"""
def __init__(
self,
*args,
benchmark: Optional[Union[str, Benchmark]] = None,
datasets_site_path: Optional[Path] = None,
**kwargs,
):
# First perform a one-time download of LLVM binaries that are needed by
# the LLVM service and are not included by the pip-installed package.
download_llvm_files()
self.inst2vec = _INST2VEC_ENCODER
super().__init__(
*args,
**kwargs,
# Set a default benchmark for use.
benchmark=benchmark or "cbench-v1/qsort",
datasets=_get_llvm_datasets(site_data_base=datasets_site_path),
service_message_converters=ServiceMessageConverters(
action_space_converter=make_llvm_action_space_converter()
),
rewards=[
CostFunctionReward(
name="IrInstructionCount",
cost_function="IrInstructionCount",
init_cost_function="IrInstructionCountO0",
default_negates_returns=True,
deterministic=True,
platform_dependent=False,
),
NormalizedReward(
name="IrInstructionCountNorm",
cost_function="IrInstructionCount",
init_cost_function="IrInstructionCountO0",
max=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=False,
),
BaselineImprovementNormalizedReward(
name="IrInstructionCountO3",
cost_function="IrInstructionCount",
baseline_cost_function="IrInstructionCountO3",
init_cost_function="IrInstructionCountO0",
success_threshold=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=False,
),
BaselineImprovementNormalizedReward(
name="IrInstructionCountOz",
cost_function="IrInstructionCount",
baseline_cost_function="IrInstructionCountOz",
init_cost_function="IrInstructionCountO0",
success_threshold=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=False,
),
CostFunctionReward(
name="ObjectTextSizeBytes",
cost_function="ObjectTextSizeBytes",
init_cost_function="ObjectTextSizeO0",
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
NormalizedReward(
name="ObjectTextSizeNorm",
cost_function="ObjectTextSizeBytes",
init_cost_function="ObjectTextSizeO0",
max=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
BaselineImprovementNormalizedReward(
name="ObjectTextSizeO3",
cost_function="ObjectTextSizeBytes",
init_cost_function="ObjectTextSizeO0",
baseline_cost_function="ObjectTextSizeO3",
success_threshold=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
BaselineImprovementNormalizedReward(
name="ObjectTextSizeOz",
cost_function="ObjectTextSizeBytes",
init_cost_function="ObjectTextSizeO0",
baseline_cost_function="ObjectTextSizeOz",
success_threshold=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
CostFunctionReward(
name="TextSizeBytes",
cost_function="TextSizeBytes",
init_cost_function="TextSizeO0",
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
NormalizedReward(
name="TextSizeNorm",
cost_function="TextSizeBytes",
init_cost_function="TextSizeO0",
max=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
BaselineImprovementNormalizedReward(
name="TextSizeO3",
cost_function="TextSizeBytes",
init_cost_function="TextSizeO0",
baseline_cost_function="TextSizeO3",
success_threshold=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
BaselineImprovementNormalizedReward(
name="TextSizeOz",
cost_function="TextSizeBytes",
init_cost_function="TextSizeO0",
baseline_cost_function="TextSizeOz",
success_threshold=1,
default_negates_returns=True,
deterministic=True,
platform_dependent=True,
),
],
derived_observation_spaces=[
{
"id": "Inst2vecPreprocessedText",
"base_id": "Ir",
"space": Sequence(
name="Inst2vecPreprocessedText", size_range=(0, None), dtype=str
),
"translate": self.inst2vec.preprocess,
"default_value": "",
},
{
"id": "Inst2vecEmbeddingIndices",
"base_id": "Ir",
"space": Sequence(
name="Inst2vecEmbeddingIndices",
size_range=(0, None),
dtype=np.int32,
),
"translate": lambda base_observation: self.inst2vec.encode(
self.inst2vec.preprocess(base_observation)
),
"default_value": np.array([self.inst2vec.vocab["!UNK"]]),
},
{
"id": "Inst2vec",
"base_id": "Ir",
"space": Sequence(
name="Inst2vec", size_range=(0, None), dtype=np.ndarray
),
"translate": lambda base_observation: self.inst2vec.embed(
self.inst2vec.encode(self.inst2vec.preprocess(base_observation))
),
"default_value": np.vstack(
[self.inst2vec.embeddings[self.inst2vec.vocab["!UNK"]]]
),
},
{
"id": "InstCountDict",
"base_id": "InstCount",
"space": DictSpace(
{
f"{name}Count": Scalar(
name=f"{name}Count", min=0, max=None, dtype=int
)
for name in INST_COUNT_FEATURE_NAMES
},
name="InstCountDict",
),
"translate": lambda base_observation: {
f"{name}Count": val
for name, val in zip(INST_COUNT_FEATURE_NAMES, base_observation)
},
},
{
"id": "InstCountNorm",
"base_id": "InstCount",
"space": Box(
name="InstCountNorm",
low=0,
high=1,
shape=(len(INST_COUNT_FEATURE_NAMES) - 1,),
dtype=np.float32,
),
"translate": lambda base_observation: (
base_observation[1:] / max(base_observation[0], 1)
).astype(np.float32),
},
{
"id": "InstCountNormDict",
"base_id": "InstCountNorm",
"space": DictSpace(
{
f"{name}Density": Scalar(
name=f"{name}Density", min=0, max=None, dtype=int
)
for name in INST_COUNT_FEATURE_NAMES[1:]
},
name="InstCountNormDict",
),
"translate": lambda base_observation: {
f"{name}Density": val
for name, val in zip(
INST_COUNT_FEATURE_NAMES[1:], base_observation
)
},
},
{
"id": "AutophaseDict",
"base_id": "Autophase",
"space": DictSpace(
{
name: Scalar(name=name, min=0, max=None, dtype=int)
for name in AUTOPHASE_FEATURE_NAMES
},
name="AutophaseDict",
),
"translate": lambda base_observation: {
name: val
for name, val in zip(AUTOPHASE_FEATURE_NAMES, base_observation)
},
},
{
"id": "LexedIrTuple",
"base_id": "LexedIr",
"space": Sequence(
name="LexedToken",
size_range=(0, None),
dtype=LexedToken,
),
"translate": lambda base_observation: [
LexedToken(tid, kind, cat, val)
for tid, kind, cat, val in zip(
base_observation["token_id"],
base_observation["token_kind"],
base_observation["token_category"],
base_observation["token_value"],
)
],
"default_value": {
"token_id": [],
"token_kind": [],
"token_category": [],
"token_value": [],
},
},
],
)
# Mutable runtime configuration options that must be set on every call
# to reset.
self._runtimes_per_observation_count: Optional[int] = None
self._runtimes_warmup_per_observation_count: Optional[int] = None
cpu_info_spaces = [
Sequence(name="name", size_range=(0, None), dtype=str),
Scalar(name="cores_count", min=None, max=None, dtype=int),
Scalar(name="l1i_cache_size", min=None, max=None, dtype=int),
Scalar(name="l1i_cache_count", min=None, max=None, dtype=int),
Scalar(name="l1d_cache_size", min=None, max=None, dtype=int),
Scalar(name="l1d_cache_count", min=None, max=None, dtype=int),
Scalar(name="l2_cache_size", min=None, max=None, dtype=int),
Scalar(name="l2_cache_count", min=None, max=None, dtype=int),
Scalar(name="l3_cache_size", min=None, max=None, dtype=int),
Scalar(name="l3_cache_count", min=None, max=None, dtype=int),
Scalar(name="l4_cache_size", min=None, max=None, dtype=int),
Scalar(name="l4_cache_count", min=None, max=None, dtype=int),
]
self.observation.spaces["CpuInfo"].space = DictSpace(
{space.name: space for space in cpu_info_spaces},
name="CpuInfo",
)
def reset(self, *args, **kwargs):
try:
return super().reset(*args, **kwargs)
except ValueError as e:
# Catch and re-raise some known benchmark initialization errors with
# a more informative error type.
if "Failed to compute .text size cost" in str(e):
raise BenchmarkInitError(
f"Failed to initialize benchmark {self._benchmark_in_use.uri}: {e}"
) from e
elif (
"File not found:" in str(e)
or "File is empty:" in str(e)
or "Error reading file:" in str(e)
):
raise BenchmarkInitError(str(e)) from e
elif "Failed to parse LLVM bitcode" in str(e):
raise BenchmarkInitError(str(e)) from e
raise
def make_benchmark(
self,
inputs: Union[
str, Path, ClangInvocation, List[Union[str, Path, ClangInvocation]]
],
copt: Optional[List[str]] = None,
system_includes: bool = True,
timeout: int = 600,
) -> Benchmark:
"""Create a benchmark for use with this environment.
This function takes one or more inputs and uses them to create an LLVM
bitcode benchmark that can be passed to
:meth:`compiler_gym.envs.LlvmEnv.reset`.
The following input types are supported:
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| **File Suffix** | **Treated as** | **Converted using** |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| :code:`.bc` | LLVM IR bitcode | No conversion required. |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| :code:`.ll` | LLVM IR text format | Assembled to bitcode using llvm-as. |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
| :code:`.c`, :code:`.cc`, :code:`.cpp`, :code:`.cxx` | C / C++ source | Compiled to bitcode using clang and the given :code:`copt`. |
+-----------------------------------------------------+---------------------+-------------------------------------------------------------+
.. note::
The LLVM IR format has no compatability guarantees between versions (see
`LLVM docs
<https://llvm.org/docs/DeveloperPolicy.html#ir-backwards-compatibility>`_).
You must ensure that any :code:`.bc` and :code:`.ll` files are
compatible with the LLVM version used by CompilerGym, which can be
reported using :func:`env.compiler_version
<compiler_gym.envs.ClientServiceCompilerEnv.compiler_version>`.
E.g. for single-source C/C++ programs, you can pass the path of the source
file:
>>> benchmark = env.make_benchmark('my_app.c')
>>> env = gym.make("llvm-v0")
>>> env.reset(benchmark=benchmark)
The clang invocation used is roughly equivalent to:
.. code-block::
$ clang my_app.c -O0 -c -emit-llvm -o benchmark.bc
Additional compile-time arguments to clang can be provided using the
:code:`copt` argument:
>>> benchmark = env.make_benchmark('/path/to/my_app.cpp', copt=['-O2'])
If you need more fine-grained control over the options, you can directly
construct a :class:`ClangInvocation
<compiler_gym.envs.llvm.ClangInvocation>` to pass a list of arguments to
clang:
>>> benchmark = env.make_benchmark(
ClangInvocation(['/path/to/my_app.c'], system_includes=False, timeout=10)
)
For multi-file programs, pass a list of inputs that will be compiled
separately and then linked to a single module:
>>> benchmark = env.make_benchmark([
'main.c',
'lib.cpp',
'lib2.bc',
'foo/input.bc'
])
:param inputs: An input, or list of inputs.
:param copt: A list of command line options to pass to clang when
compiling source files.
:param system_includes: Whether to include the system standard libraries
during compilation jobs. This requires a system toolchain. See
:func:`get_system_library_flags`.
:param timeout: The maximum number of seconds to allow clang to run
before terminating.
:return: A :code:`Benchmark` instance.
:raises FileNotFoundError: If any input sources are not found.
:raises TypeError: If the inputs are of unsupported types.
:raises OSError: If a suitable compiler cannot be found.
:raises BenchmarkInitError: If a compilation job fails.
:raises TimeoutExpired: If a compilation job exceeds :code:`timeout`
seconds.
"""
return make_benchmark(
inputs=inputs,
copt=copt,
system_includes=system_includes,
timeout=timeout,
)
@property
def ir(self) -> str:
"""Print the LLVM-IR of the program in its current state.
Alias for :code:`env.observation["Ir"]`.
:return: A string of LLVM-IR.
"""
return self.observation["Ir"]
@property
def ir_sha1(self) -> str:
"""Return the 40-characeter hex sha1 checksum of the current IR.
Equivalent to: :code:`hashlib.sha1(env.ir.encode("utf-8")).hexdigest()`.
:return: A 40-character hexadecimal sha1 string.
"""
return self.observation["IrSha1"]
def write_ir(self, path: Union[Path, str]) -> Path:
"""Write the current program state to a file.
:param path: The path of the file to write.
:return: The input :code:`path` argument.
"""
path = Path(path).expanduser()
with open(path, "w") as f:
f.write(self.ir)
return path
def write_bitcode(self, path: Union[Path, str]) -> Path:
"""Write the current program state to a bitcode file.
:param path: The path of the file to write.
:return: The input :code:`path` argument.
"""
path = Path(path).expanduser()
tmp_path = self.observation["BitcodeFile"]
try:
shutil.copyfile(tmp_path, path)
finally:
os.unlink(tmp_path)
return path
def render(
self,
mode="human",
) -> Optional[str]:
if mode == "human":
print(self.ir)
else:
return super().render(mode)
@property
def runtime_observation_count(self) -> int:
"""The number of runtimes to return for the Runtime observation space.
See the :ref:`Runtime observation space reference <llvm/index:Runtime>`
for further details.
Example usage:
>>> env = compiler_gym.make("llvm-v0")
>>> env.reset()
>>> env.runtime_observation_count = 10
>>> len(env.observation.Runtime())
10
:getter: Returns the number of runtimes that will be returned when a
:code:`Runtime` observation is requested.
:setter: Set the number of runtimes to compute when a :code:`Runtime`
observation is requested.
:type: int
"""
return self._runtimes_per_observation_count or int(
self.send_param("llvm.get_runtimes_per_observation_count", "")
)
@runtime_observation_count.setter
def runtime_observation_count(self, n: int) -> None:
try:
self.send_param(
"llvm.set_runtimes_per_observation_count", str(n), resend_on_reset=True
)
except SessionNotFound:
pass # Not in session yet, will be sent on reset().
self._runtimes_per_observation_count = n
@property
def runtime_warmup_runs_count(self) -> int:
"""The number of warmup runs of the binary to perform before measuring
the Runtime observation space.
See the :ref:`Runtime observation space reference <llvm/index:Runtime>`
for further details.
Example usage:
>>> env = compiler_gym.make("llvm-v0")
>>> env.reset()
>>> env.runtime_observation_count = 10
>>> len(env.observation.Runtime())
10
:getter: Returns the number of runs that be performed before measuring
the :code:`Runtime` observation is requested.
:setter: Set the number of warmup runs to perform when a :code:`Runtime`
observation is requested.
:type: int
"""
return self._runtimes_warmup_per_observation_count or int(
self.send_param("llvm.get_warmup_runs_count_per_runtime_observation", "")
)
@runtime_warmup_runs_count.setter
def runtime_warmup_runs_count(self, n: int) -> None:
try:
self.send_param(
"llvm.set_warmup_runs_count_per_runtime_observation",
str(n),
resend_on_reset=True,
)
except SessionNotFound:
pass # Not in session yet, will be sent on reset().
self._runtimes_warmup_per_observation_count = n
def fork(self):
fkd = super().fork()
if self.runtime_observation_count is not None:
fkd.runtime_observation_count = self.runtime_observation_count
if self.runtime_warmup_runs_count is not None:
fkd.runtime_warmup_runs_count = self.runtime_warmup_runs_count
return fkd
def make_benchmark_from_command_line(
self,
cmd: Union[str, List[str]],
replace_driver: bool = True,
system_includes: bool = True,
timeout: int = 600,
) -> Benchmark:
"""Create a benchmark for use with this environment.
This function takes a command line compiler invocation as input,
modifies it to produce an unoptimized LLVM-IR bitcode, and then runs the
modified command line to produce a bitcode benchmark.
For example, the command line:
>>> benchmark = env.make_benchmark_from_command_line(
... ["gcc", "-DNDEBUG", "a.c", "b.c", "-o", "foo", "-lm"]
... )
Will compile a.c and b.c to an unoptimized benchmark that can be then
passed to :meth:`reset() <compiler_env.envs.CompilerEnv.reset>`.
The way this works is to change the first argument of the command line
invocation to the version of clang shipped with CompilerGym, and to then
append command line flags that causes the compiler to produce LLVM-IR
with optimizations disabled. For example the input command line:
.. code-block::
gcc -DNDEBUG a.c b.c -o foo -lm
Will be rewritten to be roughly equivalent to:
.. code-block::
/path/to/compiler_gym/clang -DNDEG a.c b.c \\
-Xclang -disable-llvm-passes -Xclang -disable-llvm-optzns \\ -c
-emit-llvm -o -
The generated benchmark then has a method :meth:`compile()
<compiler_env.envs.llvm.BenchmarkFromCommandLine.compile>` which
completes the linking and compilatilion to executable. For the above
example, this would be roughly equivalent to:
.. code-block::
/path/to/compiler_gym/clang environment-bitcode.bc -o foo -lm
:param cmd: A command line compiler invocation, either as a list of
arguments (e.g. :code:`["clang", "in.c"]`) or as a single shell
string (e.g. :code:`"clang in.c"`).
:param replace_driver: Whether to replace the first argument of the
command with the clang driver used by this environment.
:param system_includes: Whether to include the system standard libraries
during compilation jobs. This requires a system toolchain. See
:func:`get_system_library_flags`.
:param timeout: The maximum number of seconds to allow the compilation
job to run before terminating.
:return: A :class:`BenchmarkFromCommandLine
<compiler_gym.envs.llvm.BenchmarkFromCommandLine>` instance.
:raises ValueError: If no command line is provided.
:raises BenchmarkInitError: If executing the command line fails.
:raises TimeoutExpired: If a compilation job exceeds :code:`timeout`
seconds.
"""
if not cmd:
raise ValueError("Input command line is empty")
# Split the command line if passed a single string.
if isinstance(cmd, str):
cmd = shlex.split(cmd)
rewritten_cmd: List[str] = cmd.copy()
if len(cmd) < 2:
raise ValueError(f"Input command line '{join_cmd(cmd)}' is too short")
# Append include flags for the system headers if requested.
if system_includes:
rewritten_cmd += get_system_library_flags()
# Use the CompilerGym clang binary in place of the original driver.
if replace_driver:
rewritten_cmd[0] = str(clang_path())
# Strip the -S flag, if present, as that changes the output format.
rewritten_cmd = [c for c in rewritten_cmd if c != "-S"]
invocation = GccInvocation(rewritten_cmd)
# Strip the output specifier(s). This is not strictly required since we
# override it later, but makes the generated command easier to
# understand.
for i in range(len(rewritten_cmd) - 2, -1, -1):
if rewritten_cmd[i] == "-o":
del rewritten_cmd[i + 1]
del rewritten_cmd[i]
# Fail early.
if "-" in invocation.sources:
raise ValueError(
"Input command line reads from stdin, "
f"which is not supported: '{join_cmd(cmd)}'"
)
# Convert all of the C/C++ sources to bitcodes which can then be linked
# into a single bitcode. We must process them individually because the
# '-c' flag does not support multiple sources when we are specifying the
# output path using '-o'.
sources = set(s for s in invocation.sources if not s.endswith(".o"))
if not sources:
raise ValueError(
f"Input command line has no source file inputs: '{join_cmd(cmd)}'"
)
bitcodes: List[bytes] = []
for source in sources:
# Adapt and execute the command line so that it will generate an
# unoptimized bitecode file.
emit_bitcode_command = rewritten_cmd.copy()
# Strip the name of other sources:
if len(sources) > 1:
emit_bitcode_command = [
c for c in emit_bitcode_command if c == source or c not in sources
]
# Append the flags to emit the bitcode and disable the optimization
# passes.
emit_bitcode_command += [
"-c",
"-emit-llvm",
"-o",
"-",
"-Xclang",
"-disable-llvm-passes",
"-Xclang",
"-disable-llvm-optzns",
]
with Popen(
emit_bitcode_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as clang:
logger.debug(
f"Generating LLVM bitcode benchmark: {join_cmd(emit_bitcode_command)}"
)
bitcode, stderr = clang.communicate(timeout=timeout)
if clang.returncode:
raise BenchmarkInitError(
f"Failed to generate LLVM bitcode with error:\n"
f"{stderr.decode('utf-8').rstrip()}\n"
f"Running command: {join_cmd(emit_bitcode_command)}\n"
f"From original commandline: {join_cmd(cmd)}"
)
bitcodes.append(bitcode)
# If there were multiple sources then link the bitcodes together.
if len(bitcodes) > 1:
with TemporaryDirectory(
dir=transient_cache_path("."), prefix="llvm-benchmark-"
) as dir:
# Write the bitcodes to files.
for i, bitcode in enumerate(bitcodes):
with open(os.path.join(dir, f"{i}.bc"), "wb") as f:
f.write(bitcode)
# Link the bitcode files.
llvm_link_cmd = [str(llvm_link_path()), "-o", "-"] + [
os.path.join(dir, f"{i}.bc") for i in range(len(bitcodes))
]
with Popen(
llvm_link_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as llvm_link:
bitcode, stderr = llvm_link.communicate(timeout=timeout)
if llvm_link.returncode:
raise BenchmarkInitError(
f"Failed to link LLVM bitcodes with error: {stderr.decode('utf-8')}"
)
return BenchmarkFromCommandLine(invocation, bitcode, timeout)
|
CompilerGym-development
|
compiler_gym/envs/llvm/llvm_env.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Utilities for LexedIRTuple derived observation space."""
import subprocess
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Dict, List, NamedTuple
import google.protobuf.text_format
import numpy as np
from compiler_gym.service.proto import Event
from compiler_gym.service.proto.py_converters import make_message_default_converter
from compiler_gym.util.commands import Popen
from compiler_gym.util.runfiles_path import runfiles_path
from compiler_gym.util.shell_format import plural
_COMPUTE_OBSERVATION_BIN = runfiles_path(
"compiler_gym/envs/llvm/service/compute_observation"
)
_COMPUTE_UNLEX_BIN = runfiles_path("compiler_gym/third_party/Lexedir/compute_unlexed")
class LexedToken(NamedTuple):
ID: int
kind: str
category: str
value: str
def LexedIr(bitcode: Path, timeout: float = 300) -> Dict[str, np.array]:
""" """
if not Path(bitcode).is_file():
raise FileNotFoundError(bitcode)
observation_space_name = "LEXED_IR"
translate = make_message_default_converter()
try:
with Popen(
[str(_COMPUTE_OBSERVATION_BIN), observation_space_name, str(bitcode)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as process:
stdout, stderr = process.communicate(timeout=timeout)
if process.returncode:
try:
stderr = stderr.decode("utf-8")
raise ValueError(f"Failed to compute LexedIr observation: {stderr}")
except UnicodeDecodeError as e:
raise ValueError("Failed to compute LexedIr observation") from e
except subprocess.TimeoutExpired as e:
raise TimeoutError(
"Failed to compute LexedIr observation in "
f"{timeout:.1f} {plural(int(round(timeout)), 'second', 'seconds')}"
) from e
try:
stdout = stdout.decode("utf-8")
except UnicodeDecodeError as e:
raise ValueError(f"Failed to parse LexedIr observation: {e}") from e
observation = Event()
try:
google.protobuf.text_format.Parse(stdout, observation)
except google.protobuf.text_format.ParseError as e:
raise ValueError("Failed to parse LexedIr observation") from e
return translate(observation)
def LexedIrTuple(bitcode: Path, timeout: float = 300) -> List[LexedToken]:
"""
Standalone IR Lexer.
"""
lexed_dict = LexedIr(bitcode, timeout=timeout)
return [
LexedToken(tid, tval, tkind, tcat)
for tid, tval, tkind, tcat in zip(
lexed_dict["token_id"],
lexed_dict["token_value"],
lexed_dict["token_kind"],
lexed_dict["token_category"],
)
]
def UnLex(token_ids: List[int], token_values: List[str], timeout: float = 300) -> str:
with NamedTemporaryFile("w", prefix="compiler_gym_unlex_") as f:
f.write(
"\n".join(["{},{}".format(i, v) for i, v in zip(token_ids, token_values)])
)
f.flush()
try:
with Popen(
[str(_COMPUTE_UNLEX_BIN), str(f.name)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as process:
stdout, stderr = process.communicate(timeout=timeout)
if process.returncode:
try:
stderr = stderr.decode("utf-8")
raise ValueError(
f"Failed to compute UnLex observation: {stderr}"
)
except UnicodeDecodeError as e:
raise ValueError("Failed to compute UnLex observation") from e
except subprocess.TimeoutExpired as e:
raise TimeoutError(
f"Failed to compute UnLex observation in "
f"{timeout:.1f} {plural(int(round(timeout)), 'second', 'seconds')}"
) from e
try:
stdout = stdout.decode("utf-8")
except UnicodeDecodeError as e:
raise ValueError(f"Failed to parse UnLex observation: {e}") from e
return stdout
|
CompilerGym-development
|
compiler_gym/envs/llvm/lexed_ir.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import enum
import io
import logging
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from collections import defaultdict
from pathlib import Path
from threading import Lock
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional
import fasteners
from compiler_gym.datasets import Benchmark, TarDatasetWithManifest
from compiler_gym.datasets.benchmark import ValidationCallback
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm import llvm_benchmark
from compiler_gym.errors import ValidationError
from compiler_gym.service.proto import BenchmarkDynamicConfig, Command
from compiler_gym.third_party import llvm
from compiler_gym.util.commands import Popen
from compiler_gym.util.download import download
from compiler_gym.util.filesystem import extract_tar
from compiler_gym.util.runfiles_path import cache_path, site_data_path
from compiler_gym.util.timer import Timer
logger = logging.getLogger(__name__)
_CBENCH_TARS = {
"macos": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cBench-v1-macos.tar.bz2",
"90b312b40317d9ee9ed09b4b57d378879f05e8970bb6de80dc8581ad0e36c84f",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cBench-v1-linux.tar.bz2",
"601fff3944c866f6617e653b6eb5c1521382c935f56ca1f36a9f5cf1a49f3de5",
),
}
_CBENCH_RUNTOME_DATA = (
"https://dl.fbaipublicfiles.com/compiler_gym/cBench-v0-runtime-data.tar.bz2",
"a1b5b5d6b115e5809ccaefc2134434494271d184da67e2ee43d7f84d07329055",
)
if sys.platform == "darwin":
_COMPILE_ARGS = [
"-L",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib",
]
else:
_COMPILE_ARGS = []
class LlvmSanitizer(enum.IntEnum):
"""The LLVM sanitizers."""
ASAN = 1
TSAN = 2
MSAN = 3
UBSAN = 4
# Compiler flags that are enabled by sanitizers.
_SANITIZER_FLAGS = {
LlvmSanitizer.ASAN: ["-O1", "-g", "-fsanitize=address", "-fno-omit-frame-pointer"],
LlvmSanitizer.TSAN: ["-O1", "-g", "-fsanitize=thread"],
LlvmSanitizer.MSAN: ["-O1", "-g", "-fsanitize=memory"],
LlvmSanitizer.UBSAN: ["-fsanitize=undefined"],
}
class BenchmarkExecutionResult(NamedTuple):
"""The result of running a benchmark."""
walltime_seconds: float
"""The execution time in seconds."""
error: Optional[ValidationError] = None
"""An error."""
output: Optional[str] = None
"""The output generated by the benchmark."""
def json(self):
return self._asdict() # pylint: disable=no-member
def _compile_and_run_bitcode_file(
bitcode_file: Path,
cmd: str,
cwd: Path,
linkopts: List[str],
env: Dict[str, str],
num_runs: int,
sanitizer: Optional[LlvmSanitizer] = None,
timeout_seconds: float = 300,
compilation_timeout_seconds: float = 60,
) -> BenchmarkExecutionResult:
"""Run the given cBench benchmark."""
# cBench benchmarks expect that a file _finfo_dataset exists in the
# current working directory and contains the number of benchmark
# iterations in it.
with open(cwd / "_finfo_dataset", "w") as f:
print(num_runs, file=f)
# Create a barebones execution environment for the benchmark.
run_env = {
"TMPDIR": os.environ.get("TMPDIR", ""),
"HOME": os.environ.get("HOME", ""),
"USER": os.environ.get("USER", ""),
# Disable all logging from GRPC. In the past I have had false-positive
# "Wrong output" errors caused by GRPC error messages being logged to
# stderr.
"GRPC_VERBOSITY": "NONE",
}
run_env.update(env)
error_data = {}
if sanitizer:
clang_path = llvm.clang_path()
binary = cwd / "a.out"
error_data["run_cmd"] = cmd.replace("$BIN", "./a.out")
# Generate the a.out binary file.
compile_cmd = (
[clang_path.name, str(bitcode_file), "-o", str(binary)]
+ _COMPILE_ARGS
+ list(linkopts)
+ _SANITIZER_FLAGS.get(sanitizer, [])
)
error_data["compile_cmd"] = compile_cmd
logger.debug("compile: %s", compile_cmd)
assert not binary.is_file()
try:
with Popen(
compile_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
env={"PATH": f"{clang_path.parent}:{os.environ.get('PATH', '')}"},
) as clang:
output, _ = clang.communicate(timeout=compilation_timeout_seconds)
if clang.returncode:
error_data["output"] = output
return BenchmarkExecutionResult(
walltime_seconds=timeout_seconds,
error=ValidationError(
type="Compilation failed",
data=error_data,
),
)
except subprocess.TimeoutExpired:
error_data["timeout"] = compilation_timeout_seconds
return BenchmarkExecutionResult(
walltime_seconds=timeout_seconds,
error=ValidationError(
type="Compilation timeout",
data=error_data,
),
)
assert binary.is_file()
else:
lli_path = llvm.lli_path()
error_data["run_cmd"] = cmd.replace("$BIN", f"{lli_path.name} benchmark.bc")
run_env["PATH"] = str(lli_path.parent)
logger.debug("exec: %s", error_data["run_cmd"])
try:
with Timer() as timer, Popen(
error_data["run_cmd"],
shell=True,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
env=run_env,
cwd=cwd,
) as process:
stdout, _ = process.communicate(timeout=timeout_seconds)
except subprocess.TimeoutExpired:
error_data["timeout_seconds"] = timeout_seconds
return BenchmarkExecutionResult(
walltime_seconds=timeout_seconds,
error=ValidationError(
type="Execution timeout",
data=error_data,
),
)
finally:
if sanitizer:
binary.unlink()
try:
output = stdout.decode("utf-8")
except UnicodeDecodeError:
output = "<binary>"
if process.returncode:
# Runtime error.
if sanitizer == LlvmSanitizer.ASAN and "LeakSanitizer" in output:
error_type = "Memory leak"
elif sanitizer == LlvmSanitizer.ASAN and "AddressSanitizer" in output:
error_type = "Memory error"
elif sanitizer == LlvmSanitizer.MSAN and "MemorySanitizer" in output:
error_type = "Memory error"
elif "Segmentation fault" in output:
error_type = "Segmentation fault"
elif "Illegal Instruction" in output:
error_type = "Illegal Instruction"
else:
error_type = f"Runtime error ({process.returncode})"
error_data["return_code"] = process.returncode
error_data["output"] = output
return BenchmarkExecutionResult(
walltime_seconds=timer.time,
error=ValidationError(
type=error_type,
data=error_data,
),
)
return BenchmarkExecutionResult(walltime_seconds=timer.time, output=output)
def download_cBench_runtime_data() -> bool:
"""Download and unpack the cBench runtime dataset."""
cbench_data = site_data_path("llvm-v0/cbench-v1-runtime-data/runtime_data")
if (cbench_data / "unpacked").is_file():
return False
else:
# Clean up any partially-extracted data directory.
if cbench_data.is_dir():
shutil.rmtree(cbench_data)
url, sha256 = _CBENCH_RUNTOME_DATA
tar_contents = io.BytesIO(download(url, sha256))
with tarfile.open(fileobj=tar_contents, mode="r:bz2") as tar:
cbench_data.parent.mkdir(parents=True, exist_ok=True)
extract_tar(tar, cbench_data.parent)
assert cbench_data.is_dir()
# Create the marker file to indicate that the directory is unpacked
# and ready to go.
(cbench_data / "unpacked").touch()
return True
# Thread lock to prevent race on download_cBench_runtime_data() from
# multi-threading. This works in tandem with the inter-process file lock - both
# are required.
_CBENCH_DOWNLOAD_THREAD_LOCK = Lock()
def _make_cBench_validator(
cmd: str,
linkopts: List[str],
os_env: Dict[str, str],
num_runs: int = 1,
compare_output: bool = True,
input_files: Optional[List[Path]] = None,
output_files: Optional[List[Path]] = None,
validate_result: Optional[
Callable[[BenchmarkExecutionResult], Optional[str]]
] = None,
pre_execution_callback: Optional[Callable[[Path], None]] = None,
sanitizer: Optional[LlvmSanitizer] = None,
flakiness: int = 5,
) -> ValidationCallback:
"""Construct a validation callback for a cBench benchmark. See validator() for usage."""
input_files = input_files or []
output_files = output_files or []
def validator_cb(env: "LlvmEnv") -> Optional[ValidationError]: # noqa: F821
"""The validation callback."""
with _CBENCH_DOWNLOAD_THREAD_LOCK:
with fasteners.InterProcessLock(cache_path(".cbench-v1-runtime-data.LOCK")):
download_cBench_runtime_data()
cbench_data = site_data_path("llvm-v0/cbench-v1-runtime-data/runtime_data")
for input_file_name in input_files:
path = cbench_data / input_file_name
if not path.is_file():
raise FileNotFoundError(f"Required benchmark input not found: {path}")
# Create a temporary working directory to execute the benchmark in.
with tempfile.TemporaryDirectory(dir=env.service.connection.cache.path) as d:
cwd = Path(d)
# Expand shell variable substitutions in the benchmark command.
expanded_command = cmd.replace("$D", str(cbench_data))
# Translate the output file names into paths inside the working
# directory.
output_paths = [cwd / o for o in output_files]
if pre_execution_callback:
pre_execution_callback(cwd)
# Produce a gold-standard output using a reference version of
# the benchmark.
if compare_output or output_files:
gs_env = env.fork()
try:
# Reset to the original benchmark state and compile it.
gs_env.reset(benchmark=env.benchmark)
gs_env.write_bitcode(cwd / "benchmark.bc")
gold_standard = _compile_and_run_bitcode_file(
bitcode_file=cwd / "benchmark.bc",
cmd=expanded_command,
cwd=cwd,
num_runs=1,
# Use default optimizations for gold standard.
linkopts=linkopts + ["-O2"],
# Always assume safe.
sanitizer=None,
env=os_env,
)
if gold_standard.error:
return ValidationError(
type=f"Gold standard: {gold_standard.error.type}",
data=gold_standard.error.data,
)
finally:
gs_env.close()
# Check that the reference run produced the expected output
# files.
for path in output_paths:
if not path.is_file():
try:
output = gold_standard.output
except UnicodeDecodeError:
output = "<binary>"
raise FileNotFoundError(
f"Expected file '{path.name}' not generated\n"
f"Benchmark: {env.benchmark}\n"
f"Command: {cmd}\n"
f"Output: {output}"
)
path.rename(f"{path}.gold_standard")
# Serialize the benchmark to a bitcode file that will then be
# compiled to a binary.
env.write_bitcode(cwd / "benchmark.bc")
outcome = _compile_and_run_bitcode_file(
bitcode_file=cwd / "benchmark.bc",
cmd=expanded_command,
cwd=cwd,
num_runs=num_runs,
linkopts=linkopts,
sanitizer=sanitizer,
env=os_env,
)
if outcome.error:
return outcome.error
# Run a user-specified validation hook.
if validate_result:
validate_result(outcome)
# Difftest the console output.
if compare_output and gold_standard.output != outcome.output:
return ValidationError(
type="Wrong output",
data={"expected": gold_standard.output, "actual": outcome.output},
)
# Difftest the output files.
for path in output_paths:
if not path.is_file():
return ValidationError(
type="Output not generated",
data={"path": path.name, "command": cmd},
)
with Popen(
["diff", str(path), f"{path}.gold_standard"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) as diff:
stdout, _ = diff.communicate(timeout=300)
if diff.returncode:
try:
stdout = stdout.decode("utf-8")
return ValidationError(
type="Wrong output (file)",
data={"path": path.name, "diff": stdout},
)
except UnicodeDecodeError:
return ValidationError(
type="Wrong output (file)",
data={"path": path.name, "diff": "<binary>"},
)
def flaky_wrapped_cb(env: "LlvmEnv") -> Optional[ValidationError]: # noqa: F821
"""Wrap the validation callback in a flakiness retry loop."""
for j in range(1, max(flakiness, 1) + 1):
try:
error = validator_cb(env)
if not error:
return
except TimeoutError:
# Timeout errors can be raised by the environment in case of a
# slow step / observation, and should be retried.
pass
# No point in repeating compilation failures as they are not flaky.
if error.type == "Compilation failed":
return error
logger.warning(
"Validation callback failed (%s), attempt=%d/%d",
error.type,
j,
flakiness,
)
return error
# The flaky_wrapped_cb() function takes an environment and produces a single
# error. We need the validator to produce an iterable of errors.
def adapt_validator_return_type(
env: "LlvmEnv", # noqa: F821
) -> Iterable[ValidationError]:
error = flaky_wrapped_cb(env)
if error:
yield error
return adapt_validator_return_type
def validator(
benchmark: str,
cmd: str,
data: Optional[List[str]] = None,
outs: Optional[List[str]] = None,
platforms: Optional[List[str]] = None,
compare_output: bool = True,
validate_result: Optional[
Callable[[BenchmarkExecutionResult], Optional[str]]
] = None,
linkopts: Optional[List[str]] = None,
env: Optional[Dict[str, str]] = None,
pre_execution_callback: Optional[Callable[[], None]] = None,
sanitizers: Optional[List[LlvmSanitizer]] = None,
) -> bool:
"""Declare a new benchmark validator.
TODO(cummins): Pull this out into a public API.
:param benchmark: The name of the benchmark that this validator supports.
:cmd: The shell command to run the validation. Variable substitution is
applied to this value as follows: :code:`$BIN` is replaced by the path
of the compiled binary and :code:`$D` is replaced with the path to the
benchmark's runtime data directory.
:data: A list of paths to input files.
:outs: A list of paths to output files.
:return: :code:`True` if the new validator was registered, else :code:`False`.
"""
platforms = platforms or ["linux", "macos"]
if {"darwin": "macos"}.get(sys.platform, sys.platform) not in platforms:
return False
infiles = data or []
outfiles = [Path(p) for p in outs or []]
linkopts = linkopts or []
env = env or {}
if sanitizers is None:
sanitizers = LlvmSanitizer
VALIDATORS[benchmark].append(
_make_cBench_validator(
cmd=cmd,
input_files=infiles,
output_files=outfiles,
compare_output=compare_output,
validate_result=validate_result,
linkopts=linkopts,
os_env=env,
pre_execution_callback=pre_execution_callback,
)
)
# Register additional validators using the sanitizers.
if sys.platform.startswith("linux"):
for sanitizer in sanitizers:
VALIDATORS[benchmark].append(
_make_cBench_validator(
cmd=cmd,
input_files=infiles,
output_files=outfiles,
compare_output=compare_output,
validate_result=validate_result,
linkopts=linkopts,
os_env=env,
pre_execution_callback=pre_execution_callback,
sanitizer=sanitizer,
)
)
# Create the BenchmarkDynamicConfig object.
cbench_data = site_data_path("llvm-v0/cbench-v1-runtime-data/runtime_data")
uri = BenchmarkUri.from_string(benchmark)
DYNAMIC_CONFIGS[uri.path].append(
BenchmarkDynamicConfig(
build_cmd=Command(
argument=["$CC", "$IN"]
+ llvm_benchmark.get_system_library_flags()
+ linkopts,
timeout_seconds=60,
outfile=["a.out"],
),
run_cmd=Command(
argument=cmd.replace("$BIN", "./a.out")
.replace("$D", str(cbench_data))
.split(),
timeout_seconds=300,
infile=["a.out", "_finfo_dataset"],
outfile=[str(s) for s in outfiles],
),
pre_run_cmd=[
Command(argument=["echo", "1", ">_finfo_dataset"], timeout_seconds=30),
],
)
)
return True
class CBenchDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path):
platform = {"darwin": "macos"}.get(sys.platform, sys.platform)
url, sha256 = _CBENCH_TARS[platform]
super().__init__(
name="benchmark://cbench-v1",
description="Runnable C benchmarks",
license="BSD 3-Clause",
references={
"Paper": "https://arxiv.org/pdf/1407.3487.pdf",
"Homepage": "https://ctuning.org/wiki/index.php/CTools:CBench",
},
tar_urls=[url],
tar_sha256=sha256,
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cbench-v1-manifest.bz2"
],
manifest_sha256="eeffd7593aeb696a160fd22e6b0c382198a65d0918b8440253ea458cfe927741",
strip_prefix="cBench-v1",
benchmark_file_suffix=".bc",
benchmark_class=Benchmark,
site_data_base=site_data_base,
sort_order=-1,
validatable="Partially",
)
def install(self):
super().install()
with _CBENCH_DOWNLOAD_THREAD_LOCK:
with fasteners.InterProcessLock(cache_path(".cbench-v1-runtime-data.LOCK")):
download_cBench_runtime_data()
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
benchmark = super().benchmark_from_parsed_uri(uri)
for val in VALIDATORS.get(str(uri), []):
benchmark.add_validation_callback(val)
# Parse the "dataset" parameter to determine the correct dynamic
# configuration to use.
if DYNAMIC_CONFIGS[uri.path]:
cfgs = DYNAMIC_CONFIGS[uri.path]
dataset = uri.params.get("dataset", ["0"])
try:
dataset_index = int(dataset[-1])
except (ValueError, TypeError) as e:
raise ValueError(f"Invalid dataset: {dataset[-1]}") from e
if dataset_index < 0 or dataset_index >= len(cfgs):
raise ValueError(f"Invalid dataset: {dataset_index}")
benchmark.proto.dynamic_config.MergeFrom(cfgs[dataset_index])
return benchmark
class CBenchLegacyDataset2(TarDatasetWithManifest):
def __init__(
self,
site_data_base: Path,
sort_order: int = 0,
name="benchmark://cbench-v1",
manifest_url="https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cbench-v1-manifest.bz2",
manifest_sha256="eeffd7593aeb696a160fd22e6b0c382198a65d0918b8440253ea458cfe927741",
deprecated=None,
):
platform = {"darwin": "macos"}.get(sys.platform, sys.platform)
url, sha256 = _CBENCH_TARS[platform]
super().__init__(
name=name,
description="Runnable C benchmarks",
license="BSD 3-Clause",
references={
"Paper": "https://arxiv.org/pdf/1407.3487.pdf",
"Homepage": "https://ctuning.org/wiki/index.php/CTools:CBench",
},
tar_urls=[url],
tar_sha256=sha256,
manifest_urls=[manifest_url],
manifest_sha256=manifest_sha256,
strip_prefix="cBench-v1",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
deprecated=deprecated,
validatable="Partially",
)
# URLs of the deprecated cBench datasets.
_CBENCH_LEGACY_TARS = {
"macos": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cBench-v0-macos.tar.bz2",
"072a730c86144a07bba948c49afe543e4f06351f1cb17f7de77f91d5c1a1b120",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cBench-v0-linux.tar.bz2",
"9b5838a90895579aab3b9375e8eeb3ed2ae58e0ad354fec7eb4f8b31ecb4a360",
),
}
class CBenchLegacyDataset(TarDatasetWithManifest):
# The difference between cbench-v0 and cbench-v1 is the arguments passed to
# clang when preparing the LLVM bitcodes:
#
# - v0: `-O0 -Xclang -disable-O0-optnone`.
# - v1: `-O1 -Xclang -Xclang -disable-llvm-passes`.
#
# The key difference with is that in v0, the generated IR functions were
# annotated with a `noinline` attribute that prevented inline. In v1 that is
# no longer the case.
def __init__(self, site_data_base: Path):
platform = {"darwin": "macos"}.get(sys.platform, sys.platform)
url, sha256 = _CBENCH_LEGACY_TARS[platform]
super().__init__(
name="benchmark://cBench-v0",
description="Runnable C benchmarks",
license="BSD 3-Clause",
references={
"Paper": "https://arxiv.org/pdf/1407.3487.pdf",
"Homepage": "https://ctuning.org/wiki/index.php/CTools:CBench",
},
tar_urls=[url],
tar_sha256=sha256,
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cBench-v0-manifest.bz2"
],
manifest_sha256="635b94eeb2784dfedb3b53fd8f84517c3b4b95d851ddb662d4c1058c72dc81e0",
strip_prefix="cBench-v0",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
deprecated="Please use 'benchmark://cbench-v1'",
)
# ===============================
# Definition of cBench validators
# ===============================
# A map from benchmark name to validation callbacks.
VALIDATORS: Dict[str, List[ValidationCallback]] = defaultdict(list)
# A map from cBench benchmark path to a list of BenchmarkDynamicConfig messages,
# one per dataset.
DYNAMIC_CONFIGS: Dict[str, List[BenchmarkDynamicConfig]] = defaultdict(list)
def validate_sha_output(result: BenchmarkExecutionResult) -> Optional[str]:
"""SHA benchmark prints 5 random hex strings. Normally these hex strings are
16 characters but occasionally they are less (presumably because of a
leading zero being omitted).
"""
try:
if not re.match(
r"[0-9a-f]{0,16} [0-9a-f]{0,16} [0-9a-f]{0,16} [0-9a-f]{0,16} [0-9a-f]{0,16}",
result.output.rstrip(),
):
return "Failed to parse hex output"
except UnicodeDecodeError:
return "Failed to parse unicode output"
def setup_ghostscript_library_files(dataset_id: int) -> Callable[[Path], None]:
"""Make a pre-execution setup hook for ghostscript."""
def setup(cwd: Path):
cbench_data = site_data_path("llvm-v0/cbench-v1-runtime-data/runtime_data")
# Copy the input data file into the current directory since ghostscript
# doesn't like long input paths.
shutil.copyfile(
cbench_data / "office_data" / f"{dataset_id}.ps", cwd / "input.ps"
)
# Ghostscript doesn't like the library files being symlinks so copy them
# into the working directory as regular files.
for path in (cbench_data / "ghostscript").iterdir():
if path.name.endswith(".ps"):
shutil.copyfile(path, cwd / path.name)
return setup
validator(
benchmark="benchmark://cbench-v1/bitcount",
cmd="$BIN 1125000",
)
validator(
benchmark="benchmark://cbench-v1/bitcount",
cmd="$BIN 512",
)
# The cBench benchmarks contain 20 runtime datasets. When use all 20 datasets
# when validating the correctness of one of these benchmarks, we use all 20
# datasets. However, this takes a long time, so for CI jobs (determined by the
# presence of the $CI environment variable), we use only 2 datasets for testing.
NUM_DATASETS = 2 if os.environ.get("CI", "") == "1" else 20
for i in range(1, NUM_DATASETS + 1):
# NOTE(cummins): Disabled due to timeout errors, further investigation
# needed.
#
# validator(
# benchmark="benchmark://cbench-v1/adpcm",
# cmd=f"$BIN $D/telecom_data/{i}.adpcm",
# data=[f"telecom_data/{i}.adpcm"],
# )
#
# validator(
# benchmark="benchmark://cbench-v1/adpcm",
# cmd=f"$BIN $D/telecom_data/{i}.pcm",
# data=[f"telecom_data/{i}.pcm"],
# )
validator(
benchmark="benchmark://cbench-v1/blowfish",
cmd=f"$BIN d $D/office_data/{i}.benc output.txt 1234567890abcdeffedcba0987654321",
data=[f"office_data/{i}.benc"],
outs=["output.txt"],
)
validator(
benchmark="benchmark://cbench-v1/bzip2",
cmd=f"$BIN -d -k -f -c $D/bzip2_data/{i}.bz2",
data=[f"bzip2_data/{i}.bz2"],
)
validator(
benchmark="benchmark://cbench-v1/crc32",
cmd=f"$BIN $D/telecom_data/{i}.pcm",
data=[f"telecom_data/{i}.pcm"],
)
validator(
benchmark="benchmark://cbench-v1/dijkstra",
cmd=f"$BIN $D/network_dijkstra_data/{i}.dat",
data=[f"network_dijkstra_data/{i}.dat"],
)
validator(
benchmark="benchmark://cbench-v1/gsm",
cmd=f"$BIN -fps -c $D/telecom_gsm_data/{i}.au",
data=[f"telecom_gsm_data/{i}.au"],
)
# NOTE(cummins): ispell fails with returncode 1 and no output when run
# under safe optimizations.
#
# validator(
# benchmark="benchmark://cbench-v1/ispell",
# cmd=f"$BIN -a -d americanmed+ $D/office_data/{i}.txt",
# data = [f"office_data/{i}.txt"],
# )
validator(
benchmark="benchmark://cbench-v1/jpeg-c",
cmd=f"$BIN -dct int -progressive -outfile output.jpeg $D/consumer_jpeg_data/{i}.ppm",
data=[f"consumer_jpeg_data/{i}.ppm"],
outs=["output.jpeg"],
# NOTE(cummins): AddressSanitizer disabled because of
# global-buffer-overflow in regular build.
sanitizers=[LlvmSanitizer.TSAN, LlvmSanitizer.UBSAN],
)
validator(
benchmark="benchmark://cbench-v1/jpeg-d",
cmd=f"$BIN -dct int -outfile output.ppm $D/consumer_jpeg_data/{i}.jpg",
data=[f"consumer_jpeg_data/{i}.jpg"],
outs=["output.ppm"],
)
validator(
benchmark="benchmark://cbench-v1/patricia",
cmd=f"$BIN $D/network_patricia_data/{i}.udp",
data=[f"network_patricia_data/{i}.udp"],
env={
# NOTE(cummins): Benchmark leaks when executed with safe optimizations.
"ASAN_OPTIONS": "detect_leaks=0",
},
)
validator(
benchmark="benchmark://cbench-v1/qsort",
cmd=f"$BIN $D/automotive_qsort_data/{i}.dat",
data=[f"automotive_qsort_data/{i}.dat"],
outs=["sorted_output.dat"],
linkopts=["-lm"],
)
# NOTE(cummins): Rijndael benchmark disabled due to memory errors under
# basic optimizations.
#
# validator(benchmark="benchmark://cbench-v1/rijndael", cmd=f"$BIN
# $D/office_data/{i}.enc output.dec d
# 1234567890abcdeffedcba09876543211234567890abcdeffedcba0987654321",
# data=[f"office_data/{i}.enc"], outs=["output.dec"],
# )
#
# validator(benchmark="benchmark://cbench-v1/rijndael", cmd=f"$BIN
# $D/office_data/{i}.txt output.enc e
# 1234567890abcdeffedcba09876543211234567890abcdeffedcba0987654321",
# data=[f"office_data/{i}.txt"], outs=["output.enc"],
# )
validator(
benchmark="benchmark://cbench-v1/sha",
cmd=f"$BIN $D/office_data/{i}.txt",
data=[f"office_data/{i}.txt"],
compare_output=False,
validate_result=validate_sha_output,
)
validator(
benchmark="benchmark://cbench-v1/stringsearch",
cmd=f"$BIN $D/office_data/{i}.txt $D/office_data/{i}.s.txt output.txt",
data=[f"office_data/{i}.txt"],
outs=["output.txt"],
env={
# NOTE(cummins): Benchmark leaks when executed with safe optimizations.
"ASAN_OPTIONS": "detect_leaks=0",
},
linkopts=["-lm"],
)
# NOTE(cummins): The stringsearch2 benchmark has a very long execution time.
# Use only a single input to keep the validation time reasonable. I have
# also observed Segmentation fault on gold standard using 4.txt and 6.txt.
if i == 1:
validator(
benchmark="benchmark://cbench-v1/stringsearch2",
cmd=f"$BIN $D/office_data/{i}.txt $D/office_data/{i}.s.txt output.txt",
data=[f"office_data/{i}.txt"],
outs=["output.txt"],
env={
# NOTE(cummins): Benchmark leaks when executed with safe optimizations.
"ASAN_OPTIONS": "detect_leaks=0",
},
# TSAN disabled because of extremely long execution leading to
# timeouts.
sanitizers=[LlvmSanitizer.ASAN, LlvmSanitizer.MSAN, LlvmSanitizer.UBSAN],
)
validator(
benchmark="benchmark://cbench-v1/susan",
cmd=f"$BIN $D/automotive_susan_data/{i}.pgm output_large.corners.pgm -c",
data=[f"automotive_susan_data/{i}.pgm"],
outs=["output_large.corners.pgm"],
linkopts=["-lm"],
)
validator(
benchmark="benchmark://cbench-v1/tiff2bw",
cmd=f"$BIN $D/consumer_tiff_data/{i}.tif output.tif",
data=[f"consumer_tiff_data/{i}.tif"],
outs=["output.tif"],
linkopts=["-lm"],
env={
# NOTE(cummins): Benchmark leaks when executed with safe optimizations.
"ASAN_OPTIONS": "detect_leaks=0",
},
)
validator(
benchmark="benchmark://cbench-v1/tiff2rgba",
cmd=f"$BIN $D/consumer_tiff_data/{i}.tif output.tif",
data=[f"consumer_tiff_data/{i}.tif"],
outs=["output.tif"],
linkopts=["-lm"],
)
validator(
benchmark="benchmark://cbench-v1/tiffdither",
cmd=f"$BIN $D/consumer_tiff_data/{i}.bw.tif out.tif",
data=[f"consumer_tiff_data/{i}.bw.tif"],
outs=["out.tif"],
linkopts=["-lm"],
)
validator(
benchmark="benchmark://cbench-v1/tiffmedian",
cmd=f"$BIN $D/consumer_tiff_data/{i}.nocomp.tif output.tif",
data=[f"consumer_tiff_data/{i}.nocomp.tif"],
outs=["output.tif"],
linkopts=["-lm"],
)
# NOTE(cummins): On macOS the following benchmarks abort with an illegal
# hardware instruction error.
# if sys.platform != "darwin":
# validator(
# benchmark="benchmark://cbench-v1/lame",
# cmd=f"$BIN $D/consumer_data/{i}.wav output.mp3",
# data=[f"consumer_data/{i}.wav"],
# outs=["output.mp3"],
# compare_output=False,
# linkopts=["-lm"],
# )
# NOTE(cummins): Segfault on gold standard.
#
# validator(
# benchmark="benchmark://cbench-v1/ghostscript",
# cmd="$BIN -sDEVICE=ppm -dNOPAUSE -dQUIET -sOutputFile=output.ppm -- input.ps",
# data=[f"office_data/{i}.ps"],
# outs=["output.ppm"],
# linkopts=["-lm", "-lz"],
# pre_execution_callback=setup_ghostscript_library_files(i),
# )
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/cbench.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import subprocess
from concurrent.futures import as_completed
from pathlib import Path
from typing import Iterable
from compiler_gym.datasets import Benchmark, TarDatasetWithManifest
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm.llvm_benchmark import ClangInvocation
from compiler_gym.util import thread_pool
from compiler_gym.util.filesystem import atomic_file_write
URIS = [
"benchmark://chstone-v0/adpcm",
"benchmark://chstone-v0/aes",
"benchmark://chstone-v0/blowfish",
"benchmark://chstone-v0/dfadd",
"benchmark://chstone-v0/dfdiv",
"benchmark://chstone-v0/dfmul",
"benchmark://chstone-v0/dfsin",
"benchmark://chstone-v0/gsm",
"benchmark://chstone-v0/jpeg",
"benchmark://chstone-v0/mips",
"benchmark://chstone-v0/motion",
"benchmark://chstone-v0/sha",
]
class CHStoneDataset(TarDatasetWithManifest):
"""A dataset of C programs curated from GitHub source code.
The dataset is from:
Hara, Yuko, Hiroyuki Tomiyama, Shinya Honda, Hiroaki Takada, and Katsuya
Ishii. "Chstone: A benchmark program suite for practical c-based
high-level synthesis." In 2008 IEEE International Symposium on Circuits
and Systems, pp. 1192-1195. IEEE, 2008.
And is available at:
http://www.ertl.jp/chstone/
"""
def __init__(
self,
site_data_base: Path,
sort_order: int = 0,
):
super().__init__(
name="benchmark://chstone-v0",
description="Benchmarks for C-based High-Level Synthesis",
references={
"Paper": "http://www.yxi.com/applications/iscas2008-300_1027.pdf",
"Homepage": "http://www.ertl.jp/chstone/",
},
license="Mixture of open source and public domain licenses",
site_data_base=site_data_base,
tar_urls=[
"https://github.com/ChrisCummins/patmos_HLS/archive/e62d878ceb91e5a18007ca2e0a9602ee44ff7d59.tar.gz"
],
tar_sha256="f7acab9d3c3dc7b971e62c8454bc909d84bddb6d0a96378e41beb94231739acb",
strip_prefix="patmos_HLS-e62d878ceb91e5a18007ca2e0a9602ee44ff7d59/benchmarks/CHStone",
tar_compression="gz",
benchmark_file_suffix=".bc",
sort_order=sort_order,
# We provide our own manifest.
manifest_urls=[],
manifest_sha256="",
)
def benchmark_uris(self) -> Iterable[str]:
yield from URIS
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
benchmark_name = uri.path[1:]
if not benchmark_name:
raise LookupError(f"No benchmark specified: {uri}")
bitcode_abspath = self.dataset_root / f"{benchmark_name}.bc"
# Most of the source files are named after the parent directory, but not
# all.
c_file_name = {
"blowfish": "bf.c",
"motion": "mpeg2.c",
"sha": "sha_driver.c",
"jpeg": "main.c",
}.get(benchmark_name, f"{benchmark_name}.c")
c_file_abspath = self.dataset_root / benchmark_name / c_file_name
# If the file does not exist, compile it on-demand.
if not bitcode_abspath.is_file():
if not c_file_abspath.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {c_file_abspath})"
)
with atomic_file_write(bitcode_abspath) as tmp_path:
compile_cmd = ClangInvocation.from_c_file(
c_file_abspath,
copt=[
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
],
).command(outpath=tmp_path)
subprocess.check_call(compile_cmd, timeout=300)
return BenchmarkWithSource.create(
uri, bitcode_abspath, "function.c", c_file_abspath
)
@property
def size(self) -> int:
return len(URIS)
def compile_all(self):
n = self.size
executor = thread_pool.get_thread_pool_executor()
# Since the dataset is lazily compiled, simply iterating over the full
# set of URIs will compile everything. Do this in parallel.
futures = (
executor.submit(self.benchmark, uri) for uri in self.benchmark_uris()
)
for i, future in enumerate(as_completed(futures), start=1):
future.result()
print(
f"\r\033[KCompiled {i} of {n} programs ({i/n:.1%} complete)",
flush=True,
end="",
)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/chstone.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import subprocess
from concurrent.futures import as_completed
from pathlib import Path
from compiler_gym.datasets import Benchmark, TarDataset, TarDatasetWithManifest
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm.llvm_benchmark import (
ClangInvocation,
get_system_library_flags,
)
from compiler_gym.service.proto import BenchmarkDynamicConfig, Command
from compiler_gym.util import thread_pool
from compiler_gym.util.filesystem import atomic_file_write
class JotaiBenchDataset(TarDatasetWithManifest):
"""A dataset of C programs curated from GitHub source code.
The dataset is from:
da Silva, Anderson Faustino, Bruno Conde Kind, José Wesley de Souza
Magalhaes, Jerônimo Nunes Rocha, Breno Campos Ferreira Guimaraes, and
Fernando Magno Quinão Pereira. "ANGHABENCH: A Suite with One Million
Compilable C Benchmarks for Code-Size Reduction." In 2021 IEEE/ACM
International Symposium on Code Generation and Optimization (CGO),
pp. 378-390. IEEE, 2021.
And is available at:
http://cuda.dcc.ufmg.br/Jotai/src/
Installation
------------
The JotaiBench dataset consists of C functions that are compiled to LLVM-IR
on-demand and cached. The first time each benchmark is used there is an
overhead of compiling it from C to bitcode. This is a one-off cost.
"""
def __init__(
self,
site_data_base: Path,
):
super().__init__(
name="benchmark://jotaibench-v0",
description="Compile-only C/C++ functions extracted from GitHub",
references={
"Paper": "https://homepages.dcc.ufmg.br/~fernando/publications/papers/FaustinoCGO21.pdf",
"Homepage": "http://cuda.dcc.ufmg.br/angha/",
},
license="GNU General Public License v3.0 (GPLv3)",
site_data_base=site_data_base,
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-jotaibench-v0.bz2"
],
manifest_sha256="ac4ee456e52073964d472d3e3969058b2f3052f8a4b402719013a3c603eb4b62",
tar_urls=[
"https://github.com/ChrisCummins/jotai-benchmarks/raw/ca26ccd27afecf38919c1e101c64e3cc17e39631/benchmarks/jotaibench.bz2"
],
tar_sha256="b5a51af3d4e2f77a66001635ec64ed321e0ece19873c4a888040859af7556401",
strip_prefix="jotaibench/jotaibench-v0",
tar_compression="bz2",
benchmark_file_suffix=".c",
sort_order=0,
)
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
benchmark_name = uri.path[1:]
if not benchmark_name:
raise LookupError(f"No benchmark specified: {uri}")
# The absolute path of the file, without an extension.
path_stem = self.dataset_root / benchmark_name
bitcode_abspath = Path(f"{path_stem}.bc")
c_file_abspath = Path(f"{path_stem}.c")
# If the file does not exist, compile it on-demand.
if not bitcode_abspath.is_file():
if not c_file_abspath.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {c_file_abspath})"
)
with atomic_file_write(bitcode_abspath) as tmp_path:
compile_cmd = ClangInvocation.from_c_file(
c_file_abspath,
copt=[
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
],
).command(outpath=tmp_path)
subprocess.check_call(compile_cmd, timeout=300)
return BenchmarkWithSource.create(
uri, bitcode_abspath, "function.c", c_file_abspath
)
def compile_all(self):
n = self.size
executor = thread_pool.get_thread_pool_executor()
# Since the dataset is lazily compiled, simply iterating over the full
# set of URIs will compile everything. Do this in parallel.
futures = (
executor.submit(self.benchmark, uri) for uri in self.benchmark_uris()
)
for i, future in enumerate(as_completed(futures), start=1):
future.result()
print(
f"\r\033[KCompiled {i} of {n} programs ({i/n:.1%} complete)",
flush=True,
end="",
)
class JotaiBenchRunnableDataset(TarDataset):
def __init__(
self,
site_data_base: Path,
):
super().__init__(
name="benchmark://jotai-runnable-v0",
description="Runnable C/C++ functions extracted from GitHub",
references={
"Paper": "https://homepages.dcc.ufmg.br/~fernando/publications/papers/FaustinoCGO21.pdf",
"Homepage": "http://cuda.dcc.ufmg.br/angha/",
},
license="GNU General Public License v3.0 (GPLv3)",
site_data_base=site_data_base,
tar_urls=[
"https://github.com/lac-dcc/jotai-benchmarks/blob/main/benchmarks/jotaibench.bz2?raw=true"
],
tar_sha256="b5a51af3d4e2f77a66001635ec64ed321e0ece19873c4a888040859af7556401",
strip_prefix="jotaibench-v0",
tar_compression="bz2",
benchmark_file_suffix=".c",
)
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
benchmark_name = uri.path[1:]
if not benchmark_name:
raise LookupError(f"No benchmark specified: {uri}")
# The absolute path of the file, without an extension.
path_stem = self.dataset_root / benchmark_name
bitcode_abspath = Path(f"{path_stem}.bc")
c_file_abspath = Path(f"{path_stem}.c")
# If the file does not exist, compile it to a bitcode file on-demand.
if not bitcode_abspath.is_file():
if not c_file_abspath.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {c_file_abspath})"
)
with atomic_file_write(bitcode_abspath) as tmp_path:
compile_cmd = ClangInvocation.from_c_file(
c_file_abspath,
copt=[
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
],
).command(outpath=tmp_path)
subprocess.check_call(compile_cmd, timeout=300)
benchmark = BenchmarkWithSource.create(
uri, bitcode_abspath, "function.c", c_file_abspath
)
# This is what makes a benchmark "runnable".
benchmark.proto.dynamic_config.MergeFrom(
BenchmarkDynamicConfig(
build_cmd=Command(
argument=["$CC", "$IN"] + get_system_library_flags(),
timeout_seconds=30,
outfile=["a.out"],
),
run_cmd=Command(
argument=["./a.out 0"],
timeout_seconds=30,
infile=[],
outfile=[],
),
)
)
return benchmark
def compile_all(self):
n = self.size
executor = thread_pool.get_thread_pool_executor()
# Since the dataset is lazily compiled, simply iterating over the full
# set of URIs will compile everything. Do this in parallel.
futures = (
executor.submit(self.benchmark, uri) for uri in self.benchmark_uris()
)
for i, future in enumerate(as_completed(futures), start=1):
future.result()
print(
f"\r\033[KCompiled {i} of {n} programs ({i/n:.1%} complete)",
flush=True,
end="",
)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/jotaibench.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import subprocess
import sys
from concurrent.futures import as_completed
from pathlib import Path
from compiler_gym.datasets import Benchmark, TarDatasetWithManifest
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm.llvm_benchmark import ClangInvocation
from compiler_gym.errors import BenchmarkInitError
from compiler_gym.util import thread_pool
from compiler_gym.util.commands import Popen
from compiler_gym.util.download import download
from compiler_gym.util.filesystem import atomic_file_write
from compiler_gym.util.truncate import truncate
logger = logging.getLogger(__name__)
class POJ104Dataset(TarDatasetWithManifest):
"""The POJ-104 dataset contains 52000 C++ programs implementing 104
different algorithms with 500 examples of each.
The dataset is from:
Lili Mou, Ge Li, Lu Zhang, Tao Wang, Zhi Jin. "Convolutional neural
networks over tree structures for programming language processing." To
appear in Proceedings of 30th AAAI Conference on Artificial
Intelligence, 2016.
And is available at:
https://sites.google.com/site/treebasedcnn/
"""
def __init__(self, site_data_base: Path, sort_order: int = 0):
manifest_url, manifest_sha256 = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-poj104-v1-macos-manifest.bz2",
"74db443f225478933dd0adf3f821fd4e615089eeaa90596c19d9d1af7006a801",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-poj104-v1-linux-manifest.bz2",
"ee6253ee826e171816105e76fa78c0d3cbd319ef66e10da4bcf9cf8a78e12ab9",
),
}[sys.platform]
super().__init__(
name="benchmark://poj104-v1",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-poj104-v1.tar.gz",
"https://drive.google.com/u/0/uc?id=0B2i-vWnOu7MxVlJwQXN6eVNONUU&export=download",
],
tar_sha256="c0b8ef3ee9c9159c882dc9337cb46da0e612a28e24852a83f8a1cd68c838f390",
tar_compression="gz",
manifest_urls=[manifest_url],
manifest_sha256=manifest_sha256,
references={
"Paper": "https://ojs.aaai.org/index.php/AAAI/article/download/10139/9998",
"Homepage": "https://sites.google.com/site/treebasedcnn/",
},
license="BSD 3-Clause",
strip_prefix="ProgramData",
description="Solutions to programming programs",
benchmark_file_suffix=".txt",
site_data_base=site_data_base,
sort_order=sort_order,
)
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
# The absolute path of the file, without an extension.
path_stem = os.path.normpath(f"{self.dataset_root}/{uri.path}")
# If the file does not exist, compile it on-demand.
bitcode_path = Path(f"{path_stem}.bc")
cc_file_path = Path(f"{path_stem}.txt")
if not bitcode_path.is_file():
if not cc_file_path.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {cc_file_path})"
)
# Load the C++ source into memory and pre-process it.
with open(cc_file_path) as f:
src = self.preprocess_poj104_source(f.read())
# Compile the C++ source into a bitcode file.
with atomic_file_write(bitcode_path) as tmp_bitcode_path:
compile_cmd = ClangInvocation.from_c_file(
"-",
copt=[
"-xc++",
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
# Some of the programs use the gets() function that was
# deprecated in C++11 and removed in C++14.
"-std=c++11",
],
).command(outpath=tmp_bitcode_path)
logger.debug("Exec %s", compile_cmd)
try:
with Popen(
compile_cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as clang:
_, stderr = clang.communicate(
input=src.encode("utf-8"), timeout=300
)
except subprocess.TimeoutExpired:
raise BenchmarkInitError(f"Benchmark compilation timed out: {uri}")
if clang.returncode:
compile_cmd = " ".join(compile_cmd)
error = truncate(stderr.decode("utf-8"), max_lines=20, max_line_len=100)
if tmp_bitcode_path.is_file():
tmp_bitcode_path.unlink()
raise BenchmarkInitError(
f"Compilation job failed!\n"
f"Command: {compile_cmd}\n"
f"Error: {error}"
)
if not bitcode_path.is_file():
raise BenchmarkInitError(
f"Compilation job failed to produce output file!\nCommand: {compile_cmd}"
)
return BenchmarkWithSource.create(uri, bitcode_path, "source.cc", cc_file_path)
@staticmethod
def preprocess_poj104_source(src: str) -> str:
"""Pre-process a POJ-104 C++ source file for compilation."""
# Clean up declaration of main function. Many are missing a return type
# declaration, or use an incorrect void return type.
src = src.replace("void main", "int main")
src = src.replace("\nmain", "int main")
if src.startswith("main"):
src = f"int {src}"
# Pull in the standard library.
if sys.platform == "linux":
header = "#include <bits/stdc++.h>\n" "using namespace std;\n"
else:
# Download a bits/stdc++ implementation for macOS.
header = download(
"https://raw.githubusercontent.com/tekfyl/bits-stdc-.h-for-mac/e1193f4470514d82ea19c3cc1357116fadaa2a4e/stdc%2B%2B.h",
sha256="b4d9b031d56d89a2b58b5ed80fa9943aa92420d6aed0835747c9a5584469afeb",
).decode("utf-8")
# These defines provide values for commonly undefined symbols. Defining
# these macros increases the number of POJ-104 programs that compile
# from 49,302 to 49,821 (+519) on linux.
defines = "#define LEN 128\n" "#define MAX_LENGTH 1024\n" "#define MAX 1024\n"
return header + defines + src
def compile_all(self):
n = self.size
executor = thread_pool.get_thread_pool_executor()
# Since the dataset is lazily compiled, simply iterating over the full
# set of URIs will compile everything. Do this in parallel.
futures = (
executor.submit(self.benchmark, uri) for uri in self.benchmark_uris()
)
for i, future in enumerate(as_completed(futures), start=1):
future.result()
print(
f"\r\033[KCompiled {i} of {n} programs ({i/n:.2%} complete)",
flush=True,
end="",
)
class POJ104LegacyDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://poj104-v0",
tar_urls="https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-poj104-v0.tar.bz2",
tar_sha256="6254d629887f6b51efc1177788b0ce37339d5f3456fb8784415ed3b8c25cce27",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-poj104-v0-manifest.bz2"
],
manifest_sha256="ac3eaaad7d2878d871ed2b5c72a3f39c058ea6694989af5c86cd162414db750b",
references={
"Paper": "https://ojs.aaai.org/index.php/AAAI/article/download/10139/9998",
"Homepage": "https://sites.google.com/site/treebasedcnn/",
},
license="BSD 3-Clause",
strip_prefix="poj104-v0",
description="Solutions to programming programs",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
deprecated="Please update to benchmark://poj104-v1.",
)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/poj104.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import subprocess
from pathlib import Path
from typing import Iterable, List, Optional
import numpy as np
from compiler_gym.datasets import Benchmark, BenchmarkSource, Dataset
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm import llvm_benchmark
from compiler_gym.envs.llvm.llvm_benchmark import ClangInvocation
from compiler_gym.errors import BenchmarkInitError
from compiler_gym.service.proto import BenchmarkDynamicConfig, Command
from compiler_gym.util.commands import Popen, communicate
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.runfiles_path import runfiles_path
from compiler_gym.util.shell_format import plural
from compiler_gym.util.truncate import truncate
logger = logging.getLogger(__name__)
# The maximum value for the --seed argument to csmith.
UINT_MAX = (2**32) - 1
_CSMITH_BIN = runfiles_path("compiler_gym/third_party/csmith/csmith/bin/csmith")
_CSMITH_INCLUDES = runfiles_path(
"compiler_gym/third_party/csmith/csmith/include/csmith-2.3.0"
)
class CsmithBenchmark(BenchmarkWithSource):
"""A CSmith benchmark."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._src = None
self.proto.dynamic_config.MergeFrom(
BenchmarkDynamicConfig(
build_cmd=Command(
argument=["$CC", "$IN"] + llvm_benchmark.get_system_library_flags(),
outfile=["a.out"],
timeout_seconds=60,
),
run_cmd=Command(
argument=["./a.out"],
timeout_seconds=300,
),
)
)
@classmethod
def create(cls, uri: str, bitcode: bytes, src: bytes) -> Benchmark:
"""Create a benchmark from paths."""
benchmark = cls.from_file_contents(uri, bitcode)
benchmark._src = src # pylint: disable=protected-access
return benchmark
@memoized_property
def sources(self) -> Iterable[BenchmarkSource]:
return [
BenchmarkSource(filename="source.c", contents=self._src),
]
@property
def source(self) -> str:
"""Return the single source file contents as a string."""
return self._src.decode("utf-8")
class CsmithDataset(Dataset):
"""A dataset which uses Csmith to generate programs.
Csmith is a tool that can generate random conformant C99 programs. It is
described in the publication:
Yang, Xuejun, Yang Chen, Eric Eide, and John Regehr. "Finding and
understanding bugs in C compilers." In Proceedings of the 32nd ACM
SIGPLAN conference on Programming Language Design and Implementation
(PLDI), pp. 283-294. 2011.
For up-to-date information about Csmith, see:
https://embed.cs.utah.edu/csmith/
Note that Csmith is a tool that is used to find errors in compilers. As
such, there is a higher likelihood that the benchmark cannot be used for an
environment and that :meth:`env.reset()
<compiler_gym.envs.CompilerEnv.reset>` will raise :class:`BenchmarkInitError
<compiler_gym.datasets.BenchmarkInitError>`.
"""
def __init__(
self,
site_data_base: Path,
sort_order: int = 0,
csmith_bin: Optional[Path] = None,
csmith_includes: Optional[Path] = None,
):
"""Constructor.
:param site_data_base: The base path of a directory that will be used to
store installed files.
:param sort_order: An optional numeric value that should be used to
order this dataset relative to others. Lowest value sorts first.
:param csmith_bin: The path of the Csmith binary to use. If not
provided, the version of Csmith shipped with CompilerGym is used.
:param csmith_includes: The path of the Csmith includes directory. If
not provided, the includes of the Csmith shipped with CompilerGym is
used.
"""
super().__init__(
name="generator://csmith-v0",
description="Random conformant C99 programs",
references={
"Paper": "http://web.cse.ohio-state.edu/~rountev.1/5343/pdf/pldi11.pdf",
"Homepage": "https://embed.cs.utah.edu/csmith/",
},
license="BSD",
site_data_base=site_data_base,
sort_order=sort_order,
benchmark_class=CsmithBenchmark,
)
self.csmith_bin_path = csmith_bin or _CSMITH_BIN
self.csmith_includes_path = csmith_includes or _CSMITH_INCLUDES
# The command that is used to compile an LLVM-IR bitcode file from a
# Csmith input. Reads from stdin, writes to stdout.
self.clang_compile_command: List[str] = ClangInvocation.from_c_file(
"-", # Read from stdin.
copt=[
"-xc", # The C programming language.
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
f"-I{self.csmith_includes_path}", # Include the Csmith headers.
],
).command(
outpath="-" # Write to stdout.
)
@property
def size(self) -> int:
# Actually 2^32 - 1, but practically infinite for all intents and
# purposes.
return 0
def benchmark_uris(self) -> Iterable[str]:
return (f"{self.name}/{i}" for i in range(UINT_MAX))
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> CsmithBenchmark:
seed = int(uri.path[1:])
return self.benchmark_from_seed(seed)
def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark:
seed = random_state.integers(UINT_MAX)
return self.benchmark_from_seed(seed)
def benchmark_from_seed(
self, seed: int, max_retries: int = 3, retry_count: int = 0
) -> CsmithBenchmark:
"""Get a benchmark from a uint32 seed.
:param seed: A number in the range 0 <= n < 2^32.
:return: A benchmark instance.
:raises OSError: If Csmith fails.
:raises BenchmarkInitError: If the C program generated by Csmith cannot
be lowered to LLVM-IR.
"""
if retry_count >= max_retries:
raise OSError(
f"Csmith failed after {retry_count} {plural(retry_count, 'attempt', 'attempts')} "
f"with seed {seed}"
)
self.install()
# Run csmith with the given seed and pipe the output to clang to
# assemble a bitcode.
logger.debug("Exec csmith --seed %d", seed)
try:
with Popen(
[str(self.csmith_bin_path), "--seed", str(seed)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as csmith:
# Generate the C source.
src, stderr = communicate(csmith, timeout=300)
if csmith.returncode:
try:
stderr = "\n".join(
truncate(
stderr.decode("utf-8"), max_line_len=200, max_lines=20
)
)
logger.warning("Csmith failed with seed %d: %s", seed, stderr)
except UnicodeDecodeError:
# Failed to interpret the stderr output, generate a generic
# error message.
logger.warning("Csmith failed with seed %d", seed)
return self.benchmark_from_seed(
seed, max_retries=max_retries, retry_count=retry_count + 1
)
# Compile to IR.
with Popen(
self.clang_compile_command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
) as clang:
stdout, _ = communicate(clang, input=src, timeout=300)
if clang.returncode:
compile_cmd = " ".join(self.clang_compile_command)
raise BenchmarkInitError(
f"Compilation job failed!\n"
f"Csmith seed: {seed}\n"
f"Command: {compile_cmd}\n"
)
except subprocess.TimeoutExpired:
raise BenchmarkInitError(
f"Benchmark generation using seed {seed} timed out"
)
return self.benchmark_class.create(f"{self.name}/{seed}", stdout, src)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/csmith.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
from pathlib import Path
from typing import Iterable, Optional
from compiler_gym.datasets import Dataset, TarDatasetWithManifest
from compiler_gym.envs.llvm.datasets.anghabench import AnghaBenchDataset
from compiler_gym.envs.llvm.datasets.cbench import (
CBenchDataset,
CBenchLegacyDataset,
CBenchLegacyDataset2,
)
from compiler_gym.envs.llvm.datasets.chstone import CHStoneDataset
from compiler_gym.envs.llvm.datasets.clgen import CLgenDataset
from compiler_gym.envs.llvm.datasets.csmith import CsmithBenchmark, CsmithDataset
from compiler_gym.envs.llvm.datasets.jotaibench import JotaiBenchDataset
from compiler_gym.envs.llvm.datasets.llvm_stress import LlvmStressDataset
from compiler_gym.envs.llvm.datasets.poj104 import POJ104Dataset, POJ104LegacyDataset
from compiler_gym.util.runfiles_path import site_data_path
class BlasDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://blas-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-blas-v0.tar.bz2"
],
tar_sha256="e724a8114709f8480adeb9873d48e426e8d9444b00cddce48e342b9f0f2b096d",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-blas-v0-manifest.bz2"
],
manifest_sha256="6946437dcb0da5fad3ed8a7fd83eb4294964198391d5537b1310e22d7ceebff4",
references={
"Paper": "https://strum355.netsoc.co/books/PDF/Basic%20Linear%20Algebra%20Subprograms%20for%20Fortran%20Usage%20-%20BLAS%20(1979).pdf",
"Homepage": "http://www.netlib.org/blas/",
},
license="BSD 3-Clause",
strip_prefix="blas-v0",
description="Basic linear algebra kernels",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
class GitHubDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
manifest_url, manifest_sha256 = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-github-v0-macos-manifest.bz2",
"10d933a7d608248be286d756b27813794789f7b87d8561c241d0897fb3238503",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-github-v0-linux-manifest.bz2",
"aede9ca78657b4694ada9a4592d93f0bbeb3b3bd0fff3b537209850228480d3b",
),
}[sys.platform]
super().__init__(
name="benchmark://github-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-github-v0.tar.bz2"
],
tar_sha256="880269dd7a5c2508ea222a2e54c318c38c8090eb105c0a87c595e9dd31720764",
manifest_urls=[manifest_url],
manifest_sha256=manifest_sha256,
license="CC BY 4.0",
references={
"Paper": "https://arxiv.org/pdf/2012.01470.pdf",
},
strip_prefix="github-v0",
description="Compile-only C/C++ objects from GitHub",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
class LinuxDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
manifest_url, manifest_sha256 = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-linux-v0-macos-manifest.bz2",
"dfc87b94c7a43e899e76507398a5af22178aebaebcb5d7e24e82088aeecb0690",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-linux-v0-linux-manifest.bz2",
"32ceb8576f683798010816ac605ee496f386ddbbe64be9e0796015d247a73f92",
),
}[sys.platform]
super().__init__(
name="benchmark://linux-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-linux-v0.tar.bz2"
],
tar_sha256="a1ae5c376af30ab042c9e54dc432f89ce75f9ebaee953bc19c08aff070f12566",
manifest_urls=[manifest_url],
manifest_sha256=manifest_sha256,
references={"Homepage": "https://www.linux.org/"},
license="GPL-2.0",
strip_prefix="linux-v0",
description="Compile-only object files from C Linux kernel",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
class MibenchDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://mibench-v1",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-mibench-v1.tar.bz2"
],
tar_sha256="795b80d3198bc96e394823a4cb294d256845beffccce52fea0e3446395212bb5",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-mibench-v0-manifest.bz2"
],
manifest_sha256="8ed985d685b48f444a3312cd84ccc5debda4a839850e442a3cdc93910ba0dc5f",
references={
"Paper": "http://vhosts.eecs.umich.edu/mibench/Publications/MiBench.pdf"
},
license="BSD 3-Clause",
strip_prefix="mibench-v1",
description="C benchmarks",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
class MibenchV0Dataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://mibench-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-mibench-v0.tar.bz2"
],
tar_sha256="128c090c40b955b99fdf766da167a5f642018fb35c16a1d082f63be2e977eb13",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-mibench-v0-manifest.bz2"
],
manifest_sha256="8ed985d685b48f444a3312cd84ccc5debda4a839850e442a3cdc93910ba0dc5f",
references={
"Paper": "http://vhosts.eecs.umich.edu/mibench/Publications/MiBench.pdf"
},
license="BSD 3-Clause",
strip_prefix="mibench-v0",
description="C benchmarks",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
deprecated="Please use mibench-v1",
)
class NPBDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://npb-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-npb-v0.tar.bz2"
],
tar_sha256="793ac2e7a4f4ed83709e8a270371e65b724da09eaa0095c52e7f4209f63bb1f2",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-npb-v0-manifest.bz2"
],
manifest_sha256="89eccb7f1b0b9e1f82b9b900b9f686ff5b189a2a67a4f8969a15901cd315dba2",
references={
"Paper": "http://optout.csc.ncsu.edu/~mueller/codeopt/codeopt05/projects/www4.ncsu.edu/~pgauria/csc791a/papers/NAS-95-020.pdf"
},
license="NASA Open Source Agreement v1.3",
strip_prefix="npb-v0",
description="NASA Parallel Benchmarks",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
class OpenCVDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://opencv-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-opencv-v0.tar.bz2"
],
tar_sha256="003df853bd58df93572862ca2f934c7b129db2a3573bcae69a2e59431037205c",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-opencv-v0-manifest.bz2"
],
manifest_sha256="8de96f722fab18f3a2a74db74b4038c7947fe8b3da867c9260206fdf5338cd81",
references={
"Paper": "https://mipro-proceedings.com/sites/mipro-proceedings.com/files/upload/sp/sp_008.pdf",
"Homepage": "https://opencv.org/",
},
license="Apache 2.0",
strip_prefix="opencv-v0",
description="Compile-only object files from C++ OpenCV library",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
class TensorFlowDataset(TarDatasetWithManifest):
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://tensorflow-v0",
tar_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-tensorflow-v0.tar.bz2"
],
tar_sha256="f77dd1988c772e8359e1303cc9aba0d73d5eb27e0c98415ac3348076ab94efd1",
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-tensorflow-v0-manifest.bz2"
],
manifest_sha256="cffc45cd10250d483cb093dec913c8a7da64026686284cccf404623bd1da6da8",
references={
"Paper": "https://www.usenix.org/system/files/conference/osdi16/osdi16-abadi.pdf",
"Homepage": "https://www.tensorflow.org/",
},
license="Apache 2.0",
strip_prefix="tensorflow-v0",
description="Compile-only object files from C++ TensorFlow library",
benchmark_file_suffix=".bc",
site_data_base=site_data_base,
sort_order=sort_order,
)
def get_llvm_datasets(site_data_base: Optional[Path] = None) -> Iterable[Dataset]:
"""Instantiate the builtin LLVM datasets.
:param site_data_base: The root of the site data path.
:return: An iterable sequence of :class:`Dataset
<compiler_gym.datasets.Dataset>` instances.
"""
site_data_base = site_data_base or site_data_path("llvm-v0")
yield AnghaBenchDataset(site_data_base=site_data_base, sort_order=0)
# Add legacy version of Anghabench using an old manifest.
anghabench_v0_manifest_url, anghabench_v0_manifest_sha256 = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-anghabench-v0-macos-manifest.bz2",
"39464256405aacefdb7550a7f990c9c578264c132804eec3daac091fa3c21bd1",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-anghabench-v0-linux-manifest.bz2",
"a038d25d39ee9472662a9704dfff19c9e3512ff6a70f1067af85c5cb3784b477",
),
}[sys.platform]
yield AnghaBenchDataset(
name="benchmark://anghabench-v0",
site_data_base=site_data_base,
sort_order=0,
manifest_url=anghabench_v0_manifest_url,
manifest_sha256=anghabench_v0_manifest_sha256,
deprecated="Please use anghabench-v1",
)
yield JotaiBenchDataset(site_data_base=site_data_base)
yield BlasDataset(site_data_base=site_data_base, sort_order=0)
yield CLgenDataset(site_data_base=site_data_base, sort_order=0)
yield CBenchDataset(site_data_base=site_data_base)
# Add legacy version of cbench-v1 in which the 'b' was capitalized. This
# is deprecated and will be removed no earlier than v0.1.10.
yield CBenchLegacyDataset2(
site_data_base=site_data_base,
name="benchmark://cBench-v1",
deprecated=(
"Please use 'benchmark://cbench-v1' (note the lowercase name). "
"The dataset is the same, only the name has changed"
),
manifest_url="https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-cBench-v1-manifest.bz2",
manifest_sha256="635b94eeb2784dfedb3b53fd8f84517c3b4b95d851ddb662d4c1058c72dc81e0",
sort_order=100,
)
yield CBenchLegacyDataset(site_data_base=site_data_base)
yield CHStoneDataset(site_data_base=site_data_base)
yield CsmithDataset(site_data_base=site_data_base, sort_order=0)
yield GitHubDataset(site_data_base=site_data_base, sort_order=0)
yield LinuxDataset(site_data_base=site_data_base, sort_order=0)
yield LlvmStressDataset(site_data_base=site_data_base, sort_order=0)
yield MibenchDataset(site_data_base=site_data_base, sort_order=0)
yield MibenchV0Dataset(site_data_base=site_data_base, sort_order=100)
yield NPBDataset(site_data_base=site_data_base, sort_order=0)
yield OpenCVDataset(site_data_base=site_data_base, sort_order=0)
yield POJ104Dataset(site_data_base=site_data_base, sort_order=0)
yield POJ104LegacyDataset(site_data_base=site_data_base, sort_order=100)
yield TensorFlowDataset(site_data_base=site_data_base, sort_order=0)
__all__ = [
"AnghaBenchDataset",
"BlasDataset",
"CBenchDataset",
"CBenchLegacyDataset",
"CLgenDataset",
"CsmithBenchmark",
"CsmithDataset",
"get_llvm_datasets",
"GitHubDataset",
"JotaiBenchDataset",
"LinuxDataset",
"LlvmStressDataset",
"MibenchDataset",
"NPBDataset",
"OpenCVDataset",
"POJ104Dataset",
"POJ104LegacyDataset",
"TensorFlowDataset",
]
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import subprocess
from pathlib import Path
from typing import Iterable
import numpy as np
from compiler_gym.datasets import Benchmark, Dataset
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.errors import BenchmarkInitError
from compiler_gym.third_party import llvm
from compiler_gym.util.commands import Popen
# The maximum value for the --seed argument to llvm-stress.
UINT_MAX = (2**32) - 1
class LlvmStressDataset(Dataset):
"""A dataset which uses llvm-stress to generate programs.
`llvm-stress <https://llvm.org/docs/CommandGuide/llvm-stress.html>`_ is a
tool for generating random LLVM-IR files.
This dataset forces reproducible results by setting the input seed to the
generator. The benchmark's URI is the seed, e.g.
"generator://llvm-stress-v0/10" is the benchmark generated by llvm-stress
using seed 10. The total number of unique seeds is 2^32 - 1.
Note that llvm-stress is a tool that is used to find errors in LLVM. As
such, there is a higher likelihood that the benchmark cannot be used for an
environment and that :meth:`env.reset()
<compiler_gym.envs.CompilerEnv.reset>` will raise
:class:`BenchmarkInitError <compiler_gym.datasets.BenchmarkInitError>`.
"""
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="generator://llvm-stress-v0",
description="Randomly generated LLVM-IR",
references={
"Documentation": "https://llvm.org/docs/CommandGuide/llvm-stress.html"
},
license="Apache License v2.0 with LLVM Exceptions",
site_data_base=site_data_base,
sort_order=sort_order,
)
@property
def size(self) -> int:
# Actually 2^32 - 1, but practically infinite for all intents and
# purposes.
return 0
def benchmark_uris(self) -> Iterable[str]:
return (f"{self.name}/{i}" for i in range(UINT_MAX))
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
seed = int(uri.path[1:])
return self.benchmark_from_seed(seed)
def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark:
seed = random_state.integers(UINT_MAX)
return self.benchmark_from_seed(seed)
def benchmark_from_seed(self, seed: int) -> Benchmark:
"""Get a benchmark from a uint32 seed.
:param seed: A number in the range 0 <= n < 2^32.
:return: A benchmark instance.
"""
self.install()
# Run llvm-stress with the given seed and pipe the output to llvm-as to
# assemble a bitcode.
try:
with Popen(
[str(llvm.llvm_stress_path()), f"--seed={seed}"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as llvm_stress:
with Popen(
[str(llvm.llvm_as_path()), "-"],
stdin=llvm_stress.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as llvm_as:
stdout, _ = llvm_as.communicate(timeout=60)
llvm_stress.communicate(timeout=60)
if llvm_stress.returncode or llvm_as.returncode:
raise BenchmarkInitError("Failed to generate benchmark")
except subprocess.TimeoutExpired:
raise BenchmarkInitError("Benchmark generation timed out")
return Benchmark.from_file_contents(f"{self.name}/{seed}", stdout)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/llvm_stress.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import io
import logging
import os
import shutil
import subprocess
import tarfile
from pathlib import Path
from threading import Lock
from typing import List
from fasteners import InterProcessLock
from compiler_gym.datasets import Benchmark, TarDatasetWithManifest
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm.llvm_benchmark import ClangInvocation
from compiler_gym.errors import BenchmarkInitError
from compiler_gym.util.commands import Popen, communicate
from compiler_gym.util.download import download
from compiler_gym.util.filesystem import atomic_file_write
from compiler_gym.util.truncate import truncate
logger = logging.getLogger(__name__)
_CLGEN_INSTALL_LOCK = Lock()
class CLgenDataset(TarDatasetWithManifest):
"""The CLgen dataset contains 1000 synthetically generated OpenCL kernels.
The dataset is from:
Cummins, Chris, Pavlos Petoumenos, Zheng Wang, and Hugh Leather.
"Synthesizing benchmarks for predictive modeling." In 2017 IEEE/ACM
International Symposium on Code Generation and Optimization (CGO),
pp. 86-99. IEEE, 2017.
And is available at:
https://github.com/ChrisCummins/paper-synthesizing-benchmarks
Installation
------------
The CLgen dataset consists of OpenCL kernels that are compiled to LLVM-IR
on-demand and cached. The first time each benchmark is used there is an
overhead of compiling it from OpenCL to bitcode. This is a one-off cost.
Compiling OpenCL to bitcode requires third party headers that are downloaded
on the first call to :code:`install()`.
"""
def __init__(self, site_data_base: Path, sort_order: int = 0):
super().__init__(
name="benchmark://clgen-v0",
description="Synthetically generated OpenCL kernels",
references={
"Paper": "https://chriscummins.cc/pub/2017-cgo.pdf",
"Homepage": "https://github.com/ChrisCummins/clgen",
},
license="GNU General Public License v3.0",
site_data_base=site_data_base,
manifest_urls=[
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-clgen-v0-manifest.bz2"
],
manifest_sha256="d2bbc1da5a24a8cb03b604d1d8e59227b33bdfcd964ebe741ca8339f1c8d65cc",
tar_urls=[
"https://github.com/ChrisCummins/paper-synthesizing-benchmarks/raw/e45b6dffe9998f612624f05a6c4878ab4bcc84ec/data/clgen-1000.tar.bz2"
],
tar_sha256="0bbd1b737f2537305e4db09b2971a5fa848b7c3a978bff6b570f45d1a488a72c",
strip_prefix="clgen-1000/kernels",
tar_compression="bz2",
benchmark_file_suffix=".bc",
sort_order=sort_order,
)
self._opencl_installed = False
self._opencl_headers_installed_marker = (
self._site_data_path / ".opencl-installed"
)
self.libclc_dir = self.site_data_path / "libclc"
self.opencl_h_path = self.site_data_path / "opencl.h"
def install(self):
super().install()
if not self._opencl_installed:
self._opencl_installed = self._opencl_headers_installed_marker.is_file()
if self._opencl_installed:
return
with _CLGEN_INSTALL_LOCK, InterProcessLock(self._tar_lockfile):
# Repeat install check now that we are in the locked region.
if self._opencl_headers_installed_marker.is_file():
return
# Download the libclc headers.
shutil.rmtree(self.libclc_dir, ignore_errors=True)
logger.info("Downloading OpenCL headers ...")
tar_data = io.BytesIO(
download(
"https://dl.fbaipublicfiles.com/compiler_gym/libclc-v0.tar.bz2",
sha256="f1c511f2ac12adf98dcc0fbfc4e09d0f755fa403c18f1fb1ffa5547e1fa1a499",
)
)
with tarfile.open(fileobj=tar_data, mode="r:bz2") as arc:
arc.extractall(str(self.site_data_path / "libclc"))
# Download the OpenCL header.
with open(self.opencl_h_path, "wb") as f:
f.write(
download(
"https://github.com/ChrisCummins/clgen/raw/463c0adcd8abcf2432b24df0aca594b77a69e9d3/deeplearning/clgen/data/include/opencl.h",
sha256="f95b9f4c8b1d09114e491846d0d41425d24930ac167e024f45dab8071d19f3f7",
)
)
self._opencl_headers_installed_marker.touch()
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
benchmark_name = uri.path[1:]
if not benchmark_name:
raise LookupError(f"No benchmark specified: {uri}")
# The absolute path of the file, without an extension.
path_stem = os.path.normpath(f"{self.dataset_root}/{uri.path}")
bc_path, cl_path = Path(f"{path_stem}.bc"), Path(f"{path_stem}.cl")
# If the file does not exist, compile it on-demand.
if not bc_path.is_file():
if not cl_path.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {cl_path}, path_stem {path_stem})"
)
# Compile the OpenCL kernel into a bitcode file.
with atomic_file_write(bc_path) as tmp_bc_path:
compile_command: List[str] = ClangInvocation.from_c_file(
cl_path,
copt=[
"-isystem",
str(self.libclc_dir),
"-include",
str(self.opencl_h_path),
"-target",
"nvptx64-nvidia-nvcl",
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
],
).command(outpath=tmp_bc_path)
logger.debug("Exec %s", compile_command)
try:
with Popen(
compile_command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as clang:
_, stderr = communicate(clang, timeout=300)
except subprocess.TimeoutExpired:
raise BenchmarkInitError(f"Benchmark compilation timed out: {uri}")
if clang.returncode:
compile_command = " ".join(compile_command)
error = truncate(
stderr.decode("utf-8"), max_lines=20, max_line_len=20000
)
raise BenchmarkInitError(
f"Compilation job failed!\n"
f"Command: {compile_command}\n"
f"Error: {error}"
)
return BenchmarkWithSource.create(uri, bc_path, "kernel.cl", cl_path)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/clgen.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import subprocess
import sys
from concurrent.futures import as_completed
from pathlib import Path
from typing import Optional
from compiler_gym.datasets import Benchmark, TarDatasetWithManifest
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.llvm.llvm_benchmark import ClangInvocation
from compiler_gym.util import thread_pool
from compiler_gym.util.filesystem import atomic_file_write
class AnghaBenchDataset(TarDatasetWithManifest):
"""A dataset of C programs curated from GitHub source code.
The dataset is from:
da Silva, Anderson Faustino, Bruno Conde Kind, José Wesley de Souza
Magalhaes, Jerônimo Nunes Rocha, Breno Campos Ferreira Guimaraes, and
Fernando Magno Quinão Pereira. "ANGHABENCH: A Suite with One Million
Compilable C Benchmarks for Code-Size Reduction." In 2021 IEEE/ACM
International Symposium on Code Generation and Optimization (CGO),
pp. 378-390. IEEE, 2021.
And is available at:
http://cuda.dcc.ufmg.br/angha/home
Installation
------------
The AnghaBench dataset consists of C functions that are compiled to LLVM-IR
on-demand and cached. The first time each benchmark is used there is an
overhead of compiling it from C to bitcode. This is a one-off cost.
"""
def __init__(
self,
site_data_base: Path,
sort_order: int = 0,
manifest_url: Optional[str] = None,
manifest_sha256: Optional[str] = None,
deprecated: Optional[str] = None,
name: Optional[str] = None,
):
manifest_url_, manifest_sha256_ = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-anghabench-v1-macos-manifest.bz2",
"96ead63da5f8efa07fd0370f0c6e452b59bed840828b8b19402102b1ce3ee109",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-anghabench-v1-linux-manifest.bz2",
"14df85f650199498cf769715e9f0d7841d09f9fa62a95b8ecc242bdaf227f33a",
),
}[sys.platform]
super().__init__(
name=name or "benchmark://anghabench-v1",
description="Compile-only C/C++ functions extracted from GitHub",
references={
"Paper": "https://homepages.dcc.ufmg.br/~fernando/publications/papers/FaustinoCGO21.pdf",
"Homepage": "http://cuda.dcc.ufmg.br/angha/",
},
license="Unknown. See: https://github.com/brenocfg/AnghaBench/issues/1",
site_data_base=site_data_base,
manifest_urls=[manifest_url or manifest_url_],
manifest_sha256=manifest_sha256 or manifest_sha256_,
tar_urls=[
"https://github.com/brenocfg/AnghaBench/archive/d8034ac8562b8c978376008f4b33df01b8887b19.tar.gz"
],
tar_sha256="85d068e4ce44f2581e3355ee7a8f3ccb92568e9f5bd338bc3a918566f3aff42f",
strip_prefix="AnghaBench-d8034ac8562b8c978376008f4b33df01b8887b19",
tar_compression="gz",
benchmark_file_suffix=".bc",
sort_order=sort_order,
deprecated=deprecated,
)
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
benchmark_name = uri.path[1:]
if not benchmark_name:
raise LookupError(f"No benchmark specified: {uri}")
# The absolute path of the file, without an extension.
path_stem = self.dataset_root / benchmark_name
bitcode_abspath = Path(f"{path_stem}.bc")
c_file_abspath = Path(f"{path_stem}.c")
# If the file does not exist, compile it on-demand.
if not bitcode_abspath.is_file():
if not c_file_abspath.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {c_file_abspath})"
)
with atomic_file_write(bitcode_abspath) as tmp_path:
compile_cmd = ClangInvocation.from_c_file(
c_file_abspath,
copt=[
"-ferror-limit=1", # Stop on first error.
"-w", # No warnings.
],
).command(outpath=tmp_path)
subprocess.check_call(compile_cmd, timeout=300)
return BenchmarkWithSource.create(
uri, bitcode_abspath, "function.c", c_file_abspath
)
def compile_all(self):
n = self.size
executor = thread_pool.get_thread_pool_executor()
# Since the dataset is lazily compiled, simply iterating over the full
# set of URIs will compile everything. Do this in parallel.
futures = (
executor.submit(self.benchmark, uri) for uri in self.benchmark_uris()
)
for i, future in enumerate(as_completed(futures), start=1):
future.result()
print(
f"\r\033[KCompiled {i} of {n} programs ({i/n:.1%} complete)",
flush=True,
end="",
)
|
CompilerGym-development
|
compiler_gym/envs/llvm/datasets/anghabench.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module demonstrates how to """
from pathlib import Path
from compiler_gym.envs.gcc.gcc import Gcc, GccSpec, Option
from compiler_gym.envs.gcc.gcc_env import DEFAULT_GCC, GccEnv
from compiler_gym.util.registration import register
from compiler_gym.util.runfiles_path import runfiles_path
GCC_SERVICE_BINARY: Path = runfiles_path(
"compiler_gym/envs/gcc/service/compiler_gym-gcc-service"
)
register(
id="gcc-v0",
entry_point="compiler_gym.envs.gcc:GccEnv",
kwargs={"service": GCC_SERVICE_BINARY},
)
__all__ = ["GccEnv", "GccSpec", "Gcc", "Option", "DEFAULT_GCC"]
|
CompilerGym-development
|
compiler_gym/envs/gcc/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""A CompilerGym environment for GCC."""
import codecs
import json
import pickle
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from deprecated.sphinx import deprecated
from compiler_gym.datasets import Benchmark
from compiler_gym.envs.gcc.datasets import get_gcc_datasets
from compiler_gym.envs.gcc.gcc import Gcc, GccSpec
from compiler_gym.envs.gcc.gcc_rewards import AsmSizeReward, ObjSizeReward
from compiler_gym.service import ConnectionOpts
from compiler_gym.service.client_service_compiler_env import ClientServiceCompilerEnv
from compiler_gym.spaces import Reward
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.gym_type_hints import ObservationType, OptionalArgumentValue
from compiler_gym.views import ObservationSpaceSpec
# The default gcc_bin argument.
DEFAULT_GCC: str = "docker:gcc:11.2.0"
class GccEnv(ClientServiceCompilerEnv):
"""A specialized ClientServiceCompilerEnv for GCC.
This class exposes the optimization space of GCC's command line flags
as an environment for reinforcement learning. For further details, see the
:ref:`GCC Environment Reference <envs/gcc:Installation>`.
"""
def __init__(
self,
*args,
gcc_bin: Union[str, Path] = DEFAULT_GCC,
benchmark: Union[str, Benchmark] = "benchmark://chstone-v0/adpcm",
datasets_site_path: Optional[Path] = None,
connection_settings: Optional[ConnectionOpts] = None,
**kwargs,
):
"""Create an environment.
:param gcc_bin: The path to the GCC executable, or the name of a docker
image to use if prefixed with :code:`docker:`. Only used if the
environment is attached to a local service. If attached remotely,
the service will have already been created.
:param benchmark: The benchmark to use for this environment. Either a
URI string, or a :class:`Benchmark
<compiler_gym.datasets.Benchmark>` instance. If not provided, a
default benchmark is used.
:param connection_settings: The connection settings to use.
:raises EnvironmentNotSupported: If the runtime requirements for the GCC
environment have not been met.
:raises ServiceInitError: If the requested GCC version cannot be used.
"""
connection_settings = connection_settings or ConnectionOpts()
# Pass the executable path via an environment variable
connection_settings.script_env = {"CC": gcc_bin}
# Eagerly create a GCC compiler instance now because:
#
# 1. We want to catch an invalid gcc_bin argument early.
#
# 2. We want to perform the expensive one-off `docker pull` before we
# start the backend service, as otherwise the backend service
# initialization may time out.
Gcc(bin=gcc_bin)
super().__init__(
*args,
**kwargs,
benchmark=benchmark,
datasets=get_gcc_datasets(
gcc_bin=gcc_bin, site_data_base=datasets_site_path
),
rewards=[AsmSizeReward(), ObjSizeReward()],
connection_settings=connection_settings,
)
def reset(
self,
benchmark: Optional[Union[str, Benchmark]] = None,
action_space: Optional[str] = None,
observation_space: Union[
OptionalArgumentValue, str, ObservationSpaceSpec
] = OptionalArgumentValue.UNCHANGED,
reward_space: Union[
OptionalArgumentValue, str, Reward
] = OptionalArgumentValue.UNCHANGED,
) -> Optional[ObservationType]:
observation = super().reset(
benchmark=benchmark,
action_space=action_space,
observation_space=observation_space,
reward_space=reward_space,
)
return observation
@deprecated(
version="0.2.1",
reason="Use `env.observation.command_line()` instead",
)
def commandline(self) -> str:
"""Return a string representing the command line options.
:return: A string.
"""
return self.observation["command_line"]
@memoized_property
def gcc_spec(self) -> GccSpec:
"""A :class:`GccSpec <compiler_gym.envs.gcc.gcc.GccSpec>` description of
the compiler specification.
"""
pickled = self.send_param("gcc_spec", "")
return pickle.loads(codecs.decode(pickled.encode(), "base64"))
@property
def source(self) -> str:
"""Get the source code."""
return self.observation["source"]
@property
def rtl(self) -> str:
"""Get the final rtl of the program."""
return self.observation["rtl"]
@property
def asm(self) -> str:
"""Get the assembly code."""
return self.observation["asm"]
@property
def asm_size(self) -> int:
"""Get the assembly code size in bytes."""
return self.observation["asm_size"]
@property
def asm_hash(self) -> str:
"""Get a hash of the assembly code."""
return self.observation["asm_hash"]
@property
def instruction_counts(self) -> Dict[str, int]:
"""Get a count of the instruction types in the assembly code.
Note, that it will also count fields beginning with a :code:`.`, like
:code:`.bss` and :code:`.align`. Make sure to remove those if not
needed.
"""
return json.loads(self.observation["instruction_counts"])
@property
def obj(self) -> bytes:
"""Get the object code."""
return self.observation["obj"]
@property
def obj_size(self) -> int:
"""Get the object code size in bytes."""
return self.observation["obj_size"]
@property
def obj_hash(self) -> str:
"""Get a hash of the object code."""
return self.observation["obj_hash"]
@property
def choices(self) -> List[int]:
"""Get the current choices"""
return self.observation["choices"]
@choices.setter
def choices(self, choices: List[int]):
"""Set the current choices.
This must be a list of ints with one element for each option the
gcc_spec. Each element must be in range for the corresponding option.
I.e. it must be between -1 and len(option) inclusive.
"""
# TODO(github.com/facebookresearch/CompilerGym/issues/52): This can be
# exposed directly through the action space once #369 is merged.
assert len(self.gcc_spec.options) == len(choices)
assert all(
-1 <= c < len(self.gcc_spec.options[i]) for i, c in enumerate(choices)
)
self.send_param("choices", ",".join(map(str, choices)))
def _init_kwargs(self) -> Dict[str, Any]:
"""Return the arguments required to initialize a GccEnv."""
return {
# GCC has an additional gcc_bin argument.
"gcc_bin": self.gcc_spec.gcc.bin,
**super()._init_kwargs(),
}
|
CompilerGym-development
|
compiler_gym/envs/gcc/gcc_env.py
|
#! /usr/bin/env python3
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Query a GCC binary for version, optimization and param spaces.
The goal of this file is to query the available settings in a GCC compiler so
that they don't have to be hard coded.
The main entry point to this file is the 'get_spec' function which returns a
GccSpec object. That object describes the version, options and parameters.
Querying these settings is time consuming, so this file tries to cache the
values in a cache directory.
Running this file will print the gcc spec to stdout.
"""
import logging
import math
import os
import pickle
import re
import subprocess
import warnings
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional, Union
import docker
from compiler_gym.errors import EnvironmentNotSupported, ServiceError, ServiceInitError
from compiler_gym.util.filesystem import atomic_file_write
from compiler_gym.util.runfiles_path import site_data_path
logger = logging.getLogger(__name__)
class Option:
"""An Option is either a command line optimization setting or a parameter.
It is essentially a list of the possible values that can be taken. Each item
is command line parameter. In GCC, all of these are single settings, so only
need one string to describe them, rather than a list.
"""
def __len__(self):
"""Number of available settings. Note that the absence of a value is not
included in this, it is implicit.
"""
raise NotImplementedError()
def __getitem__(self, key: int) -> str:
"""Get the command line argument associated with an index (key)."""
raise NotImplementedError()
def __str__(self) -> str:
"""Get the name of this option."""
raise NotImplementedError()
class GccOOption(Option):
"""This class represents the :code:`-O0`, :code:`-O1`, :code:`-O2`,
:code:`-O3`, :code:`-Os`, and :code:`-Ofast` options.
This class starts with no values, we fill them in with
:code:`_gcc_parse_optimize()`. The suffixes to append to :code:`-O` are
stored in self.values.
"""
def __init__(self):
self.values = []
def __len__(self):
return len(self.values)
def __getitem__(self, key: int) -> str:
return "-O" + self.values[key]
def __str__(self) -> str:
return "-O"
def __repr__(self) -> str:
return f"<GccOOption values=[{','.join(self.values)}]>"
class GccFlagOption(Option):
"""An ordinary :code:`-f` flag.
These have two possible settings. For a given flag name there are
:code:`'-f<name>' and :code:`'-fno-<name>. If :code:`no_fno` is true, then
there is only the :code:`-f<name>` form.
"""
def __init__(self, name: str, no_fno: bool = False):
self.name = name
self.no_fno = no_fno
def __len__(self):
return 1 if self.no_fno else 2
def __getitem__(self, key: int) -> str:
return f"-f{'' if key == 0 else 'no-'}{self.name}"
def __str__(self) -> str:
return f"-f{self.name}"
def __repr__(self) -> str:
return f"<GccFlagOption name={self.name}>"
class GccFlagEnumOption(Option):
"""A flag of style :code:`-f<name>=[val1, val2, ...]`.
:code:`self.name` holds the name. :code:`self.values` holds the values.
"""
def __init__(self, name: str, values: List[str]):
self.name = name
self.values = values
def __len__(self):
return len(self.values)
def __getitem__(self, key: int) -> str:
return f"-f{self.name}={self.values[key]}"
def __str__(self) -> str:
return f"-f{self.name}"
def __repr__(self) -> str:
return f"<GccFlagEnumOption name={self.name}, values=[{','.join(self.values)}]>"
class GccFlagIntOption(Option):
"""A flag of style :code:`-f<name>=<integer>` where the integer is between
min and max.
"""
def __init__(self, name: str, min: int, max: int):
self.name = name
self.min = min
self.max = max
def __len__(self):
return self.max - self.min + 1
def __getitem__(self, key: int) -> str:
return f"-f{self.name}={self.min + key}"
def __str__(self) -> str:
return f"-f{self.name}"
def __repr__(self) -> str:
return f"<GccFlagIntOption name={self.name}, min={self.min}, max={self.max}>"
class GccFlagAlignOption(Option):
"""Alignment flags. These take several forms. See the GCC documentation."""
def __init__(self, name: str):
logger.warning("Alignment options not properly handled %s", name)
self.name = name
def __len__(self):
return 1
def __getitem__(self, key: int) -> str:
return f"-f{self.name}"
def __str__(self) -> str:
return f"-f{self.name}"
def __repr__(self) -> str:
return f"<GccFlagAlignOption name={self.name}>"
class GccParamEnumOption(Option):
"""A parameter :code:`--param=<name>=[val1, val2, val3]`."""
def __init__(self, name: str, values: List[str]):
self.name = name
self.values = values
def __len__(self):
return len(self.values)
def __getitem__(self, key: int) -> str:
return f"--param={self.name}={self.values[key]}"
def __str__(self) -> str:
return f"--param={self.name}"
def __repr__(self) -> str:
return (
f"<GccParamEnumOption name={self.name}, values=[{','.join(self.values)}]>"
)
class GccParamIntOption(Option):
"""A parameter :code:`--param=<name>=<integer>`, where the integer is
between min and max.
"""
def __init__(self, name: str, min: int, max: int):
self.name = name
self.min = min
self.max = max
def __len__(self):
return self.max - self.min + 1
def __getitem__(self, key: int) -> str:
return f"--param={self.name}={self.min + key}"
def __str__(self) -> str:
return f"--param={self.name}"
def __repr__(self) -> str:
return f"<GccParamIntOption name={self.name}, min={self.min}, max={self.max}>"
@lru_cache(maxsize=2)
def get_docker_client():
"""Fetch the docker client singleton."""
# Ignore deprecation warnings from docker.from_env().
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
try:
return docker.from_env()
except docker.errors.DockerException as e:
raise EnvironmentNotSupported(
f"Failed to initialize docker client needed by GCC environment: {e}.\n"
"Have you installed the runtime dependencies?\n See "
"<https://facebookresearch.github.io/CompilerGym/envs/gcc.html#installation> "
"for details."
) from e
# We only need to run this function once per image.
@lru_cache(maxsize=64)
def pull_docker_image(image: str) -> str:
"""Pull the requested docker image.
:param image: The name of the docker image to pull.
:raises ServiceInitError: If pulling the docker image fails.
"""
try:
client = get_docker_client()
client.images.pull(image)
return image
except docker.errors.DockerException as e:
raise ServiceInitError(f"Failed to fetch docker image '{image}': {e}")
def join_docker_container(container, timeout_seconds: int) -> str:
"""Block until the container terminates, returning its output."""
try:
status = container.wait(timeout=timeout_seconds)
except docker.exceptions.ReadTimeout as e:
# Catch and re-raise the timeout.
raise TimeoutError(f"GCC timed out after {timeout_seconds:,d} seconds") from e
if status["StatusCode"]:
logs = ""
try:
logs = container.logs(stdout=True, stderr=False).decode()
except (UnicodeDecodeError, docker.errors.NotFound):
pass
raise ServiceError(f"GCC failed with returncode {status['StatusCode']}: {logs}")
return container.logs(stdout=True, stderr=False).decode()
class Gcc:
"""This class represents an instance of the GCC compiler, either as a binary
or a docker image.
:ivar bin: A string version of the constructor argument.
:vartype bin: str
:ivar spec: A :class:`GccSpec <compiler_gym.envs.gcc.gcc.GccSpec>` instance.
:vartype spec: GccSpec
"""
def __init__(self, bin: Union[str, Path]):
self.bin = str(bin)
self.image = self.bin[len("docker:") :]
if self.bin.startswith("docker:"):
pull_docker_image(self.image)
self.call = self._docker_run
else:
self.call = self._subprocess_run
self.spec = _get_spec(self, cache_dir=site_data_path("gcc-v0"))
def __call__(
self,
*args: str,
timeout: int,
cwd: Optional[Path] = None,
volumes: Optional[Dict[str, Dict[str, str]]] = None,
) -> str:
"""Run GCC with the given args.
:param args: The command line arguments to append.
:param timeout: A timeout in seconds.
:param cwd: The working directory.
:param volumes: A dictionary of volume bindings for docker.
:raises TimeoutError: If GCC fails to complete within timeout.
:raises ServiceError: In case GCC fails.
"""
return self.call(args, timeout, cwd=Path(cwd or "."), volumes=volumes)
def _docker_run(
self,
args: List[str],
timeout: int,
cwd: Path,
volumes: Optional[Dict[str, Dict[str, str]]] = None,
):
cwd = cwd.absolute().as_posix()
cmd_line = ["gcc"] + list(map(str, args))
if timeout:
cmd_line = ["timeout", str(timeout)] + cmd_line
volumes_ = {cwd: {"bind": cwd, "mode": "rw"}}
volumes_.update(volumes or {})
client = get_docker_client()
container = client.containers.create(
self.image,
cmd_line,
working_dir=cwd,
volumes=volumes_,
)
container.start()
try:
return join_docker_container(container, timeout_seconds=timeout)
finally:
container.remove()
def _subprocess_run(self, args, timeout, cwd, volumes):
del volumes # Unused
cmd_line = [self.bin] + list(map(str, args))
try:
result = subprocess.check_output(
cmd_line, cwd=cwd, universal_newlines=True, timeout=timeout
)
except subprocess.CalledProcessError as e:
raise ServiceError(f"Failed to run {self.bin}: {e}") from e
except FileNotFoundError:
raise ServiceInitError(f"GCC binary not found: {self.bin}")
return result
class GccSpec(NamedTuple):
"""This class combines all of the information about the version and options
for a GCC instance.
"""
gcc: Gcc
"""A compiler instance."""
version: str
"""The GCC version string."""
options: List[Option]
"""A list of options exposed by the compiler."""
@property
def size(self) -> int:
"""Calculate the size of the option space. This is the product of the
cardinalities of all the options.
"""
sz = 1
for option in self.options:
# Each option can be applied or not.
sz *= len(option) + 1
return sz
def _gcc_parse_optimize(gcc: Gcc) -> List[Option]:
"""Parse the optimization help string from the GCC binary to find options."""
logger.debug("Parsing GCC optimization space")
# Call 'gcc --help=optimize -Q'
result = gcc("--help=optimize", "-Q", timeout=60)
# Split into lines. Ignore the first line.
out = result.split("\n")[1:]
# Regex patterns to match the different options
O_num_pat = re.compile("-O<number>")
O_pat = re.compile("-O([a-z]+)")
flag_align_eq_pat = re.compile("-f(align-[-a-z]+)=")
flag_pat = re.compile("-f([-a-z0-9]+)")
flag_enum_pat = re.compile("-f([-a-z0-9]+)=\\[([-A-Za-z_\\|]+)\\]")
flag_interval_pat = re.compile("-f([-a-z0-9]+)=<([0-9]+),([0-9]+)>")
flag_number_pat = re.compile("-f([-a-z0-9]+)=<number>")
# The list of options as it gets built up.
options = {}
# Add a -O value
def add_gcc_o(value: str):
# -O flag
name = "O"
# There are multiple -O flags. We add one value at a time.
opt = options[name] = options.get(name, GccOOption())
# There shouldn't be any way to overwrite this with the wrong type.
assert type(opt) == GccOOption
opt.values.append(value)
# Add a flag
def add_gcc_flag(name: str):
# Straight flag.
# If there is something else in its place already (like a flag enum),
# then we don't overwrite it. Straight flags always have the lowest
# priority
options[name] = options.get(name, GccFlagOption(name))
# Add an enum flag
def add_gcc_flag_enum(name: str, values: List[str]):
# Enum flag.
opt = options.get(name)
if opt:
# We should only ever be overwriting a straight flag
assert type(opt) == GccFlagOption
# Always overwrite
options[name] = GccFlagEnumOption(name, values)
# Add an integer flag
def add_gcc_flag_int(name: str, min: int, max: int):
# Int flag.
opt = options.get(name)
if opt:
# We should only ever be overwriting a straight flag
assert type(opt) == GccFlagOption
# Always overwrite
options[name] = GccFlagIntOption(name, min, max)
# Add an align flag
def add_gcc_flag_align(name: str):
# Align flag.
opt = options.get(name)
if opt:
# We should only ever be overwriting a straight flag
assert type(opt) == GccFlagOption
# Always overwrite
options[name] = GccFlagAlignOption(name)
# Parse a line from the help output
def parse_line(line: str):
# The first bit of the line is the specification
bits = line.split()
if not bits:
return
spec = bits[0]
# -O<number>
m = O_num_pat.fullmatch(spec)
if m:
for i in range(4):
add_gcc_o(str(i))
return
# -Ostr
m = O_pat.fullmatch(spec)
if m:
add_gcc_o(m.group(1))
return
# -falign-str=
# These have quite complicated semantics
m = flag_align_eq_pat.fullmatch(spec)
if m:
name = m.group(1)
add_gcc_flag_align(name)
return
# -fflag
m = flag_pat.fullmatch(spec)
if m:
name = m.group(1)
add_gcc_flag(name)
return
# -fflag=[a|b]
m = flag_enum_pat.fullmatch(spec)
if m:
name = m.group(1)
values = m.group(2).split("|")
add_gcc_flag_enum(name, values)
return
# -fflag=<min,max>
m = flag_interval_pat.fullmatch(spec)
if m:
name = m.group(1)
min = int(m.group(2))
max = int(m.group(3))
add_gcc_flag_int(name, min, max)
return
# -fflag=<number>
m = flag_number_pat.fullmatch(spec)
if m:
name = m.group(1)
min = 0
max = 2 << 31 - 1
add_gcc_flag_int(name, min, max)
return
logger.warning("Unknown GCC optimization flag spec, '%s'", line)
# Parse all the lines
for line in out:
parse_line(line.strip())
# Sort and return
return list(map(lambda x: x[1], sorted(list(options.items()))))
def _gcc_parse_params(gcc: Gcc) -> List[Option]:
"""Parse the param help string from the GCC binary to find options."""
# Pretty much identical to _gcc_parse_optimize
logger.debug("Parsing GCC param space")
result = gcc("--help=param", "-Q", timeout=60)
out = result.split("\n")[1:]
param_enum_pat = re.compile("--param=([-a-zA-Z0-9]+)=\\[([-A-Za-z_\\|]+)\\]")
param_interval_pat = re.compile("--param=([-a-zA-Z0-9]+)=<(-?[0-9]+),([0-9]+)>")
param_number_pat = re.compile("--param=([-a-zA-Z0-9]+)=")
param_old_interval_pat = re.compile(
"([-a-zA-Z0-9]+)\\s+default\\s+(-?\\d+)\\s+minimum\\s+(-?\\d+)\\s+maximum\\s+(-?\\d+)"
)
params = {}
def add_gcc_param_enum(name: str, values: List[str]):
# Enum param.
opt = params.get(name)
assert not opt
params[name] = GccParamEnumOption(name, values)
def add_gcc_param_int(name: str, min: int, max: int):
# Int flag.
opt = params.get(name)
assert not opt
params[name] = GccParamIntOption(name, min, max)
def is_int(s: str) -> bool:
try:
int(s)
return True
except ValueError:
return False
def parse_line(line: str):
bits = line.split()
if not bits:
return
# TODO(hugh): Not sure what the correct behavior is there.
if len(bits) <= 1:
return
spec = bits[0]
default = bits[1]
# --param=name=[a|b]
m = param_enum_pat.fullmatch(spec)
if m:
name = m.group(1)
values = m.group(2).split("|")
assert not default or default in values
add_gcc_param_enum(name, values)
return
# --param=name=<min,max>
m = param_interval_pat.fullmatch(spec)
if m:
name = m.group(1)
min = int(m.group(2))
max = int(m.group(3))
if is_int(default):
assert not default or min <= int(default) <= max
add_gcc_param_int(name, min, max)
return
# --param=name=
m = param_number_pat.fullmatch(spec)
if m:
name = m.group(1)
min = 0
max = 2 << 31 - 1
if is_int(default):
dflt = int(default)
min = min if dflt >= min else dflt
add_gcc_param_int(name, min, max)
return
# name default num minimum num maximum num
m = param_old_interval_pat.fullmatch(line)
if m:
name = m.group(1)
default = int(m.group(2))
min = int(m.group(3))
max = int(m.group(4))
if min <= default <= max:
# For now we will only consider fully described params
add_gcc_param_int(name, min, max)
return
logger.warning("Unknown GCC param flag spec, '%s'", line)
# breakpoint()
for line in out:
parse_line(line.strip())
return list(map(lambda x: x[1], sorted(list(params.items()))))
def _fix_options(options: List[Option]) -> List[Option]:
"""Fixes for things that seem not to be true in the help."""
def keep(option: Option) -> bool:
# Ignore -flive-patching
if isinstance(option, GccFlagEnumOption):
if option.name == "live-patching":
return False
return True
options = [opt for opt in options if keep(opt)]
for i, option in enumerate(options):
if isinstance(option, GccParamIntOption):
# Some things say they can have -1, but can't
if option.name in [
"logical-op-non-short-circuit",
"prefetch-minimum-stride",
"sched-autopref-queue-depth",
"vect-max-peeling-for-alignment",
]:
option.min = 0
elif isinstance(option, GccFlagOption):
# -fhandle-exceptions renamed to -fexceptions
if option.name == "handle-exceptions":
option.name = "exceptions"
# Some flags have no -fno- version
if option.name in [
"stack-protector-all",
"stack-protector-explicit",
"stack-protector-strong",
]:
option.no_fno = True
# -fno-threadsafe-statics should have the no- removed
if option.name == "no-threadsafe-statics":
option.name = "threadsafe-statics"
elif isinstance(option, GccFlagIntOption):
# -fpack-struct has to be a small positive power of two
if option.name == "pack-struct":
values = [str(1 << j) for j in range(5)]
options[i] = GccFlagEnumOption("pack-struct", values)
return options
def _gcc_get_version(gcc: Gcc) -> str:
"""Get the version string"""
logger.debug("Getting GCC version for %s", gcc.bin)
try:
result = gcc("--version", timeout=60)
except ServiceError as e:
raise EnvironmentNotSupported(f"Failed to run GCC binary: {gcc.bin}") from e
version = result.split("\n")[0]
logger.debug("GCC version is %s", version)
if "gcc" not in version:
raise ServiceInitError(f"Invalid GCC version string: {version}")
return version
def _version_hash(version: str) -> str:
"""Hash the version so we can cache the spec at that name."""
h = 0
for c in version:
h = ord(c) + 31 * h
return str(h % (2 << 64))
def _get_spec(gcc: Gcc, cache_dir: Path) -> Optional[GccSpec]:
"""Get the specification for a GCC executable.
:param gcc: The executable.
:param cache_dir: An optional directory to search for cached versions of the
spec.
"""
# Get the version
version = _gcc_get_version(gcc)
spec = None
# See if there is a pickled spec in the cache_dir. First we use a hash to
# name the file.
spec_path = cache_dir / _version_hash(version) / "spec.pkl"
# Try to get the pickled version
if os.path.isfile(spec_path):
try:
with open(spec_path, "rb") as f:
spec = pickle.load(f)
spec = GccSpec(gcc=gcc, version=spec.version, options=spec.options)
logger.debug("GccSpec for version '%s' read from %s", version, spec_path)
except (pickle.UnpicklingError, EOFError) as e:
logger.warning("Unable to read spec from '%s': %s", spec_path, e)
if spec is None:
# Pickle doesn't exist, parse
optim_opts = _gcc_parse_optimize(gcc)
param_opts = _gcc_parse_params(gcc)
options = _fix_options(optim_opts + param_opts)
spec = GccSpec(gcc, version, options)
if not spec.options:
return None
# Cache the spec file for future.
spec_path.parent.mkdir(exist_ok=True, parents=True)
with atomic_file_write(spec_path, fileobj=True) as f:
pickle.dump(spec, f)
logger.debug("GccSpec for %s written to %s", version, spec_path)
logger.debug("GccSpec size is approximately 10^%.0f", round(math.log(spec.size)))
return spec
|
CompilerGym-development
|
compiler_gym/envs/gcc/gcc.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Reward spaces for use in the GCC environments."""
from compiler_gym.spaces import Reward
from compiler_gym.views.observation import ObservationView
class AsmSizeReward(Reward):
"""Reward for the size in bytes of the assembly code"""
def __init__(self):
super().__init__(
name="asm_size",
observation_spaces=["asm_size"],
default_value=0,
default_negates_returns=True,
deterministic=False,
platform_dependent=True,
)
self.previous = None
def reset(self, benchmark: str, observation_view: ObservationView):
super().reset(benchmark, observation_view)
del benchmark # unused
self.previous = None
def update(self, action, observations, observation_view):
del action # unused
del observation_view # unused
if self.previous is None:
self.previous = observations[0]
reward = float(self.previous - observations[0])
self.previous = observations[0]
return reward
class ObjSizeReward(Reward):
"""Reward for the size in bytes of the object code"""
def __init__(self):
super().__init__(
name="obj_size",
observation_spaces=["obj_size"],
default_value=0,
default_negates_returns=True,
deterministic=False,
platform_dependent=True,
)
self.previous = None
def reset(self, benchmark: str, observation_view: ObservationView):
super().reset(benchmark, observation_view)
del benchmark # unused
self.previous = None
def update(self, action, observations, observation_view):
del action
del observation_view
if self.previous is None:
self.previous = observations[0]
reward = float(self.previous - observations[0])
self.previous = observations[0]
return reward
|
CompilerGym-development
|
compiler_gym/envs/gcc/gcc_rewards.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from pathlib import Path
from typing import Iterable
from compiler_gym.datasets import Benchmark, TarDatasetWithManifest
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.gcc.gcc import Gcc
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.filesystem import atomic_file_write
URIS = [
"benchmark://chstone-v0/adpcm",
"benchmark://chstone-v0/aes",
"benchmark://chstone-v0/blowfish",
"benchmark://chstone-v0/dfadd",
"benchmark://chstone-v0/dfdiv",
"benchmark://chstone-v0/dfmul",
"benchmark://chstone-v0/dfsin",
"benchmark://chstone-v0/gsm",
"benchmark://chstone-v0/jpeg",
"benchmark://chstone-v0/mips",
"benchmark://chstone-v0/motion",
"benchmark://chstone-v0/sha",
]
# TODO(github.com/facebookresearch/CompilerGym/issues/325): This can be merged
# with the LLVM implementation.
class CHStoneDataset(TarDatasetWithManifest):
"""A dataset of C programs curated from GitHub source code.
The dataset is from:
Hara, Yuko, Hiroyuki Tomiyama, Shinya Honda, Hiroaki Takada, and Katsuya
Ishii. "Chstone: A benchmark program suite for practical c-based
high-level synthesis." In 2008 IEEE International Symposium on Circuits
and Systems, pp. 1192-1195. IEEE, 2008.
And is available at:
http://www.ertl.jp/chstone/
"""
def __init__(
self,
gcc_bin: Path,
site_data_base: Path,
sort_order: int = 0,
):
super().__init__(
name="benchmark://chstone-v0",
description="Benchmarks for C-based High-Level Synthesis",
references={
"Paper": "http://www.yxi.com/applications/iscas2008-300_1027.pdf",
"Homepage": "http://www.ertl.jp/chstone/",
},
license="Mixture of open source and public domain licenses",
site_data_base=site_data_base,
tar_urls=[
"https://github.com/ChrisCummins/patmos_HLS/archive/e62d878ceb91e5a18007ca2e0a9602ee44ff7d59.tar.gz"
],
tar_sha256="f7acab9d3c3dc7b971e62c8454bc909d84bddb6d0a96378e41beb94231739acb",
strip_prefix="patmos_HLS-e62d878ceb91e5a18007ca2e0a9602ee44ff7d59/benchmarks/CHStone",
tar_compression="gz",
benchmark_file_suffix=".c",
sort_order=sort_order,
# We provide our own manifest.
manifest_urls=[],
manifest_sha256="",
)
self.gcc_bin = gcc_bin
def benchmark_uris(self) -> Iterable[str]:
yield from URIS
@memoized_property
def gcc(self):
# Defer instantiation of Gcc from the constructor as it will fail if the
# given Gcc is not available. Memoize the result as initialization is
# expensive.
return Gcc(bin=self.gcc_bin)
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:
self.install()
# Most of the source files are named after the parent directory, but not
# all.
c_file_name = {
"blowfish": "bf.c",
"motion": "mpeg2.c",
"sha": "sha_driver.c",
"jpeg": "main.c",
}.get(uri.path[1:], f"{uri.path[1:]}.c")
source_dir_path = Path(os.path.normpath(f"{self.dataset_root}/{uri.path}"))
source_path = source_dir_path / c_file_name
preprocessed_path = source_dir_path / "src.c"
# If the file does not exist, preprocess it on-demand.
if not preprocessed_path.is_file():
if not source_path.is_file():
raise LookupError(
f"Benchmark not found: {uri} (file not found: {source_path})"
)
with atomic_file_write(preprocessed_path) as tmp_path:
# TODO(github.com/facebookresearch/CompilerGym/issues/325): Send
# over the unprocessed code to the service, have the service
# preprocess. Until then, we do it client side with GCC having
# to be fixed by an environment variable.
self.gcc(
"-E",
"-o",
tmp_path.name,
c_file_name,
cwd=source_dir_path,
timeout=300,
)
return Benchmark.from_file(uri, preprocessed_path)
@property
def size(self) -> int:
return len(URIS)
|
CompilerGym-development
|
compiler_gym/envs/gcc/datasets/chstone.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import shutil
import subprocess
import tempfile
from pathlib import Path
from threading import Lock
from typing import Iterable, Optional, Union
import numpy as np
from fasteners import InterProcessLock
from compiler_gym.datasets import Benchmark, BenchmarkSource, Dataset
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.datasets.uri import BenchmarkUri
from compiler_gym.envs.gcc.gcc import Gcc
from compiler_gym.util.commands import Popen
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.runfiles_path import runfiles_path
from compiler_gym.util.shell_format import plural
from compiler_gym.util.truncate import truncate
logger = logging.getLogger(__name__)
# The maximum value for the --seed argument to csmith.
UINT_MAX = (2**32) - 1
_CSMITH_BIN = runfiles_path("compiler_gym/third_party/csmith/csmith/bin/csmith")
_CSMITH_INCLUDES = runfiles_path(
"compiler_gym/third_party/csmith/csmith/include/csmith-2.3.0"
)
_CSMITH_INSTALL_LOCK = Lock()
# TODO(github.com/facebookresearch/CompilerGym/issues/325): This can be merged
# with the LLVM implementation.
class CsmithBenchmark(BenchmarkWithSource):
"""A CSmith benchmark."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._src = None
@classmethod
def create(cls, uri: str, bitcode: bytes, src: bytes) -> Benchmark:
"""Create a benchmark from paths."""
benchmark = cls.from_file_contents(uri, bitcode)
benchmark._src = src # pylint: disable=protected-access
return benchmark
@memoized_property
def sources(self) -> Iterable[BenchmarkSource]:
return [
BenchmarkSource(filename="source.c", contents=self._src),
]
@property
def source(self) -> str:
"""Return the single source file contents as a string."""
return self._src.decode("utf-8")
class CsmithDataset(Dataset):
"""A dataset which uses Csmith to generate programs.
Csmith is a tool that can generate random conformant C99 programs. It is
described in the publication:
Yang, Xuejun, Yang Chen, Eric Eide, and John Regehr. "Finding and
understanding bugs in C compilers." In Proceedings of the 32nd ACM
SIGPLAN conference on Programming Language Design and Implementation
(PLDI), pp. 283-294. 2011.
For up-to-date information about Csmith, see:
https://embed.cs.utah.edu/csmith/
Note that Csmith is a tool that is used to find errors in compilers. As
such, there is a higher likelihood that the benchmark cannot be used for an
environment and that :meth:`env.reset()
<compiler_gym.envs.CompilerEnv.reset>` will raise :class:`BenchmarkInitError
<compiler_gym.datasets.BenchmarkInitError>`.
"""
def __init__(
self,
gcc_bin: Union[Path, str],
site_data_base: Path,
sort_order: int = 0,
csmith_bin: Optional[Path] = None,
csmith_includes: Optional[Path] = None,
):
"""Constructor.
:param site_data_base: The base path of a directory that will be used to
store installed files.
:param sort_order: An optional numeric value that should be used to
order this dataset relative to others. Lowest value sorts first.
:param csmith_bin: The path of the Csmith binary to use. If not
provided, the version of Csmith shipped with CompilerGym is used.
:param csmith_includes: The path of the Csmith includes directory. If
not provided, the includes of the Csmith shipped with CompilerGym is
used.
"""
super().__init__(
name="generator://csmith-v0",
description="Random conformant C99 programs",
references={
"Paper": "http://web.cse.ohio-state.edu/~rountev.1/5343/pdf/pldi11.pdf",
"Homepage": "https://embed.cs.utah.edu/csmith/",
},
license="BSD",
site_data_base=site_data_base,
sort_order=sort_order,
benchmark_class=CsmithBenchmark,
)
self.gcc_bin = gcc_bin
self.csmith_bin_path = csmith_bin or _CSMITH_BIN
self.csmith_includes_path = csmith_includes or _CSMITH_INCLUDES
self._install_lockfile = self.site_data_path / ".install.LOCK"
@property
def size(self) -> int:
# Actually 2^32 - 1, but practically infinite for all intents and
# purposes.
return 0
@memoized_property
def gcc(self):
# Defer instantiation of Gcc from the constructor as it will fail if the
# given Gcc is not available. Memoize the result as initialization is
# expensive.
return Gcc(bin=self.gcc_bin)
def benchmark_uris(self) -> Iterable[str]:
return (f"{self.name}/{i}" for i in range(UINT_MAX))
def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> CsmithBenchmark:
return self.benchmark_from_seed(int(uri.path[1:]))
def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark:
seed = random_state.integers(UINT_MAX)
return self.benchmark_from_seed(seed)
@property
def installed(self) -> bool:
return super().installed and (self.site_data_path / "includes").is_dir()
def install(self) -> None:
super().install()
if self.installed:
return
with _CSMITH_INSTALL_LOCK, InterProcessLock(self._install_lockfile):
if (self.site_data_path / "includes").is_dir():
return
# Copy the Csmith headers into the dataset's site directory path because
# in bazel builds this includes directory is a symlink, and we need
# actual files that we can use in a docker volume.
shutil.copytree(
self.csmith_includes_path,
self.site_data_path / "includes.tmp",
)
# Atomic directory rename to prevent race on install().
(self.site_data_path / "includes.tmp").rename(
self.site_data_path / "includes"
)
def benchmark_from_seed(
self, seed: int, max_retries: int = 3, retry_count: int = 0
) -> CsmithBenchmark:
"""Get a benchmark from a uint32 seed.
:param seed: A number in the range 0 <= n < 2^32.
:return: A benchmark instance.
:raises OSError: If Csmith fails.
:raises BenchmarkInitError: If the C program generated by Csmith cannot
be lowered to LLVM-IR.
"""
if retry_count >= max_retries:
raise OSError(
f"Csmith failed after {retry_count} {plural(retry_count, 'attempt', 'attempts')} "
f"with seed {seed}"
)
self.install()
# Run csmith with the given seed and pipe the output to clang to
# assemble a bitcode.
logger.debug("Exec csmith --seed %d", seed)
with Popen(
[str(self.csmith_bin_path), "--seed", str(seed)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as csmith:
# Generate the C source.
src, stderr = csmith.communicate(timeout=300)
if csmith.returncode:
try:
stderr = "\n".join(
truncate(stderr.decode("utf-8"), max_line_len=200, max_lines=20)
)
logger.warning("Csmith failed with seed %d: %s", seed, stderr)
except UnicodeDecodeError:
# Failed to interpret the stderr output, generate a generic
# error message.
logger.warning("Csmith failed with seed %d", seed)
return self.benchmark_from_seed(
seed, max_retries=max_retries, retry_count=retry_count + 1
)
# Pre-process the source.
with tempfile.TemporaryDirectory() as tmpdir:
src_file = f"{tmpdir}/src.c"
with open(src_file, "wb") as f:
f.write(src)
preprocessed_src = self.gcc(
"-E",
"-I",
str(self.site_data_path / "includes"),
"-o",
"-",
src_file,
cwd=tmpdir,
timeout=60,
volumes={
str(self.site_data_path / "includes"): {
"bind": str(self.site_data_path / "includes"),
"mode": "ro",
}
},
)
return self.benchmark_class.create(
f"{self.name}/{seed}", preprocessed_src.encode("utf-8"), src
)
|
CompilerGym-development
|
compiler_gym/envs/gcc/datasets/csmith.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from functools import lru_cache
from pathlib import Path
from typing import Iterable, List, Optional, Union
from compiler_gym.datasets import Dataset
from compiler_gym.envs.gcc.datasets.anghabench import AnghaBenchDataset
from compiler_gym.envs.gcc.datasets.chstone import CHStoneDataset
from compiler_gym.envs.gcc.datasets.csmith import CsmithBenchmark, CsmithDataset
from compiler_gym.util.runfiles_path import site_data_path
def _get_gcc_datasets(
gcc_bin: Union[str, Path], site_data_base: Optional[Path] = None
) -> Iterable[Dataset]:
site_data_base = site_data_base or site_data_path("gcc-v0")
yield CHStoneDataset(gcc_bin=gcc_bin, site_data_base=site_data_base)
yield AnghaBenchDataset(site_data_base=site_data_base)
yield CsmithDataset(gcc_bin=gcc_bin, site_data_base=site_data_base)
@lru_cache(maxsize=16)
def get_gcc_datasets(
gcc_bin: Union[str, Path], site_data_base: Optional[Path] = None
) -> List[Dataset]:
"""Instantiate the builtin GCC datasets.
:param gcc_bin: The GCC binary to use.
:param site_data_base: The root of the site data path.
:return: An iterable sequence of :class:`Dataset
<compiler_gym.datasets.Dataset>` instances.
"""
return list(_get_gcc_datasets(gcc_bin, site_data_base))
__all__ = [
"AnghaBenchDataset",
"CHStoneDataset",
"CsmithBenchmark",
"CsmithDataset",
"get_gcc_datasets",
]
|
CompilerGym-development
|
compiler_gym/envs/gcc/datasets/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
from pathlib import Path
from typing import Optional
from compiler_gym.datasets import TarDatasetWithManifest
# TODO(github.com/facebookresearch/CompilerGym/issues/325): This can be merged
# with the LLVM implementation.
class AnghaBenchDataset(TarDatasetWithManifest):
"""A dataset of C programs curated from GitHub source code.
The dataset is from:
da Silva, Anderson Faustino, Bruno Conde Kind, José Wesley de Souza
Magalhaes, Jerônimo Nunes Rocha, Breno Campos Ferreira Guimaraes, and
Fernando Magno Quinão Pereira. "ANGHABENCH: A Suite with One Million
Compilable C Benchmarks for Code-Size Reduction." In 2021 IEEE/ACM
International Symposium on Code Generation and Optimization (CGO),
pp. 378-390. IEEE, 2021.
And is available at:
http://cuda.dcc.ufmg.br/angha/home
"""
def __init__(
self,
site_data_base: Path,
sort_order: int = 0,
manifest_url: Optional[str] = None,
manifest_sha256: Optional[str] = None,
deprecated: Optional[str] = None,
name: Optional[str] = None,
):
manifest_url_, manifest_sha256_ = {
"darwin": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-anghabench-v1-macos-manifest.bz2",
"96ead63da5f8efa07fd0370f0c6e452b59bed840828b8b19402102b1ce3ee109",
),
"linux": (
"https://dl.fbaipublicfiles.com/compiler_gym/llvm_bitcodes-10.0.0-anghabench-v1-linux-manifest.bz2",
"14df85f650199498cf769715e9f0d7841d09f9fa62a95b8ecc242bdaf227f33a",
),
}[sys.platform]
super().__init__(
name=name or "benchmark://anghabench-v1",
description="Compile-only C/C++ functions extracted from GitHub",
references={
"Paper": "https://homepages.dcc.ufmg.br/~fernando/publications/papers/FaustinoCGO21.pdf",
"Homepage": "http://cuda.dcc.ufmg.br/angha/",
},
license="Unknown. See: https://github.com/brenocfg/AnghaBench/issues/1",
site_data_base=site_data_base,
manifest_urls=[manifest_url or manifest_url_],
manifest_sha256=manifest_sha256 or manifest_sha256_,
tar_urls=[
"https://github.com/brenocfg/AnghaBench/archive/d8034ac8562b8c978376008f4b33df01b8887b19.tar.gz"
],
tar_sha256="85d068e4ce44f2581e3355ee7a8f3ccb92568e9f5bd338bc3a918566f3aff42f",
strip_prefix="AnghaBench-d8034ac8562b8c978376008f4b33df01b8887b19",
tar_compression="gz",
benchmark_file_suffix=".c",
sort_order=sort_order,
deprecated=deprecated,
)
|
CompilerGym-development
|
compiler_gym/envs/gcc/datasets/anghabench.py
|
#! /usr/bin/env python3
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""A CompilerGym service for GCC."""
import codecs
import hashlib
import json
import logging
import os
import pickle
import re
from collections import Counter
from pathlib import Path
from typing import List, Optional, Tuple
from urllib.request import urlopen
from compiler_gym.envs.gcc import Gcc, Option
from compiler_gym.service import CompilationSession
from compiler_gym.service.proto import (
ActionSpace,
Benchmark,
ByteSequenceSpace,
ByteTensor,
Event,
Int64Range,
Int64Tensor,
ListSpace,
NamedDiscreteSpace,
ObservationSpace,
Space,
StringSpace,
)
logger = logging.getLogger(__name__)
def make_gcc_compilation_session(gcc_bin: str):
"""Create a class to represent a GCC compilation service.
:param gcc_bin: Path to the gcc executable. This can a command name, like
"gcc", or it can be path to the executable. Finally, if prefixed with
"docker:" it can be the name of a docker image, e.g. "docker:gcc:11.2.0"
"""
gcc = Gcc(gcc_bin)
# The available actions
actions = []
# Actions that are small will have all their various choices made as
# explicit actions.
# Actions that are not small will have the abbility to increment the choice
# by different amounts.
for i, option in enumerate(gcc.spec.options):
if len(option) < 10:
for j in range(len(option)):
actions.append(SimpleAction(option, i, j))
if len(option) >= 10:
actions.append(IncrAction(option, i, 1))
actions.append(IncrAction(option, i, -1))
if len(option) >= 50:
actions.append(IncrAction(option, i, 10))
actions.append(IncrAction(option, i, -10))
if len(option) >= 500:
actions.append(IncrAction(option, i, 100))
actions.append(IncrAction(option, i, -100))
if len(option) >= 5000:
actions.append(IncrAction(option, i, 1000))
actions.append(IncrAction(option, i, -1000))
action_spaces_ = [
ActionSpace(
name="default",
space=Space(
named_discrete=NamedDiscreteSpace(name=[str(a) for a in actions]),
),
),
]
observation_spaces_ = [
# A string of the source code
ObservationSpace(
name="source",
space=Space(string_value=StringSpace(length_range=Int64Range(min=0))),
deterministic=True,
platform_dependent=False,
default_observation=Event(string_value=""),
),
# A string of the rtl code
ObservationSpace(
name="rtl",
space=Space(string_value=StringSpace(length_range=Int64Range(min=0))),
deterministic=True,
platform_dependent=True,
default_observation=Event(string_value=""),
),
# A string of the assembled code
ObservationSpace(
name="asm",
space=Space(string_value=StringSpace(length_range=Int64Range(min=0))),
deterministic=True,
platform_dependent=True,
default_observation=Event(string_value=""),
),
# The size of the assembled code
ObservationSpace(
name="asm_size",
space=Space(int64_value=Int64Range(min=-1)),
deterministic=True,
platform_dependent=True,
default_observation=Event(
int64_value=-1,
),
),
# The hash of the assembled code
ObservationSpace(
name="asm_hash",
space=Space(
string_value=StringSpace(length_range=Int64Range(min=0, max=200)),
),
deterministic=True,
platform_dependent=True,
default_observation=Event(string_value=""),
),
# Asm instruction counts - Counter as a JSON string
ObservationSpace(
name="instruction_counts",
space=Space(
string_value=StringSpace(length_range=Int64Range(min=0)),
),
deterministic=True,
platform_dependent=True,
default_observation=Event(string_value=""),
),
# A bytes of the object code
ObservationSpace(
name="obj",
space=Space(
byte_sequence=ByteSequenceSpace(length_range=Int64Range(min=0)),
),
deterministic=True,
platform_dependent=False,
default_observation=Event(byte_tensor=ByteTensor(shape=[0], value=b"")),
),
# The size of the object code
ObservationSpace(
name="obj_size",
space=Space(int64_value=Int64Range(min=-1)),
deterministic=True,
platform_dependent=True,
default_observation=Event(
int64_value=-1,
),
),
# The hash of the object code
ObservationSpace(
name="obj_hash",
space=Space(
string_value=StringSpace(length_range=Int64Range(min=0, max=200)),
),
deterministic=True,
platform_dependent=True,
default_observation=Event(string_value=""),
),
# A list of the choices. Each element corresponds to an option in the spec.
# '-1' indicates that this is empty on the command line (e.g. if the choice
# corresponding to the '-O' option is -1, then no -O flag will be emitted.)
# If a nonnegative number if given then that particular choice is used
# (e.g. for the -O flag, 5 means use '-Ofast' on the command line.)
ObservationSpace(
name="choices",
space=Space(
space_list=ListSpace(
space=[
Space(int64_value=Int64Range(min=0, max=len(option) - 1))
for option in gcc.spec.options
]
),
),
),
# The command line for compiling the object file as a string
ObservationSpace(
name="command_line",
space=Space(
string_value=StringSpace(length_range=Int64Range(min=0, max=200)),
),
deterministic=True,
platform_dependent=True,
default_observation=Event(string_value=""),
),
]
class GccCompilationSession(CompilationSession):
"""A GCC interactive compilation session."""
compiler_version: str = gcc.spec.version
action_spaces = action_spaces_
observation_spaces = observation_spaces_
def __init__(
self,
working_directory: Path,
action_space: ActionSpace,
benchmark: Benchmark,
):
super().__init__(working_directory, action_space, benchmark)
# The benchmark being used
self.benchmark = benchmark
# Timeout value for compilation (in seconds)
self._timeout = None
# The source code
self._source = None
# The rtl code
self._rtl = None
# The assembled code
self._asm = None
# Size of the assembled code
self._asm_size = None
# Hash of the assembled code
self._asm_hash = None
# The object binary
self._obj = None
# size of the object binary
self._obj_size = None
# Hash of the object binary
self._obj_hash = None
# Set the path to the GCC executable
self._gcc_bin = "gcc"
# Initially the choices and the spec, etc are empty. They will be
# initialised lazily
self._choices = None
@property
def num_actions(self) -> int:
return len(self.action_spaces[0].space.named_discrete.name)
@property
def choices(self) -> List[int]:
if self._choices is None:
self._choices = [-1] * len(gcc.spec.options)
return self._choices
@choices.setter
def choices(self, value: List[int]):
self._choices = value
@property
def source(self) -> str:
"""Get the benchmark source"""
self.prepare_files()
return self._source
@property
def rtl(self) -> bytes:
"""Get the RTL code"""
self.dump_rtl()
return self._rtl
@property
def asm(self) -> bytes:
"""Get the assembled code"""
self.assemble()
return self._asm
@property
def asm_size(self) -> int:
"""Get the assembled code size"""
self.assemble()
return self._asm_size
@property
def asm_hash(self) -> str:
"""Get the assembled code hash"""
self.assemble()
return self._asm_hash
@property
def instruction_counts(self) -> str:
"""Get the instuction counts as a JSON string"""
self.assemble()
insn_pat = re.compile("\t([a-zA-Z-0-9.-]+).*")
insn_cnts = Counter()
lines = self._asm.split("\n")
for line in lines:
m = insn_pat.fullmatch(line)
if m:
insn_cnts[m.group(1)] += 1
return json.dumps(insn_cnts)
@property
def obj(self) -> bytes:
"""Get the compiled code"""
self.compile()
return self._obj
@property
def obj_size(self) -> int:
"""Get the compiled code size"""
self.compile()
return self._obj_size
@property
def obj_hash(self) -> str:
"""Get the compiled code hash"""
self.compile()
return self._obj_hash
@property
def src_path(self) -> Path:
"""Get the path to the source file"""
return self.working_dir / "src.c"
@property
def obj_path(self) -> Path:
"""Get the path to object file"""
return self.working_dir / "obj.o"
@property
def asm_path(self) -> Path:
"""Get the path to the assembly"""
return self.working_dir / "asm.s"
@property
def rtl_path(self) -> Path:
"""Get the path to the rtl"""
return self.working_dir / "rtl.lsp"
def obj_command_line(
self, src_path: Path = None, obj_path: Path = None
) -> List[str]:
"""Get the command line to create the object file.
The 'src_path' and 'obj_path' give the input and output paths. If not
set, then they are taken from 'self.src_path' and 'self.obj_path'. This
is useful for printing where the actual paths are not important."""
src_path = src_path or self.src_path
obj_path = obj_path or self.obj_path
# Gather the choices as strings
opts = [
option[choice]
for option, choice in zip(gcc.spec.options, self.choices)
if choice >= 0
]
cmd_line = opts + ["-w", "-c", src_path, "-o", obj_path]
return cmd_line
def asm_command_line(
self, src_path: Path = None, asm_path: Path = None
) -> List[str]:
"""Get the command line to create the assembly file.
The 'src_path' and 'asm_path' give the input and output paths. If not
set, then they are taken from 'self.src_path' and 'self.obj_path'. This
is useful for printing where the actual paths are not important."""
src_path = src_path or self.src_path
asm_path = asm_path or self.asm_path
opts = [
option[choice]
for option, choice in zip(gcc.spec.options, self.choices)
if choice >= 0
]
cmd_line = opts + ["-w", "-S", src_path, "-o", asm_path]
return cmd_line
def rtl_command_line(
self, src_path: Path = None, rtl_path: Path = None, asm_path: Path = None
) -> List[str]:
"""Get the command line to create the rtl file - might as well do the
asm at the same time.
The 'src_path', 'rtl_path', 'asm_path' give the input and output paths. If not
set, then they are taken from 'self.src_path' and 'self.obj_path'. This
is useful for printing where the actual paths are not important."""
src_path = src_path or self.src_path
rtl_path = rtl_path or self.rtl_path
asm_path = asm_path or self.asm_path
opts = [
option[choice]
for option, choice in zip(gcc.spec.options, self.choices)
if choice >= 0
]
cmd_line = opts + [
"-w",
"-S",
src_path,
f"-fdump-rtl-dfinish={rtl_path}",
"-o",
asm_path,
]
return cmd_line
def prepare_files(self):
"""Copy the source to the working directory."""
if not self._source:
if self.benchmark.program.contents:
self._source = self.benchmark.program.contents.decode()
else:
with urlopen(self.benchmark.program.uri) as r:
self._source = r.read().decode()
with open(self.src_path, "w") as f:
print(self._source, file=f)
def compile(self) -> Optional[str]:
"""Compile the benchmark"""
if not self._obj:
self.prepare_files()
logger.debug(
"Compiling: %s", " ".join(map(str, self.obj_command_line()))
)
gcc(
*self.obj_command_line(),
cwd=self.working_dir,
timeout=self._timeout,
)
with open(self.obj_path, "rb") as f:
# Set the internal variables
self._obj = f.read()
self._obj_size = os.path.getsize(self.obj_path)
self._obj_hash = hashlib.md5(self._obj).hexdigest()
def assemble(self) -> Optional[str]:
"""Assemble the benchmark"""
if not self._asm:
self.prepare_files()
logger.debug(
"Assembling: %s", " ".join(map(str, self.asm_command_line()))
)
gcc(
*self.asm_command_line(),
cwd=self.working_dir,
timeout=self._timeout,
)
with open(self.asm_path, "rb") as f:
# Set the internal variables
asm_bytes = f.read()
self._asm = asm_bytes.decode()
self._asm_size = os.path.getsize(self.asm_path)
self._asm_hash = hashlib.md5(asm_bytes).hexdigest()
def dump_rtl(self) -> Optional[str]:
"""Dump the RTL (and assemble the benchmark)"""
if not self._rtl:
self.prepare_files()
logger.debug(
"Dumping RTL: %s", " ".join(map(str, self.rtl_command_line()))
)
gcc(
*self.rtl_command_line(),
cwd=self.working_dir,
timeout=self._timeout,
)
with open(self.asm_path, "rb") as f:
# Set the internal variables
asm_bytes = f.read()
self._asm = asm_bytes.decode()
self._asm_size = os.path.getsize(self.asm_path)
self._asm_hash = hashlib.md5(asm_bytes).hexdigest()
with open(self.rtl_path, "rb") as f:
# Set the internal variables
rtl_bytes = f.read()
self._rtl = rtl_bytes.decode()
def reset_cached(self):
"""Reset the cached values"""
self._obj = None
self._obj_size = None
self._obj_hash = None
self._rtl = None
self._asm = None
self._asm_size = None
self._asm_hash = None
def apply_action(
self, action_proto: Event
) -> Tuple[bool, Optional[ActionSpace], bool]:
"""Apply an action."""
if not action_proto.HasField("int64_value"):
raise ValueError("Invalid action, int64_value expected.")
choice_index = action_proto.int64_value
if choice_index < 0 or choice_index >= self.num_actions:
raise ValueError("Out-of-range")
# Get the action
action = actions[choice_index]
# Apply the action to this session and check if we changed anything
old_choices = self.choices.copy()
action(self)
logger.debug("Applied action %s", action)
# Reset the internal variables if this action has caused a change in the
# choices
if old_choices != self.choices:
self.reset_cached()
# The action has not changed anything yet. That waits until an
# observation is taken
return False, None, False
def get_observation(self, observation_space: ObservationSpace) -> Event:
"""Get one of the observations"""
if observation_space.name == "source":
return Event(string_value=self.source or "")
elif observation_space.name == "rtl":
return Event(string_value=self.rtl or "")
elif observation_space.name == "asm":
return Event(string_value=self.asm or "")
elif observation_space.name == "asm_size":
return Event(int64_value=self.asm_size or -1)
elif observation_space.name == "asm_hash":
return Event(string_value=self.asm_hash or "")
elif observation_space.name == "instruction_counts":
return Event(string_value=self.instruction_counts or "{}")
elif observation_space.name == "obj":
value = self.obj or b""
return Event(byte_tensor=ByteTensor(shape=[len(value)], value=value))
elif observation_space.name == "obj_size":
return Event(int64_value=self.obj_size or -1)
elif observation_space.name == "obj_hash":
return Event(string_value=self.obj_hash or "")
elif observation_space.name == "choices":
observation = Event(
int64_tensor=Int64Tensor(
shape=[len(self.choices)], value=self.choices
)
)
return observation
elif observation_space.name == "command_line":
return Event(
string_value=gcc.bin
+ " "
+ " ".join(map(str, self.obj_command_line("src.c", "obj.o")))
)
else:
raise KeyError(observation_space.name)
def handle_session_parameter(self, key: str, value: str) -> Optional[str]:
if key == "gcc_spec":
return codecs.encode(pickle.dumps(gcc.spec), "base64").decode()
elif key == "choices":
choices = list(map(int, value.split(",")))
assert len(choices) == len(gcc.spec.options)
assert all(
-1 <= p <= len(gcc.spec.options[i]) for i, p in enumerate(choices)
)
if choices != self.choices:
self.choices = choices
self.reset_cached()
return ""
elif key == "timeout":
self._timeout = None if value == "" else int(value)
return ""
return None
return GccCompilationSession
class Action:
"""An action is applying a choice to an option"""
def __init__(self, option: Option, option_index: int):
"""The option and its index in the option list. We need the index to
match it with the corresponding choice later during the application of
the action."""
self.option = option
self.option_index = option_index
def __call__(self, session: "GccCompilationSession"): # noqa
"""Apply the action to the session."""
raise NotImplementedError()
def __str__(self) -> str:
raise NotImplementedError()
class SimpleAction(Action):
"""A simple action just sets the choice directly.
The choice_index describes which choice to apply."""
def __init__(self, option: Option, option_index: int, choice_index: int):
super().__init__(option, option_index)
self.choice_index = choice_index
def __call__(self, session: "GccCompilationSession"): # noqa
session.choices[self.option_index] = self.choice_index
def __str__(self) -> str:
return self.option[self.choice_index]
class IncrAction(Action):
"""An action that increments a choice by an amount."""
def __init__(self, option: Option, option_index: int, choice_incr: int):
super().__init__(option, option_index)
self.choice_incr = choice_incr
def __call__(self, session: "GccCompilationSession"): # noqag
choice = session.choices[self.option_index]
choice += self.choice_incr
if choice < -1:
choice = -1
if choice >= len(self.option):
choice = len(self.option) - 1
session.choices[self.option_index] = choice
def __str__(self) -> str:
return f"{self.option}[{self.choice_incr:+}]"
|
CompilerGym-development
|
compiler_gym/envs/gcc/service/gcc_service.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Register the MLIR environments."""
from compiler_gym.envs.mlir.mlir_env import MlirEnv
from compiler_gym.util.registration import register
from compiler_gym.util.runfiles_path import runfiles_path
__all__ = [
"MLIR_SERVICE_BINARY",
"MlirEnv",
]
MLIR_SERVICE_BINARY = runfiles_path(
"compiler_gym/envs/mlir/service/compiler_gym-mlir-service"
)
def _register_mlir_gym_service():
"""Register an environment for each combination of MLIR
observation/reward/benchmark."""
register(
id="mlir-v0",
entry_point="compiler_gym.envs.mlir:MlirEnv",
kwargs={
"service": MLIR_SERVICE_BINARY,
},
)
_register_mlir_gym_service()
|
CompilerGym-development
|
compiler_gym/envs/mlir/__init__.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
from typing import Iterable, List, Optional, Union
import numpy as np
from compiler_gym.datasets import Dataset
from compiler_gym.envs.mlir.datasets import MatmulBenchmark, get_mlir_datasets
from compiler_gym.service.client_service_compiler_env import ClientServiceCompilerEnv
from compiler_gym.spaces import Reward, RuntimeReward
from compiler_gym.util.gym_type_hints import ActionType
from compiler_gym.views import ObservationSpaceSpec
_MLIR_DATASETS: Optional[List[Dataset]] = None
def _get_mlir_datasets(site_data_base: Optional[Path] = None) -> Iterable[Dataset]:
"""Get the MLIR datasets. Use a singleton value when site_data_base is the
default value.
"""
global _MLIR_DATASETS
if site_data_base is None:
if _MLIR_DATASETS is None:
_MLIR_DATASETS = list(get_mlir_datasets(site_data_base=site_data_base))
return _MLIR_DATASETS
return get_mlir_datasets(site_data_base=site_data_base)
class MlirEnv(ClientServiceCompilerEnv):
"""Environment that exposes optimization parameters for matrix multiplication in MLIR.
It optimizes the operation C = A * B, where A is an MxK matrix and B is an KxN.
This environment is still under construction.
The observation space is the running time of the operation.
All optimization parameters are supplied in a single step.
In other words the episode length is 1 step.
It supports x86_64 processors."""
def __init__(
self,
*args,
benchmark: Optional[Union[str, MatmulBenchmark]] = None,
datasets_site_path: Optional[Path] = None,
rewards: Optional[List[Reward]] = None,
**kwargs
):
"""
:param args: Positional arguments passed to the base class
`compiler_gym.service.ClientServiceCompilerEnv`.
:param benchmark: Specifies what MLIR code is to be optimize.
Currently the default benchmark and only benchmark is M=N=K=64.
:param rewards: The reward spaces that this environment supports.
Defaults to (-running time).
:param datasets_site_path: The base path of a directory that will be used to
store installed files.
:param kwargs: keyworded arguments passed to the base class
`compiler_gym.service.ClientServiceCompilerEnv`.
"""
super().__init__(
*args,
**kwargs,
rewards=[
RuntimeReward(
runtime_count=1,
warmup_count=0,
estimator=np.median,
default_value=-1,
)
]
if rewards is None
else rewards,
datasets=_get_mlir_datasets(site_data_base=datasets_site_path),
benchmark=benchmark
)
self._runtimes_per_observation_count: Optional[int] = None
self.reset()
if rewards is None:
self.reward.spaces["runtime"].runtime_count = self.runtime_observation_count
@property
def runtime_observation_count(self) -> int:
return self._runtimes_per_observation_count or int(
self.send_param("mlir.get_runtimes_per_observation_count", "")
)
@runtime_observation_count.setter
def runtime_observation_count(self, n: int) -> None:
if self.in_episode:
self.send_param("mlir.set_runtimes_per_observation_count", str(n))
self._runtimes_per_observation_count = n
def reset(self, *args, **kwargs):
observation = super().reset(*args, **kwargs)
# Resend the runtimes-per-observation session parameter, if it is a
# non-default value.
if self._runtimes_per_observation_count is not None:
self.runtime_observation_count = self._runtimes_per_observation_count
return observation
def fork(self):
fkd = super().fork()
if self.runtime_observation_count is not None:
fkd.runtime_observation_count = self.runtime_observation_count
return fkd
def step( # pylint: disable=arguments-differ
self,
action: ActionType,
observation_spaces: Optional[Iterable[Union[str, ObservationSpaceSpec]]] = None,
reward_spaces: Optional[Iterable[Union[str, Reward]]] = None,
):
return self.multistep(
actions=[action],
observation_spaces=observation_spaces,
reward_spaces=reward_spaces,
)
|
CompilerGym-development
|
compiler_gym/envs/mlir/mlir_env.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from pathlib import Path
from typing import Iterable, Optional
from compiler_gym.datasets import Benchmark, BenchmarkSource, Dataset
from compiler_gym.datasets.benchmark import BenchmarkWithSource
from compiler_gym.service.proto import BenchmarkDynamicConfig, Command
from compiler_gym.util.decorators import memoized_property
from compiler_gym.util.runfiles_path import runfiles_path, site_data_path
from compiler_gym.util.shell_format import plural
logger = logging.getLogger(__name__)
# The maximum value for the --seed argument to matmul.
UINT_MAX = (2**32) - 1
_matmul_bin = runfiles_path("compiler_gym/third_party/matmul/matmul/bin/matmul")
_matmul_includes = runfiles_path(
"compiler_gym/third_party/matmul/matmul/include/matmul-2.3.0"
)
matmul_sizes = [(64, 64, 64)]
class MatmulBenchmark(BenchmarkWithSource):
"""A matmul benchmark."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._src = None
self.proto.dynamic_config.MergeFrom(
BenchmarkDynamicConfig(
build_cmd=Command(
argument=["$CC", "$IN"],
outfile=["benchmark_main"],
timeout_seconds=120,
),
run_cmd=Command(
argument=["./benchmark_main", "--benchmark_format=json"],
timeout_seconds=300,
),
)
)
@classmethod
def create(cls, uri: str, bitcode: bytes, src: bytes) -> Benchmark:
"""Create a benchmark from paths."""
benchmark = cls.from_file_contents(uri, bitcode)
benchmark._src = src # pylint: disable=protected-access
return benchmark
@memoized_property
def sources(self) -> Iterable[BenchmarkSource]:
return [
BenchmarkSource(filename="source.mlir", contents=self._src),
]
@property
def source(self) -> str:
"""Return the single source file contents as a string."""
return self._src.decode("utf-8")
class MatmulDataset(Dataset):
"""A dataset which generates matmul programs."""
def __init__(
self,
site_data_base: Path,
sort_order: int = 0,
matmul_bin: Optional[Path] = None,
matmul_includes: Optional[Path] = None,
):
"""Constructor.
:param site_data_base: The base path of a directory that will be used to
store installed files.
:param sort_order: An optional numeric value that should be used to
order this dataset relative to others. Lowest value sorts first.
:param matmul_bin: The path of the matmul binary to use. If not
provided, the version of matmul shipped with CompilerGym is used.
:param matmul_includes: The path of the matmul includes directory. If
not provided, the includes of the matmul shipped with CompilerGym is
used.
"""
super().__init__(
name="generator://matmul-v0",
description="Targeted size matmul programs",
references={},
license="MIT",
site_data_base=site_data_base,
sort_order=sort_order,
benchmark_class=MatmulBenchmark,
)
self.matmul_bin_path = matmul_bin or _matmul_bin
self.matmul_includes_path = matmul_includes or _matmul_includes
@property
def size(self) -> int:
return len(matmul_sizes)
def name_from_size(self, mnk):
return f"{self.name}/{mnk[0]}_{mnk[1]}_{mnk[2]}"
# TODO(kyleherndon): Benchmarks are actually dynamically generated for any
# provided parameters, figure out a better way to represent this in the list of
# available benchmarks
def benchmark_uris(self) -> Iterable[str]:
return (self.name_from_size(mnk) for mnk in matmul_sizes)
def benchmark(self, uri: str) -> MatmulBenchmark:
sizestr = uri.split("/")[-1]
sizetuple = (int(i) for i in sizestr.split("_"))
return self.benchmark_from_size(sizetuple)
def benchmark_from_size(
self, mnk, max_retries: int = 3, retry_count: int = 0
) -> MatmulBenchmark:
"""Get a benchmark from a uint32 seed.
:param mnk: 3-tuple containing m, n, k sizes of the matmul
:return: A benchmark instance.
:raises OSError: If matmul fails.
:raises BenchmarkInitError: If the C program generated by matmul cannot
be lowered to mlir-IR.
"""
if retry_count >= max_retries:
raise OSError(
f"matmul failed after {retry_count} {plural(retry_count, 'attempt', 'attempts')} "
f"with size {mnk}"
)
self.install()
mnk = list(mnk)
# Run matmul with the given size and regex to produce the correct mlir
logger.debug("Exec matmul --mnk %d", mnk)
# TODO(kyleherndon): refactor these to another location
src_content = """
func @matmul(%a: tensor<${M}x${K}xf32> {linalg.buffer_layout = affine_map<(i, j)[s0, s1] -> (i, j)>},
%b: tensor<${K}x${N}xf32> {linalg.buffer_layout = affine_map<(i, j)[s0, s1] -> (i, j)>},
%c: tensor<${M}x${N}xf32> {linalg.buffer_layout = affine_map<(i, j)[s0, s1] -> (i, j)>}) -> tensor<${M}x${N}xf32>
attributes { passthrough = [["target-cpu", "haswell"], ["prefer-vector-width", "256"]]}
{
%f0 = arith.constant 0.0 : f32
%f1 = linalg.fill(%f0, %c) : f32, tensor<${M}x${N}xf32> -> tensor<${M}x${N}xf32>
%d = linalg.matmul ins(%a, %b : tensor<${M}x${K}xf32>, tensor<${K}x${N}xf32>)
outs(%f1: tensor<${M}x${N}xf32>) -> tensor<${M}x${N}xf32>
return %d : tensor<${M}x${N}xf32>
}"""
cc_src = """
#include <benchmark/benchmark.h>
#include <mlir/ExecutionEngine/RunnerUtils.h>
#include <cstdio>
#include <vector>
void naive_matmul(const float* a, const float* b, float* c, size_t m, size_t k, size_t n) {
// correctness check
for (size_t i = 0; i < m; i++) {
for (size_t j = 0; j < n; j++) {
#ifdef COLUMN_MAJOR
size_t ci = i + j * m;
#else
size_t ci = i * n + j;
#endif
c[ci] = 0.0f;
for (size_t p = 0; p < k; p++) {
#ifdef COLUMN_MAJOR
c[ci] += a[i + p * m] * b[p + j * k];
#else
c[ci] += a[i * k + p] * b[p * n + j];
#endif
}
}
}
}
void init_matrix(float* a, int nrows, int ncols) {
for (int j = 0; j < ncols; j++) {
for (int i = 0; i < nrows; i++) {
a[i + j * nrows] = ((float)rand() / (float)RAND_MAX);
}
}
}
extern "C" {
void matmul(float* aligned_a, float* allocated_a, int64_t offset_a, int64_t size_a0,
int64_t size_a1, int64_t strides_a0, int64_t strides_a1, float* aligned_b,
float* allocated_b, int64_t offset_b, int64_t size_b0, int64_t size_b1,
int64_t strides_b0, int64_t strides_b1, float* aligned_c, float* allocated_c,
int64_t offset_c, int64_t size_c0, int64_t size_c1, int64_t strides_c0,
int64_t strides_c1);
}
size_t g_errors = 0;
static void BenchmarkFunction(benchmark::State& state) {
// TODO(boian): pass these as command line arguments
int MDIM = ${M};
int NDIM = ${N};
int KDIM = ${K};
std::vector<float> a(MDIM * KDIM);
std::vector<float> b(KDIM * NDIM);
std::vector<float> c(MDIM * NDIM);
float *A = a.data(), *B = b.data(), *C = c.data();
// a[0] = 1; b[0] = 2;
init_matrix(A, MDIM, KDIM);
init_matrix(B, KDIM, NDIM);
init_matrix(C, MDIM, NDIM);
int LDA = KDIM;
int LDB = NDIM;
int LDC = NDIM;
for (auto _ : state) {
matmul(A, A, 0, MDIM, KDIM, LDA, 1, B, B, 0, KDIM, NDIM, LDB, 1, C, C, 0, MDIM, NDIM, LDC, 1);
}
std::vector<float> c2(MDIM * NDIM);
float* C2 = c2.data();
size_t errors = 0;
naive_matmul(A, B, C2, MDIM, KDIM, NDIM);
for (size_t i = 0; i < MDIM; i++) {
for (size_t j = 0; j < NDIM; j++) {
size_t ci = i + j * MDIM;
if (std::abs(C[ci] - C2[ci]) > 0.01f) {
if (errors == 0) {
fprintf(stderr, "Incorrect result at index %ld,%ld: C=%0.2f C2=%0.2f\\n", i, j, C[ci],
C2[ci]);
}
errors++;
}
}
}
fprintf(stderr, "Detected %ld errors.\\n", errors);
g_errors = errors;
}
int main(int argc, char** argv) {
benchmark::Initialize(&argc, argv);
benchmark::RegisterBenchmark("BM_Matmul", BenchmarkFunction)
->MeasureProcessCPUTime()
->UseRealTime();
benchmark::RunSpecifiedBenchmarks();
benchmark::Shutdown();
return g_errors != 0;
}
"""
mlir_site_dir = site_data_path("mlir-v0")
mlir_site_dir.mkdir(parents=True, exist_ok=True)
mlir_file_path = site_data_path("mlir-v0") / "matmul.mlir.template"
with open(mlir_file_path, "w+") as mlir_file:
mlir_file.write(src_content)
mlir_file.close()
cc_file_path = site_data_path("mlir-v0") / "benchmark_main.cc.template"
with open(cc_file_path, "w+") as cc_file:
cc_file.write(cc_src)
cc_file.close()
new_content = src_content.replace("${M}", str(mnk[0]))
new_content = new_content.replace("${N}", str(mnk[1]))
content = new_content.replace("${K}", str(mnk[2]))
return self.benchmark_class.create(
self.name_from_size(mnk),
bytes(content, "utf-8"),
bytes(src_content, "utf-8"),
)
|
CompilerGym-development
|
compiler_gym/envs/mlir/datasets/matmul.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.