|
| 1 | +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 2 | +# See https://llvm.org/LICENSE.txt for license information. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 4 | + |
| 5 | +from .circt import support, ir |
| 6 | +from .core import Value |
| 7 | + |
| 8 | + |
| 9 | +def _FromCirctValue(value: ir.Value) -> Value: |
| 10 | + type = support.type_to_pytype(value.type) |
| 11 | + from .rtg import rtg |
| 12 | + if isinstance(type, rtg.LabelType): |
| 13 | + from .labels import Label |
| 14 | + return Label(value) |
| 15 | + assert False, "Unsupported value" |
| 16 | + |
| 17 | + |
| 18 | +def wrap_opviews_with_values(dialect, module_name, excluded=[]): |
| 19 | + """ |
| 20 | + Wraps all of a dialect's OpView classes to have their create method return a |
| 21 | + Value instead of an OpView. |
| 22 | + """ |
| 23 | + |
| 24 | + import sys |
| 25 | + module = sys.modules[module_name] |
| 26 | + |
| 27 | + for attr in dir(dialect): |
| 28 | + cls = getattr(dialect, attr) |
| 29 | + |
| 30 | + if attr not in excluded and isinstance(cls, type) and issubclass( |
| 31 | + cls, ir.OpView): |
| 32 | + |
| 33 | + def specialize_create(cls): |
| 34 | + |
| 35 | + def create(*args, **kwargs): |
| 36 | + # If any of the arguments are 'pyrtg.Value', we need to convert them. |
| 37 | + def to_circt(arg): |
| 38 | + if isinstance(arg, (list, tuple)): |
| 39 | + return [to_circt(a) for a in arg] |
| 40 | + return arg |
| 41 | + |
| 42 | + args = [to_circt(arg) for arg in args] |
| 43 | + kwargs = {k: to_circt(v) for k, v in kwargs.items()} |
| 44 | + # Create the OpView. |
| 45 | + if hasattr(cls, "create"): |
| 46 | + created = cls.create(*args, **kwargs) |
| 47 | + else: |
| 48 | + created = cls(*args, **kwargs) |
| 49 | + if isinstance(created, support.NamedValueOpView): |
| 50 | + created = created.opview |
| 51 | + |
| 52 | + # Return the wrapped values, if any. |
| 53 | + converted_results = tuple( |
| 54 | + _FromCirctValue(res) for res in created.results) |
| 55 | + return converted_results[0] if len( |
| 56 | + converted_results) == 1 else created |
| 57 | + |
| 58 | + return create |
| 59 | + |
| 60 | + wrapped_class = specialize_create(cls) |
| 61 | + setattr(module, attr, wrapped_class) |
| 62 | + else: |
| 63 | + setattr(module, attr, cls) |
0 commit comments