168 changes: 86 additions & 82 deletions llvm/lib/Analysis/models/gen-inline-oz-test-model.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import tensorflow as tf

POLICY_DECISION_LABEL = 'inlining_decision'
POLICY_DECISION_LABEL = "inlining_decision"
POLICY_OUTPUT_SPEC = """
[
{
Expand All @@ -31,106 +31,110 @@

# pylint: disable=g-complex-comprehension
def get_input_signature():
"""Returns the list of features for LLVM inlining."""
# int64 features
inputs = [
tf.TensorSpec(dtype=tf.int64, shape=(), name=key) for key in [
'caller_basic_block_count',
'caller_conditionally_executed_blocks',
'caller_users',
'callee_basic_block_count',
'callee_conditionally_executed_blocks',
'callee_users',
'nr_ctant_params',
'node_count',
'edge_count',
'callsite_height',
'cost_estimate',
'inlining_default',
'sroa_savings',
'sroa_losses',
'load_elimination',
'call_penalty',
'call_argument_setup',
'load_relative_intrinsic',
'lowered_call_arg_setup',
'indirect_call_penalty',
'jump_table_penalty',
'case_cluster_penalty',
'switch_penalty',
'unsimplified_common_instructions',
'num_loops',
'dead_blocks',
'simplified_instructions',
'constant_args',
'constant_offset_ptr_args',
'callsite_cost',
'cold_cc_penalty',
'last_call_to_static_bonus',
'is_multiple_blocks',
'nested_inlines',
'nested_inline_cost_estimate',
'threshold',
]
]

# float32 features
inputs.extend([
tf.TensorSpec(dtype=tf.float32, shape=(), name=key)
for key in ['discount', 'reward']
])

# int32 features
inputs.extend([
tf.TensorSpec(dtype=tf.int32, shape=(), name=key)
for key in ['step_type']
])
return inputs
"""Returns the list of features for LLVM inlining."""
# int64 features
inputs = [
tf.TensorSpec(dtype=tf.int64, shape=(), name=key)
for key in [
"caller_basic_block_count",
"caller_conditionally_executed_blocks",
"caller_users",
"callee_basic_block_count",
"callee_conditionally_executed_blocks",
"callee_users",
"nr_ctant_params",
"node_count",
"edge_count",
"callsite_height",
"cost_estimate",
"inlining_default",
"sroa_savings",
"sroa_losses",
"load_elimination",
"call_penalty",
"call_argument_setup",
"load_relative_intrinsic",
"lowered_call_arg_setup",
"indirect_call_penalty",
"jump_table_penalty",
"case_cluster_penalty",
"switch_penalty",
"unsimplified_common_instructions",
"num_loops",
"dead_blocks",
"simplified_instructions",
"constant_args",
"constant_offset_ptr_args",
"callsite_cost",
"cold_cc_penalty",
"last_call_to_static_bonus",
"is_multiple_blocks",
"nested_inlines",
"nested_inline_cost_estimate",
"threshold",
]
]

# float32 features
inputs.extend(
[
tf.TensorSpec(dtype=tf.float32, shape=(), name=key)
for key in ["discount", "reward"]
]
)

# int32 features
inputs.extend(
[tf.TensorSpec(dtype=tf.int32, shape=(), name=key) for key in ["step_type"]]
)
return inputs


def get_output_signature():
return POLICY_DECISION_LABEL
return POLICY_DECISION_LABEL


def get_output_spec():
return POLICY_OUTPUT_SPEC
return POLICY_OUTPUT_SPEC


def get_output_spec_path(path):
return os.path.join(path, 'output_spec.json')
return os.path.join(path, "output_spec.json")


def build_mock_model(path, signature):
"""Build and save the mock model with the given signature"""
module = tf.Module()
def action(*inputs):
return {signature['output']: tf.constant(value=1, dtype=tf.int64)}
"""Build and save the mock model with the given signature"""
module = tf.Module()

def action(*inputs):
return {signature["output"]: tf.constant(value=1, dtype=tf.int64)}

module.action = tf.function()(action)
action = {'action': module.action.get_concrete_function(signature['inputs'])}
tf.saved_model.save(module, path, signatures=action)
module.action = tf.function()(action)
action = {"action": module.action.get_concrete_function(signature["inputs"])}
tf.saved_model.save(module, path, signatures=action)

output_spec_path = get_output_spec_path(path)
with open(output_spec_path, 'w') as f:
print(f'Writing output spec to {output_spec_path}.')
f.write(signature['output_spec'])
output_spec_path = get_output_spec_path(path)
with open(output_spec_path, "w") as f:
print(f"Writing output spec to {output_spec_path}.")
f.write(signature["output_spec"])


def get_signature():
return {
'inputs': get_input_signature(),
'output': get_output_signature(),
'output_spec': get_output_spec()
}
return {
"inputs": get_input_signature(),
"output": get_output_signature(),
"output_spec": get_output_spec(),
}


def main(argv):
assert len(argv) == 2
model_path = argv[1]
assert len(argv) == 2
model_path = argv[1]

print(f'Output model to: [{argv[1]}]')
signature = get_signature()
build_mock_model(model_path, signature)
print(f"Output model to: [{argv[1]}]")
signature = get_signature()
build_mock_model(model_path, signature)


if __name__ == '__main__':
main(sys.argv)
if __name__ == "__main__":
main(sys.argv)
64 changes: 33 additions & 31 deletions llvm/lib/Analysis/models/gen-regalloc-eviction-test-model.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import os
import sys
import tensorflow as tf
POLICY_DECISION_LABEL = 'index_to_evict'

POLICY_DECISION_LABEL = "index_to_evict"
POLICY_OUTPUT_SPEC = """
[
{
Expand All @@ -22,49 +23,50 @@
}
]
"""
PER_REGISTER_FEATURE_LIST = ['mask']
PER_REGISTER_FEATURE_LIST = ["mask"]
NUM_REGISTERS = 33


def get_input_signature():
"""Returns (time_step_spec, action_spec) for LLVM register allocation."""
inputs = dict(
(key, tf.TensorSpec(dtype=tf.int64, shape=(NUM_REGISTERS), name=key))
for key in PER_REGISTER_FEATURE_LIST)
return inputs
"""Returns (time_step_spec, action_spec) for LLVM register allocation."""
inputs = dict(
(key, tf.TensorSpec(dtype=tf.int64, shape=(NUM_REGISTERS), name=key))
for key in PER_REGISTER_FEATURE_LIST
)
return inputs


def get_output_spec_path(path):
return os.path.join(path, 'output_spec.json')
return os.path.join(path, "output_spec.json")


def build_mock_model(path):
"""Build and save the mock model with the given signature."""
module = tf.Module()
# We have to set this useless variable in order for the TF C API to correctly
# intake it
module.var = tf.Variable(0, dtype=tf.int64)
"""Build and save the mock model with the given signature."""
module = tf.Module()
# We have to set this useless variable in order for the TF C API to correctly
# intake it
module.var = tf.Variable(0, dtype=tf.int64)

def action(*inputs):
result = (
tf.math.argmax(tf.cast(inputs[0]["mask"], tf.int32), axis=-1) + module.var
)
return {POLICY_DECISION_LABEL: result}

def action(*inputs):
result = tf.math.argmax(
tf.cast(inputs[0]['mask'], tf.int32), axis=-1) + module.var
return {POLICY_DECISION_LABEL: result}
module.action = tf.function()(action)
action = {
'action': module.action.get_concrete_function(get_input_signature())
}
tf.saved_model.save(module, path, signatures=action)
output_spec_path = get_output_spec_path(path)
with open(output_spec_path, 'w') as f:
print(f'Writing output spec to {output_spec_path}.')
f.write(POLICY_OUTPUT_SPEC)
module.action = tf.function()(action)
action = {"action": module.action.get_concrete_function(get_input_signature())}
tf.saved_model.save(module, path, signatures=action)
output_spec_path = get_output_spec_path(path)
with open(output_spec_path, "w") as f:
print(f"Writing output spec to {output_spec_path}.")
f.write(POLICY_OUTPUT_SPEC)


def main(argv):
assert len(argv) == 2
model_path = argv[1]
build_mock_model(model_path)
assert len(argv) == 2
model_path = argv[1]
build_mock_model(model_path)


if __name__ == '__main__':
main(sys.argv)
if __name__ == "__main__":
main(sys.argv)
121 changes: 66 additions & 55 deletions llvm/lib/Analysis/models/gen-regalloc-priority-test-model.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import os
import sys
import tensorflow as tf
POLICY_DECISION_LABEL = 'priority'

POLICY_DECISION_LABEL = "priority"
POLICY_OUTPUT_SPEC = """
[
{
Expand All @@ -23,73 +24,83 @@
}
]
"""
PER_LIVEINTERVAL_INT64_FEATURE_LIST = [
'li_size', 'stage'
]
PER_LIVEINTERVAL_FLOAT32_FEATURE_LIST = ['weight'
]
PER_LIVEINTERVAL_FEATURE_LIST = PER_LIVEINTERVAL_FLOAT32_FEATURE_LIST + \
PER_LIVEINTERVAL_INT64_FEATURE_LIST
CONTEXT_FEATURE_LIST = ('discount', 'reward', 'step_type')
PER_LIVEINTERVAL_INT64_FEATURE_LIST = ["li_size", "stage"]
PER_LIVEINTERVAL_FLOAT32_FEATURE_LIST = ["weight"]
PER_LIVEINTERVAL_FEATURE_LIST = (
PER_LIVEINTERVAL_FLOAT32_FEATURE_LIST + PER_LIVEINTERVAL_INT64_FEATURE_LIST
)
CONTEXT_FEATURE_LIST = ("discount", "reward", "step_type")


def get_input_signature():
"""Returns (time_step_spec, action_spec) for LLVM register allocation."""
inputs = dict(
(key, tf.TensorSpec(dtype=tf.int64, shape=(), name=key))
for key in PER_LIVEINTERVAL_INT64_FEATURE_LIST)
inputs.update(
dict((key,
tf.TensorSpec(dtype=tf.float32, shape=(), name=key))
for key in PER_LIVEINTERVAL_FLOAT32_FEATURE_LIST))
inputs.update(
dict((key, tf.TensorSpec(dtype=tf.float32, shape=(), name=key))
for key in ['discount', 'reward']))
inputs.update(
dict((key, tf.TensorSpec(dtype=tf.int32, shape=(), name=key))
for key in ['step_type']))
return inputs
"""Returns (time_step_spec, action_spec) for LLVM register allocation."""
inputs = dict(
(key, tf.TensorSpec(dtype=tf.int64, shape=(), name=key))
for key in PER_LIVEINTERVAL_INT64_FEATURE_LIST
)
inputs.update(
dict(
(key, tf.TensorSpec(dtype=tf.float32, shape=(), name=key))
for key in PER_LIVEINTERVAL_FLOAT32_FEATURE_LIST
)
)
inputs.update(
dict(
(key, tf.TensorSpec(dtype=tf.float32, shape=(), name=key))
for key in ["discount", "reward"]
)
)
inputs.update(
dict(
(key, tf.TensorSpec(dtype=tf.int32, shape=(), name=key))
for key in ["step_type"]
)
)
return inputs


def get_output_spec_path(path):
return os.path.join(path, 'output_spec.json')
return os.path.join(path, "output_spec.json")


def build_mock_model(path):
"""Build and save the mock model with the given signature."""
module = tf.Module()
# We have to set this useless variable in order for the TF C API to correctly
# intake it
module.var = tf.Variable(0, dtype=tf.float32)
"""Build and save the mock model with the given signature."""
module = tf.Module()
# We have to set this useless variable in order for the TF C API to correctly
# intake it
module.var = tf.Variable(0, dtype=tf.float32)

def action(*inputs):
s1 = tf.reduce_sum(
[
tf.cast(inputs[0][key], tf.float32)
for key in PER_LIVEINTERVAL_FEATURE_LIST
],
axis=0,
)
s2 = tf.reduce_sum(
[tf.cast(inputs[0][key], tf.float32) for key in CONTEXT_FEATURE_LIST]
)
# Add a large number so s won't be 0.
s = s1 + s2
result = s + module.var
return {POLICY_DECISION_LABEL: result}

def action(*inputs):
s1 = tf.reduce_sum([
tf.cast(inputs[0][key], tf.float32) for key in PER_LIVEINTERVAL_FEATURE_LIST
],
axis=0)
s2 = tf.reduce_sum(
[tf.cast(inputs[0][key], tf.float32) for key in CONTEXT_FEATURE_LIST])
# Add a large number so s won't be 0.
s = s1 + s2
result = s + module.var
return {POLICY_DECISION_LABEL: result}
module.action = tf.function()(action)
action = {
'action': module.action.get_concrete_function(get_input_signature())
}
module.action = tf.function()(action)
action = {"action": module.action.get_concrete_function(get_input_signature())}

tf.saved_model.save(module, path, signatures=action)
output_spec_path = get_output_spec_path(path)
with open(output_spec_path, 'w') as f:
print(f'Writing output spec to {output_spec_path}.')
f.write(POLICY_OUTPUT_SPEC)
tf.saved_model.save(module, path, signatures=action)
output_spec_path = get_output_spec_path(path)
with open(output_spec_path, "w") as f:
print(f"Writing output spec to {output_spec_path}.")
f.write(POLICY_OUTPUT_SPEC)


def main(argv):
assert len(argv) == 2
model_path = argv[1]
build_mock_model(model_path)
assert len(argv) == 2
model_path = argv[1]
build_mock_model(model_path)


if __name__ == '__main__':
main(sys.argv)
if __name__ == "__main__":
main(sys.argv)
128 changes: 68 additions & 60 deletions llvm/lib/Analysis/models/interactive_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,68 +20,76 @@
from typing import Callable, List, Union


def send(f: io.BufferedWriter, value: Union[int, float],
spec: log_reader.TensorSpec):
"""Send the `value` - currently just a scalar - formatted as per `spec`."""
def send(f: io.BufferedWriter, value: Union[int, float], spec: log_reader.TensorSpec):
"""Send the `value` - currently just a scalar - formatted as per `spec`."""

# just int64 for now
assert (spec.element_type == ctypes.c_int64)
to_send = ctypes.c_int64(int(value))
assert f.write(bytes(to_send)) == ctypes.sizeof(
spec.element_type) * math.prod(spec.shape)
f.flush()
# just int64 for now
assert spec.element_type == ctypes.c_int64
to_send = ctypes.c_int64(int(value))
assert f.write(bytes(to_send)) == ctypes.sizeof(spec.element_type) * math.prod(
spec.shape
)
f.flush()


def run_interactive(temp_rootname: str,
make_response: Callable[[List[log_reader.TensorValue]],
Union[int, float]],
process_and_args: List[str]):
"""Host the compiler.
Args:
temp_rootname: the base file name from which to construct the 2 pipes for
communicating with the compiler.
make_response: a function that, given the current tensor values, provides a
response.
process_and_args: the full commandline for the compiler. It it assumed it
contains a flag poiting to `temp_rootname` so that the InteractiveModeRunner
would attempt communication on the same pair as this function opens.
def run_interactive(
temp_rootname: str,
make_response: Callable[[List[log_reader.TensorValue]], Union[int, float]],
process_and_args: List[str],
):
"""Host the compiler.
Args:
temp_rootname: the base file name from which to construct the 2 pipes for
communicating with the compiler.
make_response: a function that, given the current tensor values, provides a
response.
process_and_args: the full commandline for the compiler. It it assumed it
contains a flag poiting to `temp_rootname` so that the InteractiveModeRunner
would attempt communication on the same pair as this function opens.
This function sets up the communication with the compiler - via 2 files named
`temp_rootname`.in and `temp_rootname`.out - prints out the received features,
and sends back to the compiler an advice (which it gets from `make_response`).
It's used for testing, and also to showcase how to set up communication in an
interactive ML ("gym") environment.
"""
to_compiler = temp_rootname + ".in"
from_compiler = temp_rootname + ".out"
try:
os.mkfifo(to_compiler, 0o666)
os.mkfifo(from_compiler, 0o666)
compiler_proc = subprocess.Popen(
process_and_args, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL)
with io.BufferedWriter(io.FileIO(to_compiler, 'wb')) as tc:
with io.BufferedReader(io.FileIO(from_compiler, 'rb')) as fc:
tensor_specs, _, advice_spec = log_reader.read_header(fc)
context = None
while compiler_proc.poll() is None:
next_event = fc.readline()
if not next_event:
break
last_context, observation_id, features, _ = log_reader.read_one_observation(
context, next_event, fc, tensor_specs, None)
if last_context != context:
print(f'context: {last_context}')
context = last_context
print(f'observation: {observation_id}')
tensor_values = []
for fv in features:
log_reader.pretty_print_tensor_value(fv)
tensor_values.append(fv)
send(tc, make_response(tensor_values), advice_spec)
_, err = compiler_proc.communicate()
print(err.decode('utf-8'))
compiler_proc.wait()
This function sets up the communication with the compiler - via 2 files named
`temp_rootname`.in and `temp_rootname`.out - prints out the received features,
and sends back to the compiler an advice (which it gets from `make_response`).
It's used for testing, and also to showcase how to set up communication in an
interactive ML ("gym") environment.
"""
to_compiler = temp_rootname + ".in"
from_compiler = temp_rootname + ".out"
try:
os.mkfifo(to_compiler, 0o666)
os.mkfifo(from_compiler, 0o666)
compiler_proc = subprocess.Popen(
process_and_args, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL
)
with io.BufferedWriter(io.FileIO(to_compiler, "wb")) as tc:
with io.BufferedReader(io.FileIO(from_compiler, "rb")) as fc:
tensor_specs, _, advice_spec = log_reader.read_header(fc)
context = None
while compiler_proc.poll() is None:
next_event = fc.readline()
if not next_event:
break
(
last_context,
observation_id,
features,
_,
) = log_reader.read_one_observation(
context, next_event, fc, tensor_specs, None
)
if last_context != context:
print(f"context: {last_context}")
context = last_context
print(f"observation: {observation_id}")
tensor_values = []
for fv in features:
log_reader.pretty_print_tensor_value(fv)
tensor_values.append(fv)
send(tc, make_response(tensor_values), advice_spec)
_, err = compiler_proc.communicate()
print(err.decode("utf-8"))
compiler_proc.wait()

finally:
os.unlink(to_compiler)
os.unlink(from_compiler)
finally:
os.unlink(to_compiler)
os.unlink(from_compiler)
198 changes: 100 additions & 98 deletions llvm/lib/Analysis/models/log_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,128 +11,130 @@
from typing import List, Optional

_element_types = {
'float': ctypes.c_float,
'double': ctypes.c_double,
'int8_t': ctypes.c_int8,
'uint8_t': ctypes.c_uint8,
'int16_t': ctypes.c_int16,
'uint16_t': ctypes.c_uint16,
'int32_t': ctypes.c_int32,
'uint32_t': ctypes.c_uint32,
'int64_t': ctypes.c_int64,
'uint64_t': ctypes.c_uint64
"float": ctypes.c_float,
"double": ctypes.c_double,
"int8_t": ctypes.c_int8,
"uint8_t": ctypes.c_uint8,
"int16_t": ctypes.c_int16,
"uint16_t": ctypes.c_uint16,
"int32_t": ctypes.c_int32,
"uint32_t": ctypes.c_uint32,
"int64_t": ctypes.c_int64,
"uint64_t": ctypes.c_uint64,
}


@dataclasses.dataclass(frozen=True)
class TensorSpec:
name: str
port: int
shape: List[int]
element_type: type

@staticmethod
def from_dict(d: dict):
name = d['name']
port = d['port']
shape = [int(e) for e in d['shape']]
element_type_str = d['type']
if element_type_str not in _element_types:
raise ValueError(f'uknown type: {element_type_str}')
return TensorSpec(
name=name,
port=port,
shape=shape,
element_type=_element_types[element_type_str])
name: str
port: int
shape: List[int]
element_type: type

@staticmethod
def from_dict(d: dict):
name = d["name"]
port = d["port"]
shape = [int(e) for e in d["shape"]]
element_type_str = d["type"]
if element_type_str not in _element_types:
raise ValueError(f"uknown type: {element_type_str}")
return TensorSpec(
name=name,
port=port,
shape=shape,
element_type=_element_types[element_type_str],
)


class TensorValue:
def __init__(self, spec: TensorSpec, buffer: bytes):
self._spec = spec
self._buffer = buffer
self._view = ctypes.cast(self._buffer, ctypes.POINTER(self._spec.element_type))
self._len = math.prod(self._spec.shape)

def __init__(self, spec: TensorSpec, buffer: bytes):
self._spec = spec
self._buffer = buffer
self._view = ctypes.cast(self._buffer,
ctypes.POINTER(self._spec.element_type))
self._len = math.prod(self._spec.shape)
def spec(self) -> TensorSpec:
return self._spec

def spec(self) -> TensorSpec:
return self._spec
def __len__(self) -> int:
return self._len

def __len__(self) -> int:
return self._len

def __getitem__(self, index):
if index < 0 or index >= self._len:
raise IndexError(f'Index {index} out of range [0..{self._len})')
return self._view[index]
def __getitem__(self, index):
if index < 0 or index >= self._len:
raise IndexError(f"Index {index} out of range [0..{self._len})")
return self._view[index]


def read_tensor(fs: io.BufferedReader, ts: TensorSpec) -> TensorValue:
size = math.prod(ts.shape) * ctypes.sizeof(ts.element_type)
data = fs.read(size)
return TensorValue(ts, data)
size = math.prod(ts.shape) * ctypes.sizeof(ts.element_type)
data = fs.read(size)
return TensorValue(ts, data)


def pretty_print_tensor_value(tv: TensorValue):
print(f'{tv.spec().name}: {",".join([str(v) for v in tv])}')
print(f'{tv.spec().name}: {",".join([str(v) for v in tv])}')


def read_header(f: io.BufferedReader):
header = json.loads(f.readline())
tensor_specs = [TensorSpec.from_dict(ts) for ts in header['features']]
score_spec = TensorSpec.from_dict(
header['score']) if 'score' in header else None
advice_spec = TensorSpec.from_dict(
header['advice']) if 'advice' in header else None
return tensor_specs, score_spec, advice_spec


def read_one_observation(context: Optional[str], event_str: str,
f: io.BufferedReader, tensor_specs: List[TensorSpec],
score_spec: Optional[TensorSpec]):
event = json.loads(event_str)
if 'context' in event:
context = event['context']
event = json.loads(f.readline())
observation_id = int(event['observation'])
features = []
for ts in tensor_specs:
features.append(read_tensor(f, ts))
f.readline()
score = None
if score_spec is not None:
score_header = json.loads(f.readline())
assert int(score_header['outcome']) == observation_id
score = read_tensor(f, score_spec)
header = json.loads(f.readline())
tensor_specs = [TensorSpec.from_dict(ts) for ts in header["features"]]
score_spec = TensorSpec.from_dict(header["score"]) if "score" in header else None
advice_spec = TensorSpec.from_dict(header["advice"]) if "advice" in header else None
return tensor_specs, score_spec, advice_spec


def read_one_observation(
context: Optional[str],
event_str: str,
f: io.BufferedReader,
tensor_specs: List[TensorSpec],
score_spec: Optional[TensorSpec],
):
event = json.loads(event_str)
if "context" in event:
context = event["context"]
event = json.loads(f.readline())
observation_id = int(event["observation"])
features = []
for ts in tensor_specs:
features.append(read_tensor(f, ts))
f.readline()
return context, observation_id, features, score
score = None
if score_spec is not None:
score_header = json.loads(f.readline())
assert int(score_header["outcome"]) == observation_id
score = read_tensor(f, score_spec)
f.readline()
return context, observation_id, features, score


def read_stream(fname: str):
with io.BufferedReader(io.FileIO(fname, 'rb')) as f:
tensor_specs, score_spec, _ = read_header(f)
context = None
while True:
event_str = f.readline()
if not event_str:
break
context, observation_id, features, score = read_one_observation(
context, event_str, f, tensor_specs, score_spec)
yield context, observation_id, features, score
with io.BufferedReader(io.FileIO(fname, "rb")) as f:
tensor_specs, score_spec, _ = read_header(f)
context = None
while True:
event_str = f.readline()
if not event_str:
break
context, observation_id, features, score = read_one_observation(
context, event_str, f, tensor_specs, score_spec
)
yield context, observation_id, features, score


def main(args):
last_context = None
for ctx, obs_id, features, score in read_stream(args[1]):
if last_context != ctx:
print(f'context: {ctx}')
last_context = ctx
print(f'observation: {obs_id}')
for fv in features:
pretty_print_tensor_value(fv)
if score:
pretty_print_tensor_value(score)


if __name__ == '__main__':
main(sys.argv)
last_context = None
for ctx, obs_id, features, score in read_stream(args[1]):
if last_context != ctx:
print(f"context: {ctx}")
last_context = ctx
print(f"observation: {obs_id}")
for fv in features:
pretty_print_tensor_value(fv)
if score:
pretty_print_tensor_value(score)


if __name__ == "__main__":
main(sys.argv)
42 changes: 21 additions & 21 deletions llvm/lib/Analysis/models/saved-model-to-tflite.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,24 @@


def main(argv):
assert len(argv) == 3
sm_dir = argv[1]
tfl_dir = argv[2]
tf.io.gfile.makedirs(tfl_dir)
tfl_path = os.path.join(tfl_dir, 'model.tflite')
converter = tf.lite.TFLiteConverter.from_saved_model(sm_dir)
converter.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS,
]
tfl_model = converter.convert()
with tf.io.gfile.GFile(tfl_path, 'wb') as f:
f.write(tfl_model)
json_file = 'output_spec.json'
src_json = os.path.join(sm_dir, json_file)
if tf.io.gfile.exists(src_json):
tf.io.gfile.copy(src_json,
os.path.join(tfl_dir, json_file))

if __name__ == '__main__':
main(sys.argv)
assert len(argv) == 3
sm_dir = argv[1]
tfl_dir = argv[2]
tf.io.gfile.makedirs(tfl_dir)
tfl_path = os.path.join(tfl_dir, "model.tflite")
converter = tf.lite.TFLiteConverter.from_saved_model(sm_dir)
converter.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS,
]
tfl_model = converter.convert()
with tf.io.gfile.GFile(tfl_path, "wb") as f:
f.write(tfl_model)

json_file = "output_spec.json"
src_json = os.path.join(sm_dir, json_file)
if tf.io.gfile.exists(src_json):
tf.io.gfile.copy(src_json, os.path.join(tfl_dir, json_file))


if __name__ == "__main__":
main(sys.argv)
2 changes: 1 addition & 1 deletion llvm/test/BugPoint/compile-custom.ll.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
# Currently any print-out from the custom tool is interpreted as a crash
# (i.e. test is still interesting)

print("Error: " + ' '.join(sys.argv[1:]))
print("Error: " + " ".join(sys.argv[1:]))

sys.exit(1)
158 changes: 98 additions & 60 deletions llvm/test/CodeGen/AArch64/Atomics/generate-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
import textwrap
import enum
import os

"""
Generate the tests in llvm/test/CodeGen/AArch64/Atomics. Run from top level llvm-project.
"""

TRIPLES = [
'aarch64',
'aarch64_be',
"aarch64",
"aarch64_be",
]


Expand Down Expand Up @@ -117,28 +118,28 @@ class Feature(enum.Flag):
@property
def mattr(self):
if self == Feature.outline_atomics:
return '+outline-atomics'
return "+outline-atomics"
if self == Feature.v8_1a:
return '+v8.1a'
return "+v8.1a"
if self == Feature.rcpc3:
return '+lse2,+rcpc3'
return "+lse2,+rcpc3"
if self == Feature.lse2_lse128:
return '+lse2,+lse128'
return '+' + self.name
return "+lse2,+lse128"
return "+" + self.name


ATOMICRMW_OPS = [
'xchg',
'add',
'sub',
'and',
'nand',
'or',
'xor',
'max',
'min',
'umax',
'umin',
"xchg",
"add",
"sub",
"and",
"nand",
"or",
"xor",
"max",
"min",
"umax",
"umin",
]


Expand All @@ -147,49 +148,58 @@ def all_atomicrmw(f):
for aligned in Aligned:
for ty in Type:
for ordering in ATOMICRMW_ORDERS:
name = f'atomicrmw_{op}_{ty}_{aligned}_{ordering}'
instr = 'atomicrmw'
name = f"atomicrmw_{op}_{ty}_{aligned}_{ordering}"
instr = "atomicrmw"
f.write(
textwrap.dedent(f'''
textwrap.dedent(
f"""
define dso_local {ty} @{name}(ptr %ptr, {ty} %value) {{
%r = {instr} {op} ptr %ptr, {ty} %value {ordering}, align {ty.align(aligned)}
ret {ty} %r
}}
'''))
"""
)
)


def all_load(f):
for aligned in Aligned:
for ty in Type:
for ordering in ATOMIC_LOAD_ORDERS:
for const in [False, True]:
name = f'load_atomic_{ty}_{aligned}_{ordering}'
instr = 'load atomic'
name = f"load_atomic_{ty}_{aligned}_{ordering}"
instr = "load atomic"
if const:
name += '_const'
arg = 'ptr readonly %ptr' if const else 'ptr %ptr'
name += "_const"
arg = "ptr readonly %ptr" if const else "ptr %ptr"
f.write(
textwrap.dedent(f'''
textwrap.dedent(
f"""
define dso_local {ty} @{name}({arg}) {{
%r = {instr} {ty}, ptr %ptr {ordering}, align {ty.align(aligned)}
ret {ty} %r
}}
'''))
"""
)
)


def all_store(f):
for aligned in Aligned:
for ty in Type:
for ordering in ATOMIC_STORE_ORDERS: # FIXME stores
name = f'store_atomic_{ty}_{aligned}_{ordering}'
instr = 'store atomic'
name = f"store_atomic_{ty}_{aligned}_{ordering}"
instr = "store atomic"
f.write(
textwrap.dedent(f'''
textwrap.dedent(
f"""
define dso_local void @{name}({ty} %value, ptr %ptr) {{
{instr} {ty} %value, ptr %ptr {ordering}, align {ty.align(aligned)}
ret void
}}
'''))
"""
)
)


def all_cmpxchg(f):
Expand All @@ -198,85 +208,113 @@ def all_cmpxchg(f):
for success_ordering in CMPXCHG_SUCCESS_ORDERS:
for failure_ordering in CMPXCHG_FAILURE_ORDERS:
for weak in [False, True]:
name = f'cmpxchg_{ty}_{aligned}_{success_ordering}_{failure_ordering}'
instr = 'cmpxchg'
name = f"cmpxchg_{ty}_{aligned}_{success_ordering}_{failure_ordering}"
instr = "cmpxchg"
if weak:
name += '_weak'
instr += ' weak'
name += "_weak"
instr += " weak"
f.write(
textwrap.dedent(f'''
textwrap.dedent(
f"""
define dso_local {ty} @{name}({ty} %expected, {ty} %new, ptr %ptr) {{
%pair = {instr} ptr %ptr, {ty} %expected, {ty} %new {success_ordering} {failure_ordering}, align {ty.align(aligned)}
%r = extractvalue {{ {ty}, i1 }} %pair, 0
ret {ty} %r
}}
'''))
"""
)
)


def all_fence(f):
for ordering in FENCE_ORDERS:
name = f'fence_{ordering}'
name = f"fence_{ordering}"
f.write(
textwrap.dedent(f'''
textwrap.dedent(
f"""
define dso_local void @{name}() {{
fence {ordering}
ret void
}}
'''))
"""
)
)


def header(f, triple, features, filter_args: str):
f.write('; NOTE: Assertions have been autogenerated by '
'utils/update_llc_test_checks.py UTC_ARGS: ')
f.write(
"; NOTE: Assertions have been autogenerated by "
"utils/update_llc_test_checks.py UTC_ARGS: "
)
f.write(filter_args)
f.write('\n')
f.write(f'; The base test file was generated by {__file__}\n')
f.write("\n")
f.write(f"; The base test file was generated by {__file__}\n")
for feat in features:
for OptFlag in ['-O0', '-O1']:
f.write(' '.join([
';', 'RUN:', 'llc', '%s', '-o', '-', '-verify-machineinstrs',
f'-mtriple={triple}', f'-mattr={feat.mattr}', OptFlag, '|',
'FileCheck', '%s', f'--check-prefixes=CHECK,{OptFlag}\n'
]))
for OptFlag in ["-O0", "-O1"]:
f.write(
" ".join(
[
";",
"RUN:",
"llc",
"%s",
"-o",
"-",
"-verify-machineinstrs",
f"-mtriple={triple}",
f"-mattr={feat.mattr}",
OptFlag,
"|",
"FileCheck",
"%s",
f"--check-prefixes=CHECK,{OptFlag}\n",
]
)
)


def write_lit_tests():
os.chdir('llvm/test/CodeGen/AArch64/Atomics/')
os.chdir("llvm/test/CodeGen/AArch64/Atomics/")
for triple in TRIPLES:
# Feature has no effect on fence, so keep it to one file.
with open(f'{triple}-fence.ll', 'w') as f:
with open(f"{triple}-fence.ll", "w") as f:
filter_args = r'--filter "^\s*(dmb)"'
header(f, triple, Feature, filter_args)
all_fence(f)

for feat in Feature:
with open(f'{triple}-atomicrmw-{feat.name}.ll', 'w') as f:
with open(f"{triple}-atomicrmw-{feat.name}.ll", "w") as f:
filter_args = r'--filter-out "\b(sp)\b" --filter "^\s*(ld[^r]|st[^r]|swp|cas|bl|add|and|eor|orn|orr|sub|mvn|sxt|cmp|ccmp|csel|dmb)"'
header(f, triple, [feat], filter_args)
all_atomicrmw(f)

with open(f'{triple}-cmpxchg-{feat.name}.ll', 'w') as f:
with open(f"{triple}-cmpxchg-{feat.name}.ll", "w") as f:
filter_args = r'--filter-out "\b(sp)\b" --filter "^\s*(ld[^r]|st[^r]|swp|cas|bl|add|and|eor|orn|orr|sub|mvn|sxt|cmp|ccmp|csel|dmb)"'
header(f, triple, [feat], filter_args)
all_cmpxchg(f)

with open(f'{triple}-atomic-load-{feat.name}.ll', 'w') as f:
with open(f"{triple}-atomic-load-{feat.name}.ll", "w") as f:
filter_args = r'--filter-out "\b(sp)\b" --filter "^\s*(ld|st[^r]|swp|cas|bl|add|and|eor|orn|orr|sub|mvn|sxt|cmp|ccmp|csel|dmb)"'
header(f, triple, [feat], filter_args)
all_load(f)

with open(f'{triple}-atomic-store-{feat.name}.ll', 'w') as f:
with open(f"{triple}-atomic-store-{feat.name}.ll", "w") as f:
filter_args = r'--filter-out "\b(sp)\b" --filter "^\s*(ld[^r]|st|swp|cas|bl|add|and|eor|orn|orr|sub|mvn|sxt|cmp|ccmp|csel|dmb)"'
header(f, triple, [feat], filter_args)
all_store(f)

if __name__ == '__main__':

if __name__ == "__main__":
write_lit_tests()

print(textwrap.dedent('''
print(
textwrap.dedent(
"""
Testcases written. To update checks run:
$ ./llvm/utils/update_llc_test_checks.py -u llvm/test/CodeGen/AArch64/Atomics/*.ll
Or in parallel:
$ parallel ./llvm/utils/update_llc_test_checks.py -u ::: llvm/test/CodeGen/AArch64/Atomics/*.ll
'''))
"""
)
)
35 changes: 17 additions & 18 deletions llvm/test/CodeGen/MLRegalloc/Inputs/interactive_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,24 @@


def main(args):
# this advisor just picks the first legal register to evict, which is
# identifiable by the "mask" feature
class Advisor:
to_return = False
# this advisor just picks the first legal register to evict, which is
# identifiable by the "mask" feature
class Advisor:
to_return = False

def advice(self, tensor_values: list[log_reader.TensorValue]):
for tv in tensor_values:
if tv.spec().name != 'mask':
continue
for i, v in enumerate(tv):
if v == 1:
return i
# i.e. invalid:
return -1
def advice(self, tensor_values: list[log_reader.TensorValue]):
for tv in tensor_values:
if tv.spec().name != "mask":
continue
for i, v in enumerate(tv):
if v == 1:
return i
# i.e. invalid:
return -1

a = Advisor()
interactive_host.run_interactive(args[0], a.advice, args[1:])

a = Advisor()
interactive_host.run_interactive(args[0], a.advice, args[1:])


if __name__ == '__main__':
main(sys.argv[1:])
if __name__ == "__main__":
main(sys.argv[1:])
93 changes: 47 additions & 46 deletions llvm/test/CodeGen/NVPTX/ld-st-addrrspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"half": "b16",
"<2 x half>": "b32",
"float": "f32",
"double": "f64"
"double": "f64",
}

llvm_type_to_ptx_reg = {
Expand All @@ -31,7 +31,7 @@
"half": "h",
"<2 x half>": "hh",
"float": "f",
"double": "fd"
"double": "fd",
}

addrspace_id = {
Expand All @@ -40,12 +40,12 @@
".shared": 3,
".const": 4,
".local": 5,
".param": 101
".param": 101,
}


def gen_load_tests():
load_template = """
load_template = """
define ${type} @${testname}(${type} addrspace(${asid})* %ptr) {
; CHECK: ${testname}
; CHECK_P32: ld${_volatile}${_volatile_as}.${ptx_type} %${ptx_reg}{{[0-9]+}}, [%r{{[0-9]+}}]
Expand All @@ -56,51 +56,52 @@ def gen_load_tests():
ret ${type} %a
}
"""
for op_type, volatile, space in product(
["i8", "i16", "i32", "i64", "half", "float", "double", "<2 x half>"],
[True, False], # volatile
["", ".shared", ".global", ".const", ".local", ".param"]):

# Volatile is only supported for global, shared and generic.
if volatile and not space in ["", ".global", ".shared"]:
continue

# Volatile is only supported for global, shared and generic.
# All other volatile accesses are done in generic AS.
if volatile and not space in ["", ".global", ".shared"]:
volatile_as = ""
else:
volatile_as = space

params = {
"type": op_type,
"volatile": "volatile" if volatile else "",
"_volatile": ".volatile" if volatile else "",
"_volatile_as": volatile_as,
"_space": space,
"ptx_reg": llvm_type_to_ptx_reg[op_type],
"ptx_type": llvm_type_to_ptx_type[op_type],
"asid": addrspace_id[space],
}

testname = \
Template("ld_${_volatile}${_space}.${ptx_type}").substitute(params)
params["testname"] = testname.replace(".", "_")

# LLVM does not accept "addrspacecast Type* addrspace(0) to Type*", so we
# need to avoid it for generic pointer tests.
if space:
generic_ptr_template = ("addrspacecast ${type} addrspace(${asid})* %ptr "
"to ${type}*")
else:
generic_ptr_template = "select i1 true, ${type}* %ptr, ${type}* %ptr"
params["generic_ptr"] = Template(generic_ptr_template).substitute(params)

print(Template(load_template).substitute(params))
for op_type, volatile, space in product(
["i8", "i16", "i32", "i64", "half", "float", "double", "<2 x half>"],
[True, False], # volatile
["", ".shared", ".global", ".const", ".local", ".param"],
):

# Volatile is only supported for global, shared and generic.
if volatile and not space in ["", ".global", ".shared"]:
continue

# Volatile is only supported for global, shared and generic.
# All other volatile accesses are done in generic AS.
if volatile and not space in ["", ".global", ".shared"]:
volatile_as = ""
else:
volatile_as = space

params = {
"type": op_type,
"volatile": "volatile" if volatile else "",
"_volatile": ".volatile" if volatile else "",
"_volatile_as": volatile_as,
"_space": space,
"ptx_reg": llvm_type_to_ptx_reg[op_type],
"ptx_type": llvm_type_to_ptx_type[op_type],
"asid": addrspace_id[space],
}

testname = Template("ld_${_volatile}${_space}.${ptx_type}").substitute(params)
params["testname"] = testname.replace(".", "_")

# LLVM does not accept "addrspacecast Type* addrspace(0) to Type*", so we
# need to avoid it for generic pointer tests.
if space:
generic_ptr_template = (
"addrspacecast ${type} addrspace(${asid})* %ptr " "to ${type}*"
)
else:
generic_ptr_template = "select i1 true, ${type}* %ptr, ${type}* %ptr"
params["generic_ptr"] = Template(generic_ptr_template).substitute(params)

print(Template(load_template).substitute(params))


def main():
gen_load_tests()
gen_load_tests()


main()
1,632 changes: 848 additions & 784 deletions llvm/test/CodeGen/NVPTX/surf-tex.py

Large diffs are not rendered by default.

1,283 changes: 686 additions & 597 deletions llvm/test/CodeGen/NVPTX/wmma.py

Large diffs are not rendered by default.

50 changes: 25 additions & 25 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-01.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,41 +70,41 @@
from __future__ import print_function

branch_blocks = 10
main_size = 0xffd8
main_size = 0xFFD8

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i32 *%stop, i32 %limit) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i32 *%stop, i32 %limit) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bstop%d = getelementptr i32, i32 *%%stop, i64 %d' % (i, i))
print(' %%bcur%d = load i32 , i32 *%%bstop%d' % (i, i))
print(' %%btest%d = icmp eq i32 %%limit, %%bcur%d' % (i, i))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bstop%d = getelementptr i32, i32 *%%stop, i64 %d" % (i, i))
print(" %%bcur%d = load i32 , i32 *%%bstop%d" % (i, i))
print(" %%btest%d = icmp eq i32 %%limit, %%bcur%d" % (i, i))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%astop%d = getelementptr i32, i32 *%%stop, i64 %d' % (i, i + 25))
print(' %%acur%d = load i32 , i32 *%%astop%d' % (i, i))
print(' %%atest%d = icmp eq i32 %%limit, %%acur%d' % (i, i))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%astop%d = getelementptr i32, i32 *%%stop, i64 %d" % (i, i + 25))
print(" %%acur%d = load i32 , i32 *%%astop%d" % (i, i))
print(" %%atest%d = icmp eq i32 %%limit, %%acur%d" % (i, i))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
32 changes: 16 additions & 16 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-02.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,25 +60,25 @@

blocks = 256 + 4

print('define void @f1(i8 *%base, i32 *%stop, i32 %limit) {')
print('entry:')
print(' br label %b0')
print('')
print("define void @f1(i8 *%base, i32 *%stop, i32 %limit) {")
print("entry:")
print(" br label %b0")
print("")

a, b = 1, 1
for i in range(blocks):
a, b = b, a + b
value = a % 256
next = 'b%d' % (i + 1) if i + 1 < blocks else 'end'
other = 'end' if 2 * i < blocks else 'b0'
print('b%d:' % i)
print(' store volatile i8 %d, i8 *%%base' % value)
print(' %%astop%d = getelementptr i32, i32 *%%stop, i64 %d' % (i, i))
print(' %%acur%d = load i32 , i32 *%%astop%d' % (i, i))
print(' %%atest%d = icmp eq i32 %%limit, %%acur%d' % (i, i))
print(' br i1 %%atest%d, label %%%s, label %%%s' % (i, other, next))
next = "b%d" % (i + 1) if i + 1 < blocks else "end"
other = "end" if 2 * i < blocks else "b0"
print("b%d:" % i)
print(" store volatile i8 %d, i8 *%%base" % value)
print(" %%astop%d = getelementptr i32, i32 *%%stop, i64 %d" % (i, i))
print(" %%acur%d = load i32 , i32 *%%astop%d" % (i, i))
print(" %%atest%d = icmp eq i32 %%limit, %%acur%d" % (i, i))
print(" br i1 %%atest%d, label %%%s, label %%%s" % (i, other, next))

print('')
print('%s:' % next)
print(' ret void')
print('}')
print("")
print("%s:" % next)
print(" ret void")
print("}")
54 changes: 27 additions & 27 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-03.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,43 +70,43 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc
main_size = 0xFFCC

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i8 *%stop, i32 %limit) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i8 *%stop, i32 %limit) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i))
print(' %%bcur%d = load i8 , i8 *%%bstop%d' % (i, i))
print(' %%bext%d = sext i8 %%bcur%d to i32' % (i, i))
print(' %%btest%d = icmp eq i32 %%limit, %%bext%d' % (i, i))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i))
print(" %%bcur%d = load i8 , i8 *%%bstop%d" % (i, i))
print(" %%bext%d = sext i8 %%bcur%d to i32" % (i, i))
print(" %%btest%d = icmp eq i32 %%limit, %%bext%d" % (i, i))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%astop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i + 25))
print(' %%acur%d = load i8 , i8 *%%astop%d' % (i, i))
print(' %%aext%d = sext i8 %%acur%d to i32' % (i, i))
print(' %%atest%d = icmp eq i32 %%limit, %%aext%d' % (i, i))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%astop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i + 25))
print(" %%acur%d = load i8 , i8 *%%astop%d" % (i, i))
print(" %%aext%d = sext i8 %%acur%d to i32" % (i, i))
print(" %%atest%d = icmp eq i32 %%limit, %%aext%d" % (i, i))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
54 changes: 27 additions & 27 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-04.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,43 +74,43 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc
main_size = 0xFFCC

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i8 *%stop, i64 %limit) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i8 *%stop, i64 %limit) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i))
print(' %%bcur%d = load i8 , i8 *%%bstop%d' % (i, i))
print(' %%bext%d = sext i8 %%bcur%d to i64' % (i, i))
print(' %%btest%d = icmp eq i64 %%limit, %%bext%d' % (i, i))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i))
print(" %%bcur%d = load i8 , i8 *%%bstop%d" % (i, i))
print(" %%bext%d = sext i8 %%bcur%d to i64" % (i, i))
print(" %%btest%d = icmp eq i64 %%limit, %%bext%d" % (i, i))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%astop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i + 25))
print(' %%acur%d = load i8 , i8 *%%astop%d' % (i, i))
print(' %%aext%d = sext i8 %%acur%d to i64' % (i, i))
print(' %%atest%d = icmp eq i64 %%limit, %%aext%d' % (i, i))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%astop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i + 25))
print(" %%acur%d = load i8 , i8 *%%astop%d" % (i, i))
print(" %%aext%d = sext i8 %%acur%d to i64" % (i, i))
print(" %%atest%d = icmp eq i64 %%limit, %%aext%d" % (i, i))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
50 changes: 25 additions & 25 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-05.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,41 +74,41 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc
main_size = 0xFFCC

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i8 *%stop) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i8 *%stop) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bcur%d = load i8 , i8 *%%stop' % i)
print(' %%bext%d = sext i8 %%bcur%d to i32' % (i, i))
print(' %%btest%d = icmp slt i32 %%bext%d, %d' % (i, i, i + 50))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bcur%d = load i8 , i8 *%%stop" % i)
print(" %%bext%d = sext i8 %%bcur%d to i32" % (i, i))
print(" %%btest%d = icmp slt i32 %%bext%d, %d" % (i, i, i + 50))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%acur%d = load i8 , i8 *%%stop' % i)
print(' %%aext%d = sext i8 %%acur%d to i32' % (i, i))
print(' %%atest%d = icmp slt i32 %%aext%d, %d' % (i, i, i + 100))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%acur%d = load i8 , i8 *%%stop" % i)
print(" %%aext%d = sext i8 %%acur%d to i32" % (i, i))
print(" %%atest%d = icmp slt i32 %%aext%d, %d" % (i, i, i + 100))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
50 changes: 25 additions & 25 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-06.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,41 +74,41 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc
main_size = 0xFFCC

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i8 *%stop) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i8 *%stop) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bcur%d = load i8 , i8 *%%stop' % i)
print(' %%bext%d = sext i8 %%bcur%d to i64' % (i, i))
print(' %%btest%d = icmp slt i64 %%bext%d, %d' % (i, i, i + 50))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bcur%d = load i8 , i8 *%%stop" % i)
print(" %%bext%d = sext i8 %%bcur%d to i64" % (i, i))
print(" %%btest%d = icmp slt i64 %%bext%d, %d" % (i, i, i + 50))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%acur%d = load i8 , i8 *%%stop' % i)
print(' %%aext%d = sext i8 %%acur%d to i64' % (i, i))
print(' %%atest%d = icmp slt i64 %%aext%d, %d' % (i, i, i + 100))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%acur%d = load i8 , i8 *%%stop" % i)
print(" %%aext%d = sext i8 %%acur%d to i64" % (i, i))
print(" %%atest%d = icmp slt i64 %%aext%d, %d" % (i, i, i + 100))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
46 changes: 25 additions & 21 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-07.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,36 +35,40 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffd8
main_size = 0xFFD8

print('define void @f1(i8 *%base, i32 *%counts) {')
print('entry:')
print("define void @f1(i8 *%base, i32 *%counts) {")
print("entry:")

for i in range(branch_blocks - 1, -1, -1):
print(' %%countptr%d = getelementptr i32, i32 *%%counts, i64 %d' % (i, i))
print(' %%initcount%d = load i32 , i32 *%%countptr%d' % (i, i))
print(' br label %%loop%d' % i)

print('loop%d:' % i)
block1 = 'entry' if i == branch_blocks - 1 else 'loop%d' % (i + 1)
block2 = 'loop0' if i == 0 else 'after%d' % (i - 1)
print((' %%count%d = phi i32 [ %%initcount%d, %%%s ],'
' [ %%nextcount%d, %%%s ]' % (i, i, block1, i, block2)))
print(" %%countptr%d = getelementptr i32, i32 *%%counts, i64 %d" % (i, i))
print(" %%initcount%d = load i32 , i32 *%%countptr%d" % (i, i))
print(" br label %%loop%d" % i)

print("loop%d:" % i)
block1 = "entry" if i == branch_blocks - 1 else "loop%d" % (i + 1)
block2 = "loop0" if i == 0 else "after%d" % (i - 1)
print(
(
" %%count%d = phi i32 [ %%initcount%d, %%%s ],"
" [ %%nextcount%d, %%%s ]" % (i, i, block1, i, block2)
)
)

a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%nextcount%d = add i32 %%count%d, -1' % (i, i))
print(' %%test%d = icmp ne i32 %%nextcount%d, 0' % (i, i))
print(' br i1 %%test%d, label %%loop%d, label %%after%d' % (i, i, i))
print('')
print('after%d:' % i)
print(" %%nextcount%d = add i32 %%count%d, -1" % (i, i))
print(" %%test%d = icmp ne i32 %%nextcount%d, 0" % (i, i))
print(" br i1 %%test%d, label %%loop%d, label %%after%d" % (i, i, i))
print("")
print("after%d:" % i)

print(' ret void')
print('}')
print(" ret void")
print("}")
46 changes: 25 additions & 21 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-08.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,36 +36,40 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffd8
main_size = 0xFFD8

print('define void @f1(i8 *%base, i64 *%counts) {')
print('entry:')
print("define void @f1(i8 *%base, i64 *%counts) {")
print("entry:")

for i in range(branch_blocks - 1, -1, -1):
print(' %%countptr%d = getelementptr i64, i64 *%%counts, i64 %d' % (i, i))
print(' %%initcount%d = load i64 , i64 *%%countptr%d' % (i, i))
print(' br label %%loop%d' % i)

print('loop%d:' % i)
block1 = 'entry' if i == branch_blocks - 1 else 'loop%d' % (i + 1)
block2 = 'loop0' if i == 0 else 'after%d' % (i - 1)
print((' %%count%d = phi i64 [ %%initcount%d, %%%s ],'
' [ %%nextcount%d, %%%s ]' % (i, i, block1, i, block2)))
print(" %%countptr%d = getelementptr i64, i64 *%%counts, i64 %d" % (i, i))
print(" %%initcount%d = load i64 , i64 *%%countptr%d" % (i, i))
print(" br label %%loop%d" % i)

print("loop%d:" % i)
block1 = "entry" if i == branch_blocks - 1 else "loop%d" % (i + 1)
block2 = "loop0" if i == 0 else "after%d" % (i - 1)
print(
(
" %%count%d = phi i64 [ %%initcount%d, %%%s ],"
" [ %%nextcount%d, %%%s ]" % (i, i, block1, i, block2)
)
)

a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%nextcount%d = add i64 %%count%d, -1' % (i, i))
print(' %%test%d = icmp ne i64 %%nextcount%d, 0' % (i, i))
print(' br i1 %%test%d, label %%loop%d, label %%after%d' % (i, i, i))
print('')
print('after%d:' % i)
print(" %%nextcount%d = add i64 %%count%d, -1" % (i, i))
print(" %%test%d = icmp ne i64 %%nextcount%d, 0" % (i, i))
print(" br i1 %%test%d, label %%loop%d, label %%after%d" % (i, i, i))
print("")
print("after%d:" % i)

print(' ret void')
print('}')
print(" ret void")
print("}")
54 changes: 27 additions & 27 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-09.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,43 +70,43 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc
main_size = 0xFFCC

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i8 *%stop, i32 %limit) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i8 *%stop, i32 %limit) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i))
print(' %%bcur%d = load i8 , i8 *%%bstop%d' % (i, i))
print(' %%bext%d = sext i8 %%bcur%d to i32' % (i, i))
print(' %%btest%d = icmp ult i32 %%limit, %%bext%d' % (i, i))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i))
print(" %%bcur%d = load i8 , i8 *%%bstop%d" % (i, i))
print(" %%bext%d = sext i8 %%bcur%d to i32" % (i, i))
print(" %%btest%d = icmp ult i32 %%limit, %%bext%d" % (i, i))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%astop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i + 25))
print(' %%acur%d = load i8 , i8 *%%astop%d' % (i, i))
print(' %%aext%d = sext i8 %%acur%d to i32' % (i, i))
print(' %%atest%d = icmp ult i32 %%limit, %%aext%d' % (i, i))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%astop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i + 25))
print(" %%acur%d = load i8 , i8 *%%astop%d" % (i, i))
print(" %%aext%d = sext i8 %%acur%d to i32" % (i, i))
print(" %%atest%d = icmp ult i32 %%limit, %%aext%d" % (i, i))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
54 changes: 27 additions & 27 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-10.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,43 +74,43 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc
main_size = 0xFFCC

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i8 *%stop, i64 %limit) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i8 *%stop, i64 %limit) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i))
print(' %%bcur%d = load i8 , i8 *%%bstop%d' % (i, i))
print(' %%bext%d = sext i8 %%bcur%d to i64' % (i, i))
print(' %%btest%d = icmp ult i64 %%limit, %%bext%d' % (i, i))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bstop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i))
print(" %%bcur%d = load i8 , i8 *%%bstop%d" % (i, i))
print(" %%bext%d = sext i8 %%bcur%d to i64" % (i, i))
print(" %%btest%d = icmp ult i64 %%limit, %%bext%d" % (i, i))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%astop%d = getelementptr i8, i8 *%%stop, i64 %d' % (i, i + 25))
print(' %%acur%d = load i8 , i8 *%%astop%d' % (i, i))
print(' %%aext%d = sext i8 %%acur%d to i64' % (i, i))
print(' %%atest%d = icmp ult i64 %%limit, %%aext%d' % (i, i))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%astop%d = getelementptr i8, i8 *%%stop, i64 %d" % (i, i + 25))
print(" %%acur%d = load i8 , i8 *%%astop%d" % (i, i))
print(" %%aext%d = sext i8 %%acur%d to i64" % (i, i))
print(" %%atest%d = icmp ult i64 %%limit, %%aext%d" % (i, i))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
54 changes: 27 additions & 27 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-11.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,43 +90,43 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffc6
main_size = 0xFFC6

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i32 *%stopa, i32 *%stopb) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i32 *%stopa, i32 *%stopb) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bcur%da = load i32 , i32 *%%stopa' % i)
print(' %%bcur%db = load i32 , i32 *%%stopb' % i)
print(' %%bsub%d = sub i32 %%bcur%da, %%bcur%db' % (i, i, i))
print(' %%btest%d = icmp ult i32 %%bsub%d, %d' % (i, i, i + 50))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bcur%da = load i32 , i32 *%%stopa" % i)
print(" %%bcur%db = load i32 , i32 *%%stopb" % i)
print(" %%bsub%d = sub i32 %%bcur%da, %%bcur%db" % (i, i, i))
print(" %%btest%d = icmp ult i32 %%bsub%d, %d" % (i, i, i + 50))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%acur%da = load i32 , i32 *%%stopa' % i)
print(' %%acur%db = load i32 , i32 *%%stopb' % i)
print(' %%asub%d = sub i32 %%acur%da, %%acur%db' % (i, i, i))
print(' %%atest%d = icmp ult i32 %%asub%d, %d' % (i, i, i + 100))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%acur%da = load i32 , i32 *%%stopa" % i)
print(" %%acur%db = load i32 , i32 *%%stopb" % i)
print(" %%asub%d = sub i32 %%acur%da, %%acur%db" % (i, i, i))
print(" %%atest%d = icmp ult i32 %%asub%d, %d" % (i, i, i + 100))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
54 changes: 27 additions & 27 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-12.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,43 +90,43 @@
from __future__ import print_function

branch_blocks = 8
main_size = 0xffb4
main_size = 0xFFB4

print('@global = global i32 0')
print("@global = global i32 0")

print('define void @f1(i8 *%base, i64 *%stopa, i64 *%stopb) {')
print('entry:')
print(' br label %before0')
print('')
print("define void @f1(i8 *%base, i64 *%stopa, i64 *%stopb) {")
print("entry:")
print(" br label %before0")
print("")

for i in range(branch_blocks):
next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
print('before%d:' % i)
print(' %%bcur%da = load i64 , i64 *%%stopa' % i)
print(' %%bcur%db = load i64 , i64 *%%stopb' % i)
print(' %%bsub%d = sub i64 %%bcur%da, %%bcur%db' % (i, i, i))
print(' %%btest%d = icmp ult i64 %%bsub%d, %d' % (i, i, i + 50))
print(' br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
print('')
next = "before%d" % (i + 1) if i + 1 < branch_blocks else "main"
print("before%d:" % i)
print(" %%bcur%da = load i64 , i64 *%%stopa" % i)
print(" %%bcur%db = load i64 , i64 *%%stopb" % i)
print(" %%bsub%d = sub i64 %%bcur%da, %%bcur%db" % (i, i, i))
print(" %%btest%d = icmp ult i64 %%bsub%d, %d" % (i, i, i + 50))
print(" br i1 %%btest%d, label %%after0, label %%%s" % (i, next))
print("")

print('%s:' % next)
print("%s:" % next)
a, b = 1, 1
for i in range(0, main_size, 6):
a, b = b, a + b
offset = 4096 + b % 500000
value = a % 256
print(' %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
print(' store volatile i8 %d, i8 *%%ptr%d' % (value, i))
print(" %%ptr%d = getelementptr i8, i8 *%%base, i64 %d" % (i, offset))
print(" store volatile i8 %d, i8 *%%ptr%d" % (value, i))

for i in range(branch_blocks):
print(' %%acur%da = load i64 , i64 *%%stopa' % i)
print(' %%acur%db = load i64 , i64 *%%stopb' % i)
print(' %%asub%d = sub i64 %%acur%da, %%acur%db' % (i, i, i))
print(' %%atest%d = icmp ult i64 %%asub%d, %d' % (i, i, i + 100))
print(' br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
print('')
print('after%d:' % i)
print(" %%acur%da = load i64 , i64 *%%stopa" % i)
print(" %%acur%db = load i64 , i64 *%%stopb" % i)
print(" %%asub%d = sub i64 %%acur%da, %%acur%db" % (i, i, i))
print(" %%atest%d = icmp ult i64 %%asub%d, %d" % (i, i, i + 100))
print(" br i1 %%atest%d, label %%main, label %%after%d" % (i, i))
print("")
print("after%d:" % i)

print(' %dummy = load volatile i32, i32 *@global')
print(' ret void')
print('}')
print(" %dummy = load volatile i32, i32 *@global")
print(" ret void")
print("}")
24 changes: 13 additions & 11 deletions llvm/test/CodeGen/SystemZ/Large/branch-range-13.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,20 @@

num = 11000

print('define void @f1() {')
print('entry:')
print(' br label %block')
print('')
print('block:')
print("define void @f1() {")
print("entry:")
print(" br label %block")
print("")
print("block:")

for i in range(num):
print(' tail call i64 asm "lang\\09$0,$2,$1\\0A", "=d,=*Q,d,*Q"(i32* elementtype(i32) undef, i32 undef, i32* elementtype(i32) undef)')
print(
' tail call i64 asm "lang\\09$0,$2,$1\\0A", "=d,=*Q,d,*Q"(i32* elementtype(i32) undef, i32 undef, i32* elementtype(i32) undef)'
)

print(' br label %block')
print(" br label %block")

print('')
print('exit:')
print(' ret void')
print('}')
print("")
print("exit:")
print(" ret void")
print("}")
24 changes: 12 additions & 12 deletions llvm/test/CodeGen/SystemZ/Large/spill-01.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,21 @@

count = 500

print('declare void @foo()')
print('')
print('define void @f1(i64 *%base0, i64 *%base1) {')
print("declare void @foo()")
print("")
print("define void @f1(i64 *%base0, i64 *%base1) {")

for i in range(count):
print(' %%ptr%d = getelementptr i64, i64 *%%base%d, i64 %d' % (i, i % 2, i / 2))
print(' %%val%d = load i64 , i64 *%%ptr%d' % (i, i))
print('')
print(" %%ptr%d = getelementptr i64, i64 *%%base%d, i64 %d" % (i, i % 2, i / 2))
print(" %%val%d = load i64 , i64 *%%ptr%d" % (i, i))
print("")

print(' call void @foo()')
print('')
print(" call void @foo()")
print("")

for i in range(count):
print(' store i64 %%val%d, i64 *%%ptr%d' % (i, i))
print(" store i64 %%val%d, i64 *%%ptr%d" % (i, i))

print('')
print(' ret void')
print('}')
print("")
print(" ret void")
print("}")
56 changes: 28 additions & 28 deletions llvm/test/CodeGen/SystemZ/Large/spill-02.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,53 +24,53 @@

args = int((8168 - 160) / 8 + (5 - 1))

print('declare i64 *@foo(i64 *%s)' % (', i64' * args))
print('declare void @bar(i64 *)')
print('')
print('define i64 @f1(i64 %foo) {')
print('entry:')
print("declare i64 *@foo(i64 *%s)" % (", i64" * args))
print("declare void @bar(i64 *)")
print("")
print("define i64 @f1(i64 %foo) {")
print("entry:")

# Make the allocation big, so that it goes at the top of the frame.
print(' %array = alloca [1000 x i64]')
print(' %area = getelementptr [1000 x i64], [1000 x i64] *%array, i64 0, i64 0')
print(' %%base = call i64 *@foo(i64 *%%area%s)' % (', i64 0' * args))
print('')
print(" %array = alloca [1000 x i64]")
print(" %area = getelementptr [1000 x i64], [1000 x i64] *%array, i64 0, i64 0")
print(" %%base = call i64 *@foo(i64 *%%area%s)" % (", i64 0" * args))
print("")

# Make sure all GPRs are used. One is needed for the stack pointer and
# another for %base, so we need 14 live values.
count = 14
for i in range(count):
print(' %%ptr%d = getelementptr i64, i64 *%%base, i64 %d' % (i, i / 2))
print(' %%val%d = load volatile i64 , i64 *%%ptr%d' % (i, i))
print('')
print(" %%ptr%d = getelementptr i64, i64 *%%base, i64 %d" % (i, i / 2))
print(" %%val%d = load volatile i64 , i64 *%%ptr%d" % (i, i))
print("")

# Encourage the register allocator to give preference to these %vals
# by using them several times.
for j in range(4):
for i in range(count):
print(' store volatile i64 %%val%d, i64 *%%ptr%d' % (i, i))
print('')
print(" store volatile i64 %%val%d, i64 *%%ptr%d" % (i, i))
print("")

# Copy the incoming argument, which we expect to be spilled, to the frame
# index for the alloca area. Also throw in a volatile store, so that this
# block cannot be reordered with the surrounding code.
print(' %cond = icmp eq i64 %val0, %val1')
print(' br i1 %cond, label %skip, label %fallthru')
print('')
print('fallthru:')
print(' store i64 %foo, i64 *%area')
print(' store volatile i64 %val0, i64 *%ptr0')
print(' br label %skip')
print('')
print('skip:')
print(" %cond = icmp eq i64 %val0, %val1")
print(" br i1 %cond, label %skip, label %fallthru")
print("")
print("fallthru:")
print(" store i64 %foo, i64 *%area")
print(" store volatile i64 %val0, i64 *%ptr0")
print(" br label %skip")
print("")
print("skip:")

# Use each %val a few more times to emphasise the point, and to make sure
# that they are live across the store of %foo.
for j in range(4):
for i in range(count):
print(' store volatile i64 %%val%d, i64 *%%ptr%d' % (i, i))
print('')
print(" store volatile i64 %%val%d, i64 *%%ptr%d" % (i, i))
print("")

print(' call void @bar(i64 *%area)')
print(' ret i64 0')
print('}')
print(" call void @bar(i64 *%area)")
print(" ret i64 0")
print("}")
269 changes: 134 additions & 135 deletions llvm/test/CodeGen/WebAssembly/multivalue-stackify.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,183 +36,182 @@


def get_num_defs(program):
num_defs = 0
for _, defs in program:
num_defs += len(defs)
return num_defs
num_defs = 0
for _, defs in program:
num_defs += len(defs)
return num_defs


def possible_ops(program):
program_defs = get_num_defs(program)
for num_defs in range(MAX_PROGRAM_DEFS - program_defs + 1):
for num_uses in range(MAX_OP_USES + 1):
if num_defs == 0 and num_uses == 0:
continue
for uses in product(range(program_defs), repeat=num_uses):
yield uses, tuple(program_defs + i for i in range(num_defs))
program_defs = get_num_defs(program)
for num_defs in range(MAX_PROGRAM_DEFS - program_defs + 1):
for num_uses in range(MAX_OP_USES + 1):
if num_defs == 0 and num_uses == 0:
continue
for uses in product(range(program_defs), repeat=num_uses):
yield uses, tuple(program_defs + i for i in range(num_defs))


def generate_programs():
queue = deque()
queue.append([])
program_id = 0
while True:
program = queue.popleft()
if len(program) == MAX_PROGRAM_OPS:
break
for op in possible_ops(program):
program_id += 1
new_program = program + [op]
queue.append(new_program)
yield program_id, new_program
queue = deque()
queue.append([])
program_id = 0
while True:
program = queue.popleft()
if len(program) == MAX_PROGRAM_OPS:
break
for op in possible_ops(program):
program_id += 1
new_program = program + [op]
queue.append(new_program)
yield program_id, new_program


def get_num_terminal_ops(program):
num_terminal_ops = 0
for _, defs in program:
if len(defs) == 0:
num_terminal_ops += 1
return num_terminal_ops
num_terminal_ops = 0
for _, defs in program:
if len(defs) == 0:
num_terminal_ops += 1
return num_terminal_ops


def get_max_uses(program):
num_uses = [0] * MAX_PROGRAM_DEFS
for uses, _ in program:
for u in uses:
num_uses[u] += 1
return max(num_uses)
num_uses = [0] * MAX_PROGRAM_DEFS
for uses, _ in program:
for u in uses:
num_uses[u] += 1
return max(num_uses)


def has_unused_op(program):
used = [False] * MAX_PROGRAM_DEFS
for uses, defs in program[::-1]:
if defs and all(not used[d] for d in defs):
return True
for u in uses:
used[u] = True
return False
used = [False] * MAX_PROGRAM_DEFS
for uses, defs in program[::-1]:
if defs and all(not used[d] for d in defs):
return True
for u in uses:
used[u] = True
return False


def has_multivalue_use(program):
is_multi = [False] * MAX_PROGRAM_DEFS
for uses, defs in program:
if any(is_multi[u] for u in uses):
return True
if len(defs) >= 2:
for d in defs:
is_multi[d] = True
return False
is_multi = [False] * MAX_PROGRAM_DEFS
for uses, defs in program:
if any(is_multi[u] for u in uses):
return True
if len(defs) >= 2:
for d in defs:
is_multi[d] = True
return False


def has_mvp_use(program):
is_mvp = [False] * MAX_PROGRAM_DEFS
for uses, defs in program:
if uses and all(is_mvp[u] for u in uses):
return True
if len(defs) <= 1:
if any(is_mvp[u] for u in uses):
return True
for d in defs:
is_mvp[d] = True
return False
is_mvp = [False] * MAX_PROGRAM_DEFS
for uses, defs in program:
if uses and all(is_mvp[u] for u in uses):
return True
if len(defs) <= 1:
if any(is_mvp[u] for u in uses):
return True
for d in defs:
is_mvp[d] = True
return False


def is_interesting(program):
# Allow only multivalue single-op programs
if len(program) == 1:
return len(program[0][1]) > 1
# Allow only multivalue single-op programs
if len(program) == 1:
return len(program[0][1]) > 1

# Reject programs where the last two instructions are identical
if len(program) >= 2 and program[-1][0] == program[-2][0]:
return False
# Reject programs where the last two instructions are identical
if len(program) >= 2 and program[-1][0] == program[-2][0]:
return False

# Reject programs with too many ops that don't produce values
if get_num_terminal_ops(program) > 2:
return False
# Reject programs with too many ops that don't produce values
if get_num_terminal_ops(program) > 2:
return False

# The third use of a value is no more interesting than the second
if get_max_uses(program) >= 3:
return False
# The third use of a value is no more interesting than the second
if get_max_uses(program) >= 3:
return False

# Reject nontrivial programs that have unused instructions
if has_unused_op(program):
return False
# Reject nontrivial programs that have unused instructions
if has_unused_op(program):
return False

# Reject programs that have boring MVP uses of MVP defs
if has_mvp_use(program):
return False
# Reject programs that have boring MVP uses of MVP defs
if has_mvp_use(program):
return False

# Otherwise if it has multivalue usage it is interesting
return has_multivalue_use(program)
# Otherwise if it has multivalue usage it is interesting
return has_multivalue_use(program)


def make_llvm_type(num_defs):
if num_defs == 0:
return 'void'
else:
return '{' + ', '.join(['i32'] * num_defs) + '}'
if num_defs == 0:
return "void"
else:
return "{" + ", ".join(["i32"] * num_defs) + "}"


def make_llvm_op_name(num_uses, num_defs):
return f'op_{num_uses}_to_{num_defs}'
return f"op_{num_uses}_to_{num_defs}"


def make_llvm_args(first_use, num_uses):
return ', '.join([f'i32 %t{first_use + i}' for i in range(num_uses)])
return ", ".join([f"i32 %t{first_use + i}" for i in range(num_uses)])


def print_llvm_program(program, name):
tmp = 0
def_data = []
print(f'define void @{name}() {{')
for uses, defs in program:
first_arg = tmp
# Extract operands
for use in uses:
ret_type, var, idx = def_data[use]
print(f' %t{tmp} = extractvalue {ret_type} %t{var}, {idx}')
tmp += 1
# Print instruction
assignment = ''
if len(defs) > 0:
assignment = f'%t{tmp} = '
result_var = tmp
tmp += 1
ret_type = make_llvm_type(len(defs))
op_name = make_llvm_op_name(len(uses), len(defs))
args = make_llvm_args(first_arg, len(uses))
print(f' {assignment}call {ret_type} @{op_name}({args})')
# Update def_data
for i in range(len(defs)):
def_data.append((ret_type, result_var, i))
print(' ret void')
print('}')
tmp = 0
def_data = []
print(f"define void @{name}() {{")
for uses, defs in program:
first_arg = tmp
# Extract operands
for use in uses:
ret_type, var, idx = def_data[use]
print(f" %t{tmp} = extractvalue {ret_type} %t{var}, {idx}")
tmp += 1
# Print instruction
assignment = ""
if len(defs) > 0:
assignment = f"%t{tmp} = "
result_var = tmp
tmp += 1
ret_type = make_llvm_type(len(defs))
op_name = make_llvm_op_name(len(uses), len(defs))
args = make_llvm_args(first_arg, len(uses))
print(f" {assignment}call {ret_type} @{op_name}({args})")
# Update def_data
for i in range(len(defs)):
def_data.append((ret_type, result_var, i))
print(" ret void")
print("}")


def print_header():
print('; NOTE: Test functions have been generated by multivalue-stackify.py.')
print()
print('; RUN: llc < %s -verify-machineinstrs -mattr=+multivalue',
'| FileCheck %s')
print()
print('; Test that the multivalue stackification works')
print()
print('target triple = "wasm32-unknown-unknown"')
print()
for num_uses in range(MAX_OP_USES + 1):
for num_defs in range(MAX_PROGRAM_DEFS + 1):
if num_uses == 0 and num_defs == 0:
continue
ret_type = make_llvm_type(num_defs)
op_name = make_llvm_op_name(num_uses, num_defs)
args = make_llvm_args(0, num_uses)
print(f'declare {ret_type} @{op_name}({args})')
print()


if __name__ == '__main__':
print_header()
for i, program in generate_programs():
if is_interesting(program):
print_llvm_program(program, 'f' + str(i))
print()
print("; NOTE: Test functions have been generated by multivalue-stackify.py.")
print()
print("; RUN: llc < %s -verify-machineinstrs -mattr=+multivalue", "| FileCheck %s")
print()
print("; Test that the multivalue stackification works")
print()
print('target triple = "wasm32-unknown-unknown"')
print()
for num_uses in range(MAX_OP_USES + 1):
for num_defs in range(MAX_PROGRAM_DEFS + 1):
if num_uses == 0 and num_defs == 0:
continue
ret_type = make_llvm_type(num_defs)
op_name = make_llvm_op_name(num_uses, num_defs)
args = make_llvm_args(0, num_uses)
print(f"declare {ret_type} @{op_name}({args})")
print()


if __name__ == "__main__":
print_header()
for i, program in generate_programs():
if is_interesting(program):
print_llvm_program(program, "f" + str(i))
print()
7 changes: 5 additions & 2 deletions llvm/test/MC/COFF/bigobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
# CHECK-NEXT: }

for i in range(0, num_sections):
print(""" .section .bss,"bw",discard,_b%d
print(
""" .section .bss,"bw",discard,_b%d
.globl _b%d # @b%d
_b%d:
.byte 0 # 0x0
""" % (i, i, i, i))
"""
% (i, i, i, i)
)
18 changes: 9 additions & 9 deletions llvm/test/Other/opt-bisect-helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@

parser = argparse.ArgumentParser()

parser.add_argument('--start', type=int, default=0)
parser.add_argument('--end', type=int, default=(1 << 32))
parser.add_argument('--optcmd', default=("opt"))
parser.add_argument('--filecheckcmd', default=("FileCheck"))
parser.add_argument('--prefix', default=("CHECK-BISECT"))
parser.add_argument('--test', default=(""))
parser.add_argument("--start", type=int, default=0)
parser.add_argument("--end", type=int, default=(1 << 32))
parser.add_argument("--optcmd", default=("opt"))
parser.add_argument("--filecheckcmd", default=("FileCheck"))
parser.add_argument("--prefix", default=("CHECK-BISECT"))
parser.add_argument("--test", default=(""))

args = parser.parse_args()

Expand All @@ -24,9 +24,9 @@
opt_command = [args.optcmd, "-O2", "-opt-bisect-limit=%(count)s", "-S", args.test]
check_command = [args.filecheckcmd, args.test, "--check-prefix=%s" % args.prefix]
last = None
while start != end and start != end-1:
count = int(round(start + (end - start)/2))
cmd = [x % {'count':count} for x in opt_command]
while start != end and start != end - 1:
count = int(round(start + (end - start) / 2))
cmd = [x % {"count": count} for x in opt_command]
print("opt: " + str(cmd))
opt_result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
filecheck_result = subprocess.Popen(check_command, stdin=opt_result.stdout)
Expand Down
13 changes: 8 additions & 5 deletions llvm/test/TableGen/JSON-check.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
prefix_pos = line.index(prefix)
except ValueError:
continue
check_expr = line[prefix_pos + len(prefix):]
check_expr = line[prefix_pos + len(prefix) :]

try:
exception = None
result = eval(check_expr, {"data":data})
result = eval(check_expr, {"data": data})
except Exception:
result = False
exception = traceback.format_exc().splitlines()[-1]
Expand All @@ -34,13 +34,16 @@
sys.stderr.write(
"{file}:{line:d}: check threw exception: {expr}\n"
"{file}:{line:d}: exception was: {exception}\n".format(
file=testfile, line=lineno,
expr=check_expr, exception=exception))
file=testfile, line=lineno, expr=check_expr, exception=exception
)
)
fails += 1
elif not result:
sys.stderr.write(
"{file}:{line:d}: check returned False: {expr}\n".format(
file=testfile, line=lineno, expr=check_expr))
file=testfile, line=lineno, expr=check_expr
)
)
fails += 1
else:
passes += 1
Expand Down
23 changes: 11 additions & 12 deletions llvm/test/Transforms/Inline/ML/Inputs/interactive_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@


def main(args):
class Advisor:
to_return = False

class Advisor:
to_return = False
def advice(self, _):
# The adice will be a sequence of yes/no/yes/no/...
# see ../interactive-mode.ll
self.to_return = not self.to_return
return int(self.to_return)

def advice(self, _):
# The adice will be a sequence of yes/no/yes/no/...
# see ../interactive-mode.ll
self.to_return = not self.to_return
return int(self.to_return)
a = Advisor()
interactive_host.run_interactive(args[0], a.advice, args[1:])

a = Advisor()
interactive_host.run_interactive(args[0], a.advice, args[1:])


if __name__ == '__main__':
main(sys.argv[1:])
if __name__ == "__main__":
main(sys.argv[1:])
49 changes: 25 additions & 24 deletions llvm/test/Unit/lit.cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,52 +8,53 @@
import lit.formats

# name: The name of this test suite.
config.name = 'LLVM-Unit'
config.name = "LLVM-Unit"

# suffixes: A list of file extensions to treat as test files.
config.suffixes = []

# test_source_root: The root path where tests are located.
# test_exec_root: The root path where tests should be run.
config.test_exec_root = os.path.join(config.llvm_obj_root, 'unittests')
config.test_exec_root = os.path.join(config.llvm_obj_root, "unittests")
config.test_source_root = config.test_exec_root

# testFormat: The test format to use to interpret tests.
config.test_format = lit.formats.GoogleTest(config.llvm_build_mode, 'Tests')
config.test_format = lit.formats.GoogleTest(config.llvm_build_mode, "Tests")

# Propagate the temp directory. Windows requires this because it uses \Windows\
# if none of these are present.
if 'TMP' in os.environ:
config.environment['TMP'] = os.environ['TMP']
if 'TEMP' in os.environ:
config.environment['TEMP'] = os.environ['TEMP']
if "TMP" in os.environ:
config.environment["TMP"] = os.environ["TMP"]
if "TEMP" in os.environ:
config.environment["TEMP"] = os.environ["TEMP"]

# Propagate HOME as it can be used to override incorrect homedir in passwd
# that causes the tests to fail.
if 'HOME' in os.environ:
config.environment['HOME'] = os.environ['HOME']
if "HOME" in os.environ:
config.environment["HOME"] = os.environ["HOME"]

# Propagate sanitizer options.
for var in [
'ASAN_SYMBOLIZER_PATH',
'HWASAN_SYMBOLIZER_PATH',
'MSAN_SYMBOLIZER_PATH',
'TSAN_SYMBOLIZER_PATH',
'UBSAN_SYMBOLIZER_PATH',
'ASAN_OPTIONS',
'HWASAN_OPTIONS',
'MSAN_OPTIONS',
'TSAN_OPTIONS',
'UBSAN_OPTIONS',
"ASAN_SYMBOLIZER_PATH",
"HWASAN_SYMBOLIZER_PATH",
"MSAN_SYMBOLIZER_PATH",
"TSAN_SYMBOLIZER_PATH",
"UBSAN_SYMBOLIZER_PATH",
"ASAN_OPTIONS",
"HWASAN_OPTIONS",
"MSAN_OPTIONS",
"TSAN_OPTIONS",
"UBSAN_OPTIONS",
]:
if var in os.environ:
config.environment[var] = os.environ[var]

# Win32 seeks DLLs along %PATH%.
if sys.platform in ['win32', 'cygwin'] and os.path.isdir(config.shlibdir):
config.environment['PATH'] = os.path.pathsep.join((
config.shlibdir, config.environment['PATH']))
if sys.platform in ["win32", "cygwin"] and os.path.isdir(config.shlibdir):
config.environment["PATH"] = os.path.pathsep.join(
(config.shlibdir, config.environment["PATH"])
)

# Win32 may use %SYSTEMDRIVE% during file system shell operations, so propogate.
if sys.platform == 'win32' and 'SYSTEMDRIVE' in os.environ:
config.environment['SYSTEMDRIVE'] = os.environ['SYSTEMDRIVE']
if sys.platform == "win32" and "SYSTEMDRIVE" in os.environ:
config.environment["SYSTEMDRIVE"] = os.environ["SYSTEMDRIVE"]
Loading