Skip to content

Hw

hw

This is a stub of CIRCT’s hw dialect. Follows definitions as of CIRCT commit f8c7faec1e8447521a1ea9a0836b6923a132c79e.

See rationale for symbols. See external documentation.

ArrayElementCovT = TypeVar('ArrayElementCovT', bound=Attribute, covariant=True, default=Attribute) module-attribute

HW = Dialect('hw', [ArrayCreateOp, ArrayGetOp, BitcastOp, HWModuleExternOp, HWModuleOp, InstanceOp, OutputOp], [ArrayType, DirectionAttr, InnerRefAttr, InnerSymAttr, InnerSymPropertiesAttr, ModulePort, ModuleType, ParamDeclAttr]) module-attribute

InnerSymTarget dataclass

The target of an inner symbol, the entity the symbol is a handle for.

A None operation defines an invalid target, which is returned from InnerSymbolTable.lookup() when no matching operation is found. An invalid target is falsey when constrained to bool.

Source code in xdsl/dialects/hw.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@dataclass
class InnerSymTarget:
    """The target of an inner symbol, the entity the symbol is a handle for.

    A None operation defines an invalid target, which is returned from InnerSymbolTable.lookup()
    when no matching operation is found. An invalid target is falsey when constrained to bool.
    """

    op: Operation | None = None
    field_id: int = 0
    port_idx: int | None = None

    def __bool__(self):
        return self.op is not None

    def is_port(self) -> bool:
        return self.port_idx is not None

    def is_field(self) -> bool:
        return self.field_id != 0

    def is_op_only(self) -> bool:
        return not self.is_field() and not self.is_port()

    @classmethod
    def get_target_for_subfield(
        cls, base: InnerSymTarget, field_id: int
    ) -> InnerSymTarget:
        """
        Return a target to the specified field within the given base.
        `field_id` is relative to the specified base target.
        """
        return cls(base.op, base.field_id + field_id, base.port_idx)

op: Operation | None = None class-attribute instance-attribute

field_id: int = 0 class-attribute instance-attribute

port_idx: int | None = None class-attribute instance-attribute

__init__(op: Operation | None = None, field_id: int = 0, port_idx: int | None = None) -> None

__bool__()

Source code in xdsl/dialects/hw.py
89
90
def __bool__(self):
    return self.op is not None

is_port() -> bool

Source code in xdsl/dialects/hw.py
92
93
def is_port(self) -> bool:
    return self.port_idx is not None

is_field() -> bool

Source code in xdsl/dialects/hw.py
95
96
def is_field(self) -> bool:
    return self.field_id != 0

is_op_only() -> bool

Source code in xdsl/dialects/hw.py
98
99
def is_op_only(self) -> bool:
    return not self.is_field() and not self.is_port()

get_target_for_subfield(base: InnerSymTarget, field_id: int) -> InnerSymTarget classmethod

Return a target to the specified field within the given base. field_id is relative to the specified base target.

Source code in xdsl/dialects/hw.py
101
102
103
104
105
106
107
108
109
@classmethod
def get_target_for_subfield(
    cls, base: InnerSymTarget, field_id: int
) -> InnerSymTarget:
    """
    Return a target to the specified field within the given base.
    `field_id` is relative to the specified base target.
    """
    return cls(base.op, base.field_id + field_id, base.port_idx)

InnerRefAttr

Bases: ParametrizedAttribute

This works like a symbol reference, but to a name inside a module.

Source code in xdsl/dialects/hw.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
@irdl_attr_definition
class InnerRefAttr(ParametrizedAttribute):
    """This works like a symbol reference, but to a name inside a module."""

    name = "hw.innerNameRef"
    module_ref: FlatSymbolRefAttr
    # NB. upstream defines as “name” which clashes with Attribute.name
    sym_name: StringAttr

    def __init__(self, module: str | StringAttr, name: str | StringAttr) -> None:
        if isinstance(module, str):
            module = StringAttr(module)
        if isinstance(name, str):
            name = StringAttr(name)
        super().__init__(SymbolRefAttr(module), name)

    @classmethod
    def get_from_operation(
        cls, op: Operation, sym_name: StringAttr, module_name: StringAttr
    ) -> InnerRefAttr:
        """Get the InnerRefAttr for an operation and add the sym on it."""
        # NB: declared upstream, but no implementation to be found
        raise NotImplementedError

    def get_module(self) -> StringAttr:
        """Return the name of the referenced module."""
        return self.module_ref.root_reference

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
        parser.parse_punctuation("<")
        symbol_ref = parser.parse_attribute()
        parser.parse_punctuation(">")
        if (
            not isinstance(symbol_ref, SymbolRefAttr)
            or len(symbol_ref.nested_references) != 1
        ):
            parser.raise_error("Expected a module and symbol reference")
        return [
            SymbolRefAttr(symbol_ref.root_reference),
            symbol_ref.nested_references.data[0],
        ]

    def print_parameters(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            printer.print_symbol_name(self.module_ref.root_reference.data)
            printer.print_string("::")
            printer.print_symbol_name(self.sym_name.data)

name = 'hw.innerNameRef' class-attribute instance-attribute

module_ref: FlatSymbolRefAttr instance-attribute

sym_name: StringAttr instance-attribute

__init__(module: str | StringAttr, name: str | StringAttr) -> None

Source code in xdsl/dialects/hw.py
121
122
123
124
125
126
def __init__(self, module: str | StringAttr, name: str | StringAttr) -> None:
    if isinstance(module, str):
        module = StringAttr(module)
    if isinstance(name, str):
        name = StringAttr(name)
    super().__init__(SymbolRefAttr(module), name)

get_from_operation(op: Operation, sym_name: StringAttr, module_name: StringAttr) -> InnerRefAttr classmethod

Get the InnerRefAttr for an operation and add the sym on it.

Source code in xdsl/dialects/hw.py
128
129
130
131
132
133
134
@classmethod
def get_from_operation(
    cls, op: Operation, sym_name: StringAttr, module_name: StringAttr
) -> InnerRefAttr:
    """Get the InnerRefAttr for an operation and add the sym on it."""
    # NB: declared upstream, but no implementation to be found
    raise NotImplementedError

get_module() -> StringAttr

Return the name of the referenced module.

Source code in xdsl/dialects/hw.py
136
137
138
def get_module(self) -> StringAttr:
    """Return the name of the referenced module."""
    return self.module_ref.root_reference

parse_parameters(parser: AttrParser) -> list[Attribute] classmethod

Source code in xdsl/dialects/hw.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@classmethod
def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
    parser.parse_punctuation("<")
    symbol_ref = parser.parse_attribute()
    parser.parse_punctuation(">")
    if (
        not isinstance(symbol_ref, SymbolRefAttr)
        or len(symbol_ref.nested_references) != 1
    ):
        parser.raise_error("Expected a module and symbol reference")
    return [
        SymbolRefAttr(symbol_ref.root_reference),
        symbol_ref.nested_references.data[0],
    ]

print_parameters(printer: Printer) -> None

Source code in xdsl/dialects/hw.py
155
156
157
158
159
def print_parameters(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        printer.print_symbol_name(self.module_ref.root_reference.data)
        printer.print_string("::")
        printer.print_symbol_name(self.sym_name.data)

InnerSymbolTableTrait dataclass

Bases: OpTrait

A trait for inner symbol table functionality on an operation.

Source code in xdsl/dialects/hw.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
@dataclass(frozen=True)
class InnerSymbolTableTrait(OpTrait):
    """A trait for inner symbol table functionality on an operation."""

    def verify(self, op: Operation):
        # Insist that ops with InnerSymbolTable's provide a Symbol, this is
        # essential to how InnerRef's work.
        if not op.has_trait(trait := SymbolOpInterface):
            raise VerifyException(
                f"Operation {op.name} must have trait {trait.__name__}"
            )

        # InnerSymbolTable's must be directly nested within an InnerRefNamespaceTrait (or similar),
        # however don’t test InnerRefNamespace’s symbol lookups
        parent = op.parent_op()
        if parent is None or not parent.has_trait(trait := InnerRefNamespaceLike):
            raise VerifyException(
                f"Operation {op.name} with trait {type(self).__name__} must have a parent with trait {trait.__name__}"
            )

__init__() -> None

verify(op: Operation)

Source code in xdsl/dialects/hw.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def verify(self, op: Operation):
    # Insist that ops with InnerSymbolTable's provide a Symbol, this is
    # essential to how InnerRef's work.
    if not op.has_trait(trait := SymbolOpInterface):
        raise VerifyException(
            f"Operation {op.name} must have trait {trait.__name__}"
        )

    # InnerSymbolTable's must be directly nested within an InnerRefNamespaceTrait (or similar),
    # however don’t test InnerRefNamespace’s symbol lookups
    parent = op.parent_op()
    if parent is None or not parent.has_trait(trait := InnerRefNamespaceLike):
        raise VerifyException(
            f"Operation {op.name} with trait {type(self).__name__} must have a parent with trait {trait.__name__}"
        )

InnerSymbolTable dataclass

A class for lookups in inner symbol tables. Called InnerSymbolTable in upstream (name clash with trait).

Source code in xdsl/dialects/hw.py
183
184
185
186
187
188
189
190
191
192
193
@dataclass
class InnerSymbolTable:
    """A class for lookups in inner symbol tables. Called InnerSymbolTable in upstream (name clash with trait)."""

    op: InitVar[Operation | None] = None
    symbol_table: dict[StringAttr, InnerSymTarget] = field(
        default_factory=dict[StringAttr, InnerSymTarget]
    )

    def __post_init__(self, op: Operation | None = None) -> None:
        pass

symbol_table: dict[StringAttr, InnerSymTarget] = field(default_factory=(dict[StringAttr, InnerSymTarget])) class-attribute instance-attribute

__init__(op: InitVar[Operation | None] = None, symbol_table: dict[StringAttr, InnerSymTarget] = dict[StringAttr, InnerSymTarget]()) -> None

__post_init__(op: Operation | None = None) -> None

Source code in xdsl/dialects/hw.py
192
193
def __post_init__(self, op: Operation | None = None) -> None:
    pass

InnerSymbolTableCollection dataclass

This class represents a collection of InnerSymbolTable.

Source code in xdsl/dialects/hw.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
@dataclass
class InnerSymbolTableCollection:
    """This class represents a collection of InnerSymbolTable."""

    symbol_tables: dict[Operation, InnerSymbolTable] = field(
        default_factory=dict[Operation, InnerSymbolTable], init=False
    )
    op: InitVar[Operation | None] = None

    def __post_init__(self, op: Operation | None = None) -> None:
        if op is None:
            return
        if not op.has_trait(trait := InnerRefNamespaceTrait):
            raise VerifyException(
                f"Operation {op.name} should have {trait.__name__} trait"
            )
        self.populate_and_verify_tables(op)

    def get_inner_symbol_table(self, op: Operation) -> InnerSymbolTable:
        """Returns the InnerSymolTable trait, ensuring `op` is in the collection"""
        if not op.has_trait(trait := InnerSymbolTableTrait):
            raise VerifyException(
                f"Operation {op.name} should have {trait.__name__} trait"
            )
        if op not in self.symbol_tables:
            self.symbol_tables[op] = InnerSymbolTable(op)
        return self.symbol_tables[op]

    def populate_and_verify_tables(self, inner_ref_ns_op: Operation):
        """Populate tables for all InnerSymbolTable operations in the given InnerRefNamespace operation, verifying each."""
        # Gather top-level operations that have the InnerSymbolTable trait.
        inner_sym_table_ops = (
            op for op in inner_ref_ns_op.walk() if op.has_trait(InnerSymbolTableTrait)
        )

        # Construct the tables
        for op in inner_sym_table_ops:
            if op in self.symbol_tables:
                raise VerifyException(
                    f"Trying to insert the same op twice in symbol tables: {op}"
                )
            self.symbol_tables[op] = InnerSymbolTable(op)

symbol_tables: dict[Operation, InnerSymbolTable] = field(default_factory=(dict[Operation, InnerSymbolTable]), init=False) class-attribute instance-attribute

__init__(op: InitVar[Operation | None] = None) -> None

__post_init__(op: Operation | None = None) -> None

Source code in xdsl/dialects/hw.py
206
207
208
209
210
211
212
213
def __post_init__(self, op: Operation | None = None) -> None:
    if op is None:
        return
    if not op.has_trait(trait := InnerRefNamespaceTrait):
        raise VerifyException(
            f"Operation {op.name} should have {trait.__name__} trait"
        )
    self.populate_and_verify_tables(op)

get_inner_symbol_table(op: Operation) -> InnerSymbolTable

Returns the InnerSymolTable trait, ensuring op is in the collection

Source code in xdsl/dialects/hw.py
215
216
217
218
219
220
221
222
223
def get_inner_symbol_table(self, op: Operation) -> InnerSymbolTable:
    """Returns the InnerSymolTable trait, ensuring `op` is in the collection"""
    if not op.has_trait(trait := InnerSymbolTableTrait):
        raise VerifyException(
            f"Operation {op.name} should have {trait.__name__} trait"
        )
    if op not in self.symbol_tables:
        self.symbol_tables[op] = InnerSymbolTable(op)
    return self.symbol_tables[op]

populate_and_verify_tables(inner_ref_ns_op: Operation)

Populate tables for all InnerSymbolTable operations in the given InnerRefNamespace operation, verifying each.

Source code in xdsl/dialects/hw.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def populate_and_verify_tables(self, inner_ref_ns_op: Operation):
    """Populate tables for all InnerSymbolTable operations in the given InnerRefNamespace operation, verifying each."""
    # Gather top-level operations that have the InnerSymbolTable trait.
    inner_sym_table_ops = (
        op for op in inner_ref_ns_op.walk() if op.has_trait(InnerSymbolTableTrait)
    )

    # Construct the tables
    for op in inner_sym_table_ops:
        if op in self.symbol_tables:
            raise VerifyException(
                f"Trying to insert the same op twice in symbol tables: {op}"
            )
        self.symbol_tables[op] = InnerSymbolTable(op)

InnerRefUserOpInterfaceTrait dataclass

Bases: OpTrait

This interface describes an operation that may use a InnerRef. This interface allows for users of inner symbols to hook into verification and other inner symbol related utilities that are either costly or otherwise disallowed within a traditional operation.

Source code in xdsl/dialects/hw.py
241
242
243
244
245
246
247
248
249
class InnerRefUserOpInterfaceTrait(OpTrait):
    """This interface describes an operation that may use a `InnerRef`. This
    interface allows for users of inner symbols to hook into verification and
    other inner symbol related utilities that are either costly or otherwise
    disallowed within a traditional operation."""

    def verify_inner_refs(self, op: Operation, namespace: InnerRefNamespace):
        """Verify the inner ref uses held by this operation."""
        ...

verify_inner_refs(op: Operation, namespace: InnerRefNamespace)

Verify the inner ref uses held by this operation.

Source code in xdsl/dialects/hw.py
247
248
249
def verify_inner_refs(self, op: Operation, namespace: InnerRefNamespace):
    """Verify the inner ref uses held by this operation."""
    ...

InnerRefNamespaceTrait dataclass

Bases: OpTrait

Trait for operations defining a new scope for InnerRef's. Operations with this trait must be a SymbolTable.

Source code in xdsl/dialects/hw.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
@dataclass(frozen=True)
class InnerRefNamespaceTrait(OpTrait):
    """Trait for operations defining a new scope for InnerRef's. Operations with this trait must be a SymbolTable."""

    def verify(self, op: Operation):
        if not op.has_trait(trait := SymbolTable):
            raise VerifyException(
                f"Operation {op.name} must have trait {trait.__name__}"
            )

        # Upstreams verifies that len(op.regions) == 1 and len(op.regions[0].blocks) == 1
        # however this is already checked as part of SymbolTable, so would be redundant to re-check here

        namespace = InnerRefNamespace(op)

        for inner_op in op.walk():
            inner_ref_user_op_trait = inner_op.get_trait(InnerRefUserOpInterfaceTrait)
            if inner_ref_user_op_trait is not None:
                inner_ref_user_op_trait.verify_inner_refs(inner_op, namespace)

__init__() -> None

verify(op: Operation)

Source code in xdsl/dialects/hw.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def verify(self, op: Operation):
    if not op.has_trait(trait := SymbolTable):
        raise VerifyException(
            f"Operation {op.name} must have trait {trait.__name__}"
        )

    # Upstreams verifies that len(op.regions) == 1 and len(op.regions[0].blocks) == 1
    # however this is already checked as part of SymbolTable, so would be redundant to re-check here

    namespace = InnerRefNamespace(op)

    for inner_op in op.walk():
        inner_ref_user_op_trait = inner_op.get_trait(InnerRefUserOpInterfaceTrait)
        if inner_ref_user_op_trait is not None:
            inner_ref_user_op_trait.verify_inner_refs(inner_op, namespace)

InnerRefNamespaceLike dataclass

Bases: ABC, OpTrait

Trait-metaclass to check whether an operation is explicitly an IRN or appears compatible.

Source code in xdsl/dialects/hw.py
273
274
class InnerRefNamespaceLike(abc.ABC, OpTrait):
    """Trait-metaclass to check whether an operation is explicitly an IRN or appears compatible."""

InnerRefNamespace dataclass

Class to perform symbol lookups within a InnerRef namespace, used during verification. Combines InnerSymbolTableCollection with a SymbolTable for resolution of InnerRefAttrs.

Inner symbols are more costly than normal symbols, with tricker verification. For this reason, verification is driven as a trait verifier on InnerRefNamespace which constructs and verifies InnerSymbolTables in parallel. See: https://circt.llvm.org/docs/RationaleSymbols/#innerrefnamespace

Source code in xdsl/dialects/hw.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
@dataclass
class InnerRefNamespace:
    """Class to perform symbol lookups within a InnerRef namespace, used during verification.
    Combines InnerSymbolTableCollection with a SymbolTable for resolution of InnerRefAttrs.

    Inner symbols are more costly than normal symbols, with tricker verification. For this reason,
    verification is driven as a trait verifier on InnerRefNamespace which constructs and verifies InnerSymbolTables in parallel.
    See: https://circt.llvm.org/docs/RationaleSymbols/#innerrefnamespace
    """

    inner_sym_tables: InnerSymbolTableCollection = field(init=False)
    inner_ref_ns_op: InitVar[Operation]

    def __init__(self, inner_ref_ns_op: Operation):
        self.inner_sym_tables = InnerSymbolTableCollection(inner_ref_ns_op)

inner_ref_ns_op: InitVar[Operation] instance-attribute

inner_sym_tables: InnerSymbolTableCollection = InnerSymbolTableCollection(inner_ref_ns_op) class-attribute instance-attribute

__init__(inner_ref_ns_op: Operation)

Source code in xdsl/dialects/hw.py
294
295
def __init__(self, inner_ref_ns_op: Operation):
    self.inner_sym_tables = InnerSymbolTableCollection(inner_ref_ns_op)

InnerSymPropertiesAttr

Bases: ParametrizedAttribute

Source code in xdsl/dialects/hw.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
@irdl_attr_definition
class InnerSymPropertiesAttr(ParametrizedAttribute):
    name = "hw.innerSymProps"

    # NB. upstream defines as “name” which clashes with Attribute.name
    sym_name: StringAttr
    field_id: IntAttr
    sym_visibility: StringAttr

    def __init__(
        self,
        sym: str | StringAttr,
        field_id: int | IntAttr = 0,
        sym_visibility: str | StringAttr = "public",
    ) -> None:
        if isinstance(sym, str):
            sym = StringAttr(sym)
        if isinstance(field_id, int):
            field_id = IntAttr(field_id)
        if isinstance(sym_visibility, str):
            sym_visibility = StringAttr(sym_visibility)
        super().__init__(sym, field_id, sym_visibility)

    @classmethod
    def parse_parameters(
        cls, parser: AttrParser
    ) -> tuple[StringAttr, IntAttr, StringAttr]:
        parser.parse_punctuation("<")
        sym_name = parser.parse_symbol_name()
        parser.parse_punctuation(",")
        field_id = parser.parse_integer(allow_negative=False, allow_boolean=False)
        parser.parse_punctuation(",")
        sym_visibility = parser.parse_identifier()
        if sym_visibility not in {"public", "private", "nested"}:
            parser.raise_error('Expected "public", "private", or "nested"')
        parser.parse_punctuation(">")
        return (sym_name, IntAttr(field_id), StringAttr(sym_visibility))

    def print_parameters(self, printer: Printer) -> None:
        printer.print_string("<@")
        printer.print_string(self.sym_name.data)
        printer.print_string(",")
        printer.print_int(self.field_id.data)
        printer.print_string(",")
        printer.print_string(self.sym_visibility.data)
        printer.print_string(">")

    def verify(self):
        if not self.sym_name or not self.sym_name.data:
            raise VerifyException("inner symbol cannot have empty name")

name = 'hw.innerSymProps' class-attribute instance-attribute

sym_name: StringAttr instance-attribute

field_id: IntAttr instance-attribute

sym_visibility: StringAttr instance-attribute

__init__(sym: str | StringAttr, field_id: int | IntAttr = 0, sym_visibility: str | StringAttr = 'public') -> None

Source code in xdsl/dialects/hw.py
307
308
309
310
311
312
313
314
315
316
317
318
319
def __init__(
    self,
    sym: str | StringAttr,
    field_id: int | IntAttr = 0,
    sym_visibility: str | StringAttr = "public",
) -> None:
    if isinstance(sym, str):
        sym = StringAttr(sym)
    if isinstance(field_id, int):
        field_id = IntAttr(field_id)
    if isinstance(sym_visibility, str):
        sym_visibility = StringAttr(sym_visibility)
    super().__init__(sym, field_id, sym_visibility)

parse_parameters(parser: AttrParser) -> tuple[StringAttr, IntAttr, StringAttr] classmethod

Source code in xdsl/dialects/hw.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
@classmethod
def parse_parameters(
    cls, parser: AttrParser
) -> tuple[StringAttr, IntAttr, StringAttr]:
    parser.parse_punctuation("<")
    sym_name = parser.parse_symbol_name()
    parser.parse_punctuation(",")
    field_id = parser.parse_integer(allow_negative=False, allow_boolean=False)
    parser.parse_punctuation(",")
    sym_visibility = parser.parse_identifier()
    if sym_visibility not in {"public", "private", "nested"}:
        parser.raise_error('Expected "public", "private", or "nested"')
    parser.parse_punctuation(">")
    return (sym_name, IntAttr(field_id), StringAttr(sym_visibility))

print_parameters(printer: Printer) -> None

Source code in xdsl/dialects/hw.py
336
337
338
339
340
341
342
343
def print_parameters(self, printer: Printer) -> None:
    printer.print_string("<@")
    printer.print_string(self.sym_name.data)
    printer.print_string(",")
    printer.print_int(self.field_id.data)
    printer.print_string(",")
    printer.print_string(self.sym_visibility.data)
    printer.print_string(">")

verify()

Source code in xdsl/dialects/hw.py
345
346
347
def verify(self):
    if not self.sym_name or not self.sym_name.data:
        raise VerifyException("inner symbol cannot have empty name")

InnerSymAttr

Bases: ParametrizedAttribute, Iterable[InnerSymPropertiesAttr], OpaqueSyntaxAttribute

Inner symbol definition

Defines the properties of an inner_sym attribute. It specifies the symbol name and symbol visibility for each field ID. For any ground types, there are no subfields and the field ID is 0. For aggregate types, a unique field ID is assigned to each field by visiting them in a depth-first pre-order.

The custom assembly format ensures that for ground types, only @<sym_name> is printed.

Source code in xdsl/dialects/hw.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
@irdl_attr_definition
class InnerSymAttr(
    ParametrizedAttribute, Iterable[InnerSymPropertiesAttr], OpaqueSyntaxAttribute
):
    """Inner symbol definition

    Defines the properties of an inner_sym attribute. It specifies the symbol name and symbol
    visibility for each field ID. For any ground types, there are no subfields and the field ID is 0.
    For aggregate types, a unique field ID is assigned to each field by visiting them in a
    depth-first pre-order.

    The custom assembly format ensures that for ground types, only `@<sym_name>` is printed.
    """

    name = "hw.innerSym"

    props: ArrayAttr[InnerSymPropertiesAttr]

    @overload
    def __init__(self) -> None:
        # Create an empty array, represents an invalid InnerSym.
        ...

    @overload
    def __init__(self, syms: str | StringAttr) -> None: ...

    @overload
    def __init__(
        self, syms: Sequence[InnerSymPropertiesAttr] | ArrayAttr[InnerSymPropertiesAttr]
    ) -> None: ...

    def __init__(
        self,
        syms: (
            str
            | StringAttr
            | Sequence[InnerSymPropertiesAttr]
            | ArrayAttr[InnerSymPropertiesAttr]
        ) = [],
    ) -> None:
        if isinstance(syms, str | StringAttr):
            syms = [InnerSymPropertiesAttr(syms)]
        if not isinstance(syms, ArrayAttr):
            syms = ArrayAttr(syms)
        super().__init__(syms)

    def get_sym_if_exists(self, field_id: IntAttr | int) -> StringAttr | None:
        """Get the inner sym name for field_id, if it exists."""
        if not isinstance(field_id, IntAttr):
            field_id = IntAttr(field_id)

        for prop in self.props:
            if field_id == prop.field_id:
                return prop.sym_name

    def get_sym_name(self) -> StringAttr | None:
        """Get the inner sym name for field_id=0, if it exists."""
        return self.get_sym_if_exists(0)

    def __len__(self) -> int:
        """Get the number of inner symbols defined."""
        return len(self.props)

    def __iter__(self) -> Iterator[InnerSymPropertiesAttr]:
        """Iterator for all the InnerSymPropertiesAttr."""
        return iter(self.props)

    def erase(self, field_id: IntAttr | int) -> InnerSymAttr:
        """Return an InnerSymAttr with the inner symbol for the specified field_id removed."""
        if not isinstance(field_id, IntAttr):
            field_id = IntAttr(field_id)
        return InnerSymAttr([prop for prop in self.props if prop.field_id != field_id])

    @classmethod
    def parse_parameters(
        cls, parser: AttrParser
    ) -> list[ArrayAttr[InnerSymPropertiesAttr]]:
        if (sym_name := parser.parse_optional_symbol_name()) is not None:
            return [ArrayAttr([InnerSymPropertiesAttr(sym_name, 0, "public")])]

        data = parser.parse_comma_separated_list(
            parser.Delimiter.SQUARE,
            lambda: InnerSymPropertiesAttr.parse_parameters(parser),
        )
        return [ArrayAttr(InnerSymPropertiesAttr(*tup) for tup in data)]

    def print_parameters(self, printer: Printer):
        if (
            len(self) == 1
            and (sym_name := self.get_sym_name()) is not None
            and self.props.data[0].sym_visibility.data == "public"
            and self.props.data[0].field_id.data == 0
        ):
            printer.print_string("@")
            printer.print_string(sym_name.data)
        else:
            printer.print_string("[")
            printer.print_list(
                sorted(self.props, key=lambda prop: prop.field_id.data),
                lambda prop: prop.print_parameters(printer),
            )
            printer.print_string("]")

name = 'hw.innerSym' class-attribute instance-attribute

props: ArrayAttr[InnerSymPropertiesAttr] instance-attribute

__init__(syms: str | StringAttr | Sequence[InnerSymPropertiesAttr] | ArrayAttr[InnerSymPropertiesAttr] = []) -> None

__init__() -> None
__init__(syms: str | StringAttr) -> None
__init__(
    syms: Sequence[InnerSymPropertiesAttr]
    | ArrayAttr[InnerSymPropertiesAttr],
) -> None
Source code in xdsl/dialects/hw.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def __init__(
    self,
    syms: (
        str
        | StringAttr
        | Sequence[InnerSymPropertiesAttr]
        | ArrayAttr[InnerSymPropertiesAttr]
    ) = [],
) -> None:
    if isinstance(syms, str | StringAttr):
        syms = [InnerSymPropertiesAttr(syms)]
    if not isinstance(syms, ArrayAttr):
        syms = ArrayAttr(syms)
    super().__init__(syms)

get_sym_if_exists(field_id: IntAttr | int) -> StringAttr | None

Get the inner sym name for field_id, if it exists.

Source code in xdsl/dialects/hw.py
396
397
398
399
400
401
402
403
def get_sym_if_exists(self, field_id: IntAttr | int) -> StringAttr | None:
    """Get the inner sym name for field_id, if it exists."""
    if not isinstance(field_id, IntAttr):
        field_id = IntAttr(field_id)

    for prop in self.props:
        if field_id == prop.field_id:
            return prop.sym_name

get_sym_name() -> StringAttr | None

Get the inner sym name for field_id=0, if it exists.

Source code in xdsl/dialects/hw.py
405
406
407
def get_sym_name(self) -> StringAttr | None:
    """Get the inner sym name for field_id=0, if it exists."""
    return self.get_sym_if_exists(0)

__len__() -> int

Get the number of inner symbols defined.

Source code in xdsl/dialects/hw.py
409
410
411
def __len__(self) -> int:
    """Get the number of inner symbols defined."""
    return len(self.props)

__iter__() -> Iterator[InnerSymPropertiesAttr]

Iterator for all the InnerSymPropertiesAttr.

Source code in xdsl/dialects/hw.py
413
414
415
def __iter__(self) -> Iterator[InnerSymPropertiesAttr]:
    """Iterator for all the InnerSymPropertiesAttr."""
    return iter(self.props)

erase(field_id: IntAttr | int) -> InnerSymAttr

Return an InnerSymAttr with the inner symbol for the specified field_id removed.

Source code in xdsl/dialects/hw.py
417
418
419
420
421
def erase(self, field_id: IntAttr | int) -> InnerSymAttr:
    """Return an InnerSymAttr with the inner symbol for the specified field_id removed."""
    if not isinstance(field_id, IntAttr):
        field_id = IntAttr(field_id)
    return InnerSymAttr([prop for prop in self.props if prop.field_id != field_id])

parse_parameters(parser: AttrParser) -> list[ArrayAttr[InnerSymPropertiesAttr]] classmethod

Source code in xdsl/dialects/hw.py
423
424
425
426
427
428
429
430
431
432
433
434
@classmethod
def parse_parameters(
    cls, parser: AttrParser
) -> list[ArrayAttr[InnerSymPropertiesAttr]]:
    if (sym_name := parser.parse_optional_symbol_name()) is not None:
        return [ArrayAttr([InnerSymPropertiesAttr(sym_name, 0, "public")])]

    data = parser.parse_comma_separated_list(
        parser.Delimiter.SQUARE,
        lambda: InnerSymPropertiesAttr.parse_parameters(parser),
    )
    return [ArrayAttr(InnerSymPropertiesAttr(*tup) for tup in data)]

print_parameters(printer: Printer)

Source code in xdsl/dialects/hw.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
def print_parameters(self, printer: Printer):
    if (
        len(self) == 1
        and (sym_name := self.get_sym_name()) is not None
        and self.props.data[0].sym_visibility.data == "public"
        and self.props.data[0].field_id.data == 0
    ):
        printer.print_string("@")
        printer.print_string(sym_name.data)
    else:
        printer.print_string("[")
        printer.print_list(
            sorted(self.props, key=lambda prop: prop.field_id.data),
            lambda prop: prop.print_parameters(printer),
        )
        printer.print_string("]")

Direction

Bases: Enum

Represents the direction of a module port.

Source code in xdsl/dialects/hw.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
class Direction(Enum):
    """
    Represents the direction of a module port.
    """

    # TODO: support INOUT direction (https://github.com/xdslproject/xdsl/issues/2368)
    INPUT = 0
    OUTPUT = 1

    @staticmethod
    def parse_optional(parser: BaseParser, short: bool = False) -> Direction | None:
        if parser.parse_optional_keyword("input" if not short else "in"):
            return Direction.INPUT
        elif parser.parse_optional_keyword("output" if not short else "out"):
            return Direction.OUTPUT
        else:
            return None

    @staticmethod
    def parse(parser: BaseParser, short: bool = False) -> Direction:
        if (direction := Direction.parse_optional(parser, short)) is None:
            return parser.raise_error("invalid port direction")
        return direction

    def print(self, printer: Printer, short: bool = False) -> None:
        match self:
            case Direction.INPUT:
                printer.print_string("input" if not short else "in")
            case Direction.OUTPUT:
                printer.print_string("output" if not short else "out")

    def is_input_like(self) -> bool:
        return self == Direction.INPUT

    def is_output_like(self) -> bool:
        return self == Direction.OUTPUT

INPUT = 0 class-attribute instance-attribute

OUTPUT = 1 class-attribute instance-attribute

parse_optional(parser: BaseParser, short: bool = False) -> Direction | None staticmethod

Source code in xdsl/dialects/hw.py
463
464
465
466
467
468
469
470
@staticmethod
def parse_optional(parser: BaseParser, short: bool = False) -> Direction | None:
    if parser.parse_optional_keyword("input" if not short else "in"):
        return Direction.INPUT
    elif parser.parse_optional_keyword("output" if not short else "out"):
        return Direction.OUTPUT
    else:
        return None

parse(parser: BaseParser, short: bool = False) -> Direction staticmethod

Source code in xdsl/dialects/hw.py
472
473
474
475
476
@staticmethod
def parse(parser: BaseParser, short: bool = False) -> Direction:
    if (direction := Direction.parse_optional(parser, short)) is None:
        return parser.raise_error("invalid port direction")
    return direction

print(printer: Printer, short: bool = False) -> None

Source code in xdsl/dialects/hw.py
478
479
480
481
482
483
def print(self, printer: Printer, short: bool = False) -> None:
    match self:
        case Direction.INPUT:
            printer.print_string("input" if not short else "in")
        case Direction.OUTPUT:
            printer.print_string("output" if not short else "out")

is_input_like() -> bool

Source code in xdsl/dialects/hw.py
485
486
def is_input_like(self) -> bool:
    return self == Direction.INPUT

is_output_like() -> bool

Source code in xdsl/dialects/hw.py
488
489
def is_output_like(self) -> bool:
    return self == Direction.OUTPUT

DirectionAttr dataclass

Bases: Data[Direction]

Represents a ModulePort's direction. This attribute does not exist in CIRCT but is useful in xDSL to give structure to ModuleType.

Source code in xdsl/dialects/hw.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
@irdl_attr_definition
class DirectionAttr(Data[Direction]):
    """
    Represents a ModulePort's direction. This attribute does not
    exist in CIRCT but is useful in xDSL to give structure to ModuleType.
    """

    name = "hw.direction"

    @classmethod
    def parse_parameter(cls, parser: AttrParser) -> Direction:
        with parser.in_angle_brackets():
            return Direction.parse(parser)

    def print_parameter(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            self.data.print(printer)

name = 'hw.direction' class-attribute instance-attribute

parse_parameter(parser: AttrParser) -> Direction classmethod

Source code in xdsl/dialects/hw.py
501
502
503
504
@classmethod
def parse_parameter(cls, parser: AttrParser) -> Direction:
    with parser.in_angle_brackets():
        return Direction.parse(parser)

print_parameter(printer: Printer) -> None

Source code in xdsl/dialects/hw.py
506
507
508
def print_parameter(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        self.data.print(printer)

ModulePort dataclass

Bases: ParametrizedAttribute

Represents a ModulePort. This attribute does not exist in CIRCT but is useful in xDSL to give structure to ModuleType.

Source code in xdsl/dialects/hw.py
511
512
513
514
515
516
517
518
519
520
521
522
@irdl_attr_definition
class ModulePort(ParametrizedAttribute):
    """
    Represents a ModulePort. This attribute does not exist in CIRCT
    but is useful in xDSL to give structure to ModuleType.
    """

    name = "hw.modport"

    port_name: StringAttr
    type: TypeAttribute
    dir: DirectionAttr

name = 'hw.modport' class-attribute instance-attribute

port_name: StringAttr instance-attribute

type: TypeAttribute instance-attribute

dir: DirectionAttr instance-attribute

ModuleType dataclass

Bases: ParametrizedAttribute, TypeAttribute

Source code in xdsl/dialects/hw.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
@irdl_attr_definition
class ModuleType(ParametrizedAttribute, TypeAttribute):
    name = "hw.modty"

    ports: ArrayAttr[ModulePort]

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
        def parse_port() -> ModulePort:
            direction = Direction.parse(parser)
            name = (
                parser.parse_optional_identifier()
                or parser.parse_optional_str_literal()
            )
            if name is None:
                parser.raise_error("expected port name as identifier or string literal")

            parser.parse_punctuation(":")
            typ = parser.parse_type()

            return ModulePort(StringAttr(name), typ, DirectionAttr(direction))

        return [
            ArrayAttr(
                parser.parse_comma_separated_list(parser.Delimiter.ANGLE, parse_port)
            )
        ]

    def print_parameters(self, printer: Printer):
        def print_port(port: ModulePort):
            port.dir.data.print(printer)
            printer.print_string(" ")
            printer.print_identifier_or_string_literal(port.port_name.data)
            printer.print_string(" : ")
            printer.print_attribute(port.type)

        with printer.in_angle_brackets():
            printer.print_list(self.ports.data, print_port)

name = 'hw.modty' class-attribute instance-attribute

ports: ArrayAttr[ModulePort] instance-attribute

parse_parameters(parser: AttrParser) -> Sequence[Attribute] classmethod

Source code in xdsl/dialects/hw.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
@classmethod
def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
    def parse_port() -> ModulePort:
        direction = Direction.parse(parser)
        name = (
            parser.parse_optional_identifier()
            or parser.parse_optional_str_literal()
        )
        if name is None:
            parser.raise_error("expected port name as identifier or string literal")

        parser.parse_punctuation(":")
        typ = parser.parse_type()

        return ModulePort(StringAttr(name), typ, DirectionAttr(direction))

    return [
        ArrayAttr(
            parser.parse_comma_separated_list(parser.Delimiter.ANGLE, parse_port)
        )
    ]

print_parameters(printer: Printer)

Source code in xdsl/dialects/hw.py
553
554
555
556
557
558
559
560
561
562
def print_parameters(self, printer: Printer):
    def print_port(port: ModulePort):
        port.dir.data.print(printer)
        printer.print_string(" ")
        printer.print_identifier_or_string_literal(port.port_name.data)
        printer.print_string(" : ")
        printer.print_attribute(port.type)

    with printer.in_angle_brackets():
        printer.print_list(self.ports.data, print_port)

ParamDeclAttr dataclass

Bases: ParametrizedAttribute

Source code in xdsl/dialects/hw.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
@irdl_attr_definition
class ParamDeclAttr(ParametrizedAttribute):
    name = "hw.param.decl"

    port_name: StringAttr
    type: TypeAttribute

    @classmethod
    def parse_free_standing_parameters(
        cls, parser: AttrParser, only_accept_string_literal_name: bool = False
    ) -> tuple[StringAttr, TypeAttribute]:
        """
        Parses the parameter declaration without the encompassing angle brackets.
        If only_accept_string_literal_name is True, the parser will not accept
        the name of the parameter to be an identifier but only as a string literal.
        """

        name = parser.parse_optional_str_literal()
        if name is None:
            if only_accept_string_literal_name:
                parser.raise_error("expected parameter name as string literal")
            name = parser.expect(
                parser.parse_optional_identifier, "expected parameter name"
            )
        parser.parse_punctuation(":")
        typ = parser.parse_attribute()
        if not isinstance(typ, TypeAttribute):
            parser.raise_error("expected type attribute for parameter")

        if parser.parse_optional_punctuation("=") is not None:
            # TODO: support default values for parameters (https://github.com/xdslproject/xdsl/issues/2367)
            parser.raise_error("default values for parameters are not yet supported")

        return (StringAttr(name), typ)

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
        with parser.in_angle_brackets():
            return cls.parse_free_standing_parameters(
                parser, only_accept_string_literal_name=True
            )

    def print_free_standing_parameters(
        self, printer: Printer, print_name_as_string_literal: bool = False
    ):
        """
        Prints the parameter declaration without the encompassing angle brackets.
        If print_name_as_string_literal is True, the name of the parameter will
        never be printed as an identifier but only as a string literal.
        """
        if print_name_as_string_literal:
            printer.print_attribute(self.port_name)
        else:
            printer.print_identifier_or_string_literal(self.port_name.data)
        printer.print_string(": ")
        printer.print_attribute(self.type)

    def print_parameters(self, printer: Printer):
        with printer.in_angle_brackets():
            self.print_free_standing_parameters(
                printer, print_name_as_string_literal=True
            )

name = 'hw.param.decl' class-attribute instance-attribute

port_name: StringAttr instance-attribute

type: TypeAttribute instance-attribute

parse_free_standing_parameters(parser: AttrParser, only_accept_string_literal_name: bool = False) -> tuple[StringAttr, TypeAttribute] classmethod

Parses the parameter declaration without the encompassing angle brackets. If only_accept_string_literal_name is True, the parser will not accept the name of the parameter to be an identifier but only as a string literal.

Source code in xdsl/dialects/hw.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
@classmethod
def parse_free_standing_parameters(
    cls, parser: AttrParser, only_accept_string_literal_name: bool = False
) -> tuple[StringAttr, TypeAttribute]:
    """
    Parses the parameter declaration without the encompassing angle brackets.
    If only_accept_string_literal_name is True, the parser will not accept
    the name of the parameter to be an identifier but only as a string literal.
    """

    name = parser.parse_optional_str_literal()
    if name is None:
        if only_accept_string_literal_name:
            parser.raise_error("expected parameter name as string literal")
        name = parser.expect(
            parser.parse_optional_identifier, "expected parameter name"
        )
    parser.parse_punctuation(":")
    typ = parser.parse_attribute()
    if not isinstance(typ, TypeAttribute):
        parser.raise_error("expected type attribute for parameter")

    if parser.parse_optional_punctuation("=") is not None:
        # TODO: support default values for parameters (https://github.com/xdslproject/xdsl/issues/2367)
        parser.raise_error("default values for parameters are not yet supported")

    return (StringAttr(name), typ)

parse_parameters(parser: AttrParser) -> Sequence[Attribute] classmethod

Source code in xdsl/dialects/hw.py
600
601
602
603
604
605
@classmethod
def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
    with parser.in_angle_brackets():
        return cls.parse_free_standing_parameters(
            parser, only_accept_string_literal_name=True
        )

print_free_standing_parameters(printer: Printer, print_name_as_string_literal: bool = False)

Prints the parameter declaration without the encompassing angle brackets. If print_name_as_string_literal is True, the name of the parameter will never be printed as an identifier but only as a string literal.

Source code in xdsl/dialects/hw.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def print_free_standing_parameters(
    self, printer: Printer, print_name_as_string_literal: bool = False
):
    """
    Prints the parameter declaration without the encompassing angle brackets.
    If print_name_as_string_literal is True, the name of the parameter will
    never be printed as an identifier but only as a string literal.
    """
    if print_name_as_string_literal:
        printer.print_attribute(self.port_name)
    else:
        printer.print_identifier_or_string_literal(self.port_name.data)
    printer.print_string(": ")
    printer.print_attribute(self.type)

print_parameters(printer: Printer)

Source code in xdsl/dialects/hw.py
622
623
624
625
626
def print_parameters(self, printer: Printer):
    with printer.in_angle_brackets():
        self.print_free_standing_parameters(
            printer, print_name_as_string_literal=True
        )

ArrayType

Bases: ParametrizedAttribute, TypeAttribute, ContainerType[ArrayElementCovT], Generic[ArrayElementCovT]

Fixed-sized array

Source code in xdsl/dialects/hw.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
@irdl_attr_definition
class ArrayType(
    ParametrizedAttribute,
    TypeAttribute,
    ContainerType[ArrayElementCovT],
    Generic[ArrayElementCovT],
):
    """
    Fixed-sized array
    """

    name = "hw.array"

    element_type: ArrayElementCovT
    size_attr: IntAttr

    def __init__(
        self,
        element_type: ArrayElementCovT,
        size_attr: IntAttr | int,
    ):
        if isinstance(size_attr, int):
            size_attr = IntAttr(size_attr)
        super().__init__(
            element_type,
            size_attr,
        )

    def __len__(self) -> int:
        return self.size_attr.data

    def get_element_type(self) -> ArrayElementCovT:
        return self.element_type

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
        parser.parse_punctuation("<", " in hw.array type")
        size_attr, type = parser.parse_ranked_shape()
        if len(size_attr) != 1:
            parser.raise_error("Expected one size in hw.array type")
        size_attr = IntAttr(size_attr[0])
        parser.parse_punctuation(">", " in hw.array type")
        return [type, size_attr]

    def print_parameters(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            printer.print_int(len(self))
            printer.print_string("x")
            printer.print_attribute(self.get_element_type())

    def _verify(self):
        typ = self.get_element_type()
        if isa(typ, ArrayType):
            typ.get_element_type()._verify()
        elif isa(typ, IntegerType):
            if typ.signedness.data != Signedness.SIGNLESS:
                raise VerifyException(f"{self} -> {typ} must be a signless integer")
        else:
            raise VerifyException(
                f"{self} -> {typ} is not a hw.array or a signless integer"
            )
        return

name = 'hw.array' class-attribute instance-attribute

element_type: ArrayElementCovT instance-attribute

size_attr: IntAttr instance-attribute

__init__(element_type: ArrayElementCovT, size_attr: IntAttr | int)

Source code in xdsl/dialects/hw.py
650
651
652
653
654
655
656
657
658
659
660
def __init__(
    self,
    element_type: ArrayElementCovT,
    size_attr: IntAttr | int,
):
    if isinstance(size_attr, int):
        size_attr = IntAttr(size_attr)
    super().__init__(
        element_type,
        size_attr,
    )

__len__() -> int

Source code in xdsl/dialects/hw.py
662
663
def __len__(self) -> int:
    return self.size_attr.data

get_element_type() -> ArrayElementCovT

Source code in xdsl/dialects/hw.py
665
666
def get_element_type(self) -> ArrayElementCovT:
    return self.element_type

parse_parameters(parser: AttrParser) -> list[Attribute] classmethod

Source code in xdsl/dialects/hw.py
668
669
670
671
672
673
674
675
676
@classmethod
def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
    parser.parse_punctuation("<", " in hw.array type")
    size_attr, type = parser.parse_ranked_shape()
    if len(size_attr) != 1:
        parser.raise_error("Expected one size in hw.array type")
    size_attr = IntAttr(size_attr[0])
    parser.parse_punctuation(">", " in hw.array type")
    return [type, size_attr]

print_parameters(printer: Printer) -> None

Source code in xdsl/dialects/hw.py
678
679
680
681
682
def print_parameters(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        printer.print_int(len(self))
        printer.print_string("x")
        printer.print_attribute(self.get_element_type())

HWModuleLike dataclass

Bases: OpTrait, ABC

Represents an operation that can be interpreted as a hardware module.

Source code in xdsl/dialects/hw.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
class HWModuleLike(OpTrait, abc.ABC):
    """
    Represents an operation that can be interpreted as a hardware module.
    """

    @classmethod
    @abc.abstractmethod
    def get_hw_module_type(cls, op: Operation) -> ModuleType:
        """
        Returns the type of the module.
        """
        raise NotImplementedError()

    @classmethod
    @abc.abstractmethod
    def set_hw_module_type(cls, op: Operation, module_type: ModuleType) -> None:
        """
        Sets the type of the module.
        """
        raise NotImplementedError()

get_hw_module_type(op: Operation) -> ModuleType abstractmethod classmethod

Returns the type of the module.

Source code in xdsl/dialects/hw.py
703
704
705
706
707
708
709
@classmethod
@abc.abstractmethod
def get_hw_module_type(cls, op: Operation) -> ModuleType:
    """
    Returns the type of the module.
    """
    raise NotImplementedError()

set_hw_module_type(op: Operation, module_type: ModuleType) -> None abstractmethod classmethod

Sets the type of the module.

Source code in xdsl/dialects/hw.py
711
712
713
714
715
716
717
@classmethod
@abc.abstractmethod
def set_hw_module_type(cls, op: Operation, module_type: ModuleType) -> None:
    """
    Sets the type of the module.
    """
    raise NotImplementedError()

ParsedModuleHeader

Bases: NamedTuple

Represents the parsed common base of all modules. It consists mostly of the ports and parameters of the module.

Source code in xdsl/dialects/hw.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
class ParsedModuleHeader(NamedTuple):
    """
    Represents the parsed common base of all modules.
    It consists mostly of the ports and parameters of the
    module.
    """

    class ModuleArg(NamedTuple):
        port_dir: Direction
        port_name: str
        port_ssa: Parser.Argument | None
        port_type: TypeAttribute
        port_attrs: dict[str, Attribute]
        port_location: LocationAttr | None

    visibility: StringAttr | None
    module_name: StringAttr
    parameters: ArrayAttr[ParamDeclAttr]
    args: list[ModuleArg]

    def get_module_type(self) -> ModuleType:
        return ModuleType(
            ArrayAttr(
                tuple(
                    ModulePort(
                        StringAttr(arg.port_name),
                        arg.port_type,
                        DirectionAttr(arg.port_dir),
                    )
                    for arg in self.args
                )
            )
        )

    @classmethod
    def parse(cls, parser: Parser) -> ParsedModuleHeader:
        def parse_optional_port_name() -> str | None:
            return (
                parser.parse_optional_identifier()
                or parser.parse_optional_str_literal()
            )

        def parse_module_arg() -> ParsedModuleHeader.ModuleArg:
            port_dir = Direction.parse(parser, short=True)
            if port_dir.is_input_like():
                port_ssa = parser.parse_argument(expect_type=False)
                port_name = parse_optional_port_name()
                if port_name is None:
                    port_name = port_ssa.name.text[1:]
            else:
                port_ssa = None
                port_name = parse_optional_port_name()
                if port_name is None:
                    parser.raise_error(
                        "expected identifier or string literal as port name"
                    )
            parser.parse_punctuation(":")
            port_type = parser.parse_attribute()
            if not isinstance(port_type, TypeAttribute):
                parser.raise_error("port type must be a type attribute")

            port_attrs = parser.parse_optional_attr_dict()
            port_location = parser.parse_optional_location()

            # Resolve the argument
            if port_ssa is not None:
                port_ssa = Parser.Argument(port_ssa.name, port_type)

            return ParsedModuleHeader.ModuleArg(
                port_dir, port_name, port_ssa, port_type, port_attrs, port_location
            )

        sym_visibility = parser.parse_optional_visibility_keyword()
        name = parser.parse_symbol_name()
        parameters = parser.parse_optional_comma_separated_list(
            parser.Delimiter.ANGLE,
            lambda: ParamDeclAttr(
                *ParamDeclAttr.parse_free_standing_parameters(parser)
            ),
        )
        args = parser.parse_comma_separated_list(
            parser.Delimiter.PAREN, parse_module_arg
        )

        return cls(
            visibility=sym_visibility,
            module_name=name,
            parameters=ArrayAttr(parameters if parameters is not None else []),
            args=args,
        )

visibility: StringAttr | None instance-attribute

module_name: StringAttr instance-attribute

parameters: ArrayAttr[ParamDeclAttr] instance-attribute

args: list[ModuleArg] instance-attribute

ModuleArg

Bases: NamedTuple

Source code in xdsl/dialects/hw.py
727
728
729
730
731
732
733
class ModuleArg(NamedTuple):
    port_dir: Direction
    port_name: str
    port_ssa: Parser.Argument | None
    port_type: TypeAttribute
    port_attrs: dict[str, Attribute]
    port_location: LocationAttr | None
port_dir: Direction instance-attribute
port_name: str instance-attribute
port_ssa: Parser.Argument | None instance-attribute
port_type: TypeAttribute instance-attribute
port_attrs: dict[str, Attribute] instance-attribute
port_location: LocationAttr | None instance-attribute

get_module_type() -> ModuleType

Source code in xdsl/dialects/hw.py
740
741
742
743
744
745
746
747
748
749
750
751
752
def get_module_type(self) -> ModuleType:
    return ModuleType(
        ArrayAttr(
            tuple(
                ModulePort(
                    StringAttr(arg.port_name),
                    arg.port_type,
                    DirectionAttr(arg.port_dir),
                )
                for arg in self.args
            )
        )
    )

parse(parser: Parser) -> ParsedModuleHeader classmethod

Source code in xdsl/dialects/hw.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
@classmethod
def parse(cls, parser: Parser) -> ParsedModuleHeader:
    def parse_optional_port_name() -> str | None:
        return (
            parser.parse_optional_identifier()
            or parser.parse_optional_str_literal()
        )

    def parse_module_arg() -> ParsedModuleHeader.ModuleArg:
        port_dir = Direction.parse(parser, short=True)
        if port_dir.is_input_like():
            port_ssa = parser.parse_argument(expect_type=False)
            port_name = parse_optional_port_name()
            if port_name is None:
                port_name = port_ssa.name.text[1:]
        else:
            port_ssa = None
            port_name = parse_optional_port_name()
            if port_name is None:
                parser.raise_error(
                    "expected identifier or string literal as port name"
                )
        parser.parse_punctuation(":")
        port_type = parser.parse_attribute()
        if not isinstance(port_type, TypeAttribute):
            parser.raise_error("port type must be a type attribute")

        port_attrs = parser.parse_optional_attr_dict()
        port_location = parser.parse_optional_location()

        # Resolve the argument
        if port_ssa is not None:
            port_ssa = Parser.Argument(port_ssa.name, port_type)

        return ParsedModuleHeader.ModuleArg(
            port_dir, port_name, port_ssa, port_type, port_attrs, port_location
        )

    sym_visibility = parser.parse_optional_visibility_keyword()
    name = parser.parse_symbol_name()
    parameters = parser.parse_optional_comma_separated_list(
        parser.Delimiter.ANGLE,
        lambda: ParamDeclAttr(
            *ParamDeclAttr.parse_free_standing_parameters(parser)
        ),
    )
    args = parser.parse_comma_separated_list(
        parser.Delimiter.PAREN, parse_module_arg
    )

    return cls(
        visibility=sym_visibility,
        module_name=name,
        parameters=ArrayAttr(parameters if parameters is not None else []),
        args=args,
    )

HWModulesHWModuleLike dataclass

Bases: HWModuleLike

Source code in xdsl/dialects/hw.py
877
878
879
880
881
882
883
884
885
886
class HWModulesHWModuleLike(HWModuleLike):
    @classmethod
    def get_hw_module_type(cls, op: Operation) -> ModuleType:
        assert isinstance(op, HWModuleOp | HWModuleExternOp)
        return op.module_type

    @classmethod
    def set_hw_module_type(cls, op: Operation, module_type: ModuleType) -> None:
        assert isinstance(op, HWModuleOp | HWModuleExternOp)
        op.module_type = module_type

get_hw_module_type(op: Operation) -> ModuleType classmethod

Source code in xdsl/dialects/hw.py
878
879
880
881
@classmethod
def get_hw_module_type(cls, op: Operation) -> ModuleType:
    assert isinstance(op, HWModuleOp | HWModuleExternOp)
    return op.module_type

set_hw_module_type(op: Operation, module_type: ModuleType) -> None classmethod

Source code in xdsl/dialects/hw.py
883
884
885
886
@classmethod
def set_hw_module_type(cls, op: Operation, module_type: ModuleType) -> None:
    assert isinstance(op, HWModuleOp | HWModuleExternOp)
    op.module_type = module_type

HWModuleOp

Bases: IRDLOperation

Represents a Verilog module, including a given name, a list of ports, a list of parameters, and a body that represents the connections within the module.

Source code in xdsl/dialects/hw.py
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
@irdl_op_definition
class HWModuleOp(IRDLOperation):
    """
    Represents a Verilog module, including a given name, a list of ports,
    a list of parameters, and a body that represents the connections within
    the module.
    """

    name = "hw.module"

    sym_name = attr_def(SymbolNameConstraint())
    module_type = attr_def(ModuleType)
    sym_visibility = opt_attr_def(StringAttr)
    parameters = opt_attr_def(ArrayAttr[ParamDeclAttr])

    body = region_def("single_block")

    traits = lazy_traits_def(
        lambda: (
            SymbolOpInterface(),
            IsolatedFromAbove(),
            SingleBlockImplicitTerminator(OutputOp),
            HWModulesHWModuleLike(),
        )
    )

    def __init__(
        self,
        sym_name: StringAttr,
        module_type: ModuleType,
        body: Region,
        parameters: ArrayAttr[ParamDeclAttr] = ArrayAttr([]),
        visibility: str | StringAttr | None = None,
    ):
        attributes: dict[str, Attribute] = {
            "sym_name": sym_name,
            "module_type": module_type,
            "parameters": parameters,
        }

        if visibility:
            if isinstance(visibility, str):
                visibility = StringAttr(visibility)
            attributes["sym_visibility"] = visibility

        return super().__init__(
            attributes=attributes,
            regions=[body],
        )

    def verify_(self) -> None:
        if self.parameters is not None:
            # FIXME: once xDSL supports typed attributes, check that parameter
            # types are consistent with their default values
            param_names = [param.port_name.data for param in self.parameters.data]
            if len(set(param_names)) != len(param_names):
                raise VerifyException("module has two parameters of same name")
        block_args = iter(self.body.block.args)
        for i, port in enumerate(self.module_type.ports.data):
            if not port.dir.data.is_input_like():
                continue
            if (next_block_arg := next(block_args, None)) is None:
                raise VerifyException("missing block arguments in module block")
            if port.type != next_block_arg.type:
                raise VerifyException(
                    f"input-like port #{i} has inconsistent type with its matching "
                    f"module block argument (expected {port.type}, block argument "
                    f"is of type {next_block_arg.type})"
                )
        if next(block_args, None) is not None:
            raise VerifyException("too many block arguments in module block")

    @classmethod
    def parse(cls, parser: Parser) -> HWModuleOp:
        module_header = ParsedModuleHeader.parse(parser)

        attrs = parser.parse_optional_attr_dict_with_keyword(
            _MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT
        )

        # Create a body region suitable for the ports of the module.
        region_args = tuple(arg.port_ssa for arg in module_header.args if arg.port_ssa)
        body = parser.parse_region(region_args)

        module_op = cls(
            module_header.module_name,
            module_header.get_module_type(),
            body,
            module_header.parameters,
            module_header.visibility,
        )

        if attrs is not None:
            module_op.attributes.update(attrs.data)

        return module_op

    def print(self, printer: Printer):
        print_module_header(
            printer=printer,
            visibility=self.sym_visibility,
            module_name=self.sym_name,
            parameters=self.parameters,
            arg_ssa_iter=self.body.block.args,
            module_type=self.module_type,
        )
        printer.print_op_attributes(
            self.attributes,
            reserved_attr_names=_MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT,
            print_keyword=True,
        )
        printer.print_string(" ")
        printer.print_region(self.body, print_entry_block_args=False)

name = 'hw.module' class-attribute instance-attribute

sym_name = attr_def(SymbolNameConstraint()) class-attribute instance-attribute

module_type = attr_def(ModuleType) class-attribute instance-attribute

sym_visibility = opt_attr_def(StringAttr) class-attribute instance-attribute

parameters = opt_attr_def(ArrayAttr[ParamDeclAttr]) class-attribute instance-attribute

body = region_def('single_block') class-attribute instance-attribute

traits = lazy_traits_def(lambda: (SymbolOpInterface(), IsolatedFromAbove(), SingleBlockImplicitTerminator(OutputOp), HWModulesHWModuleLike())) class-attribute instance-attribute

__init__(sym_name: StringAttr, module_type: ModuleType, body: Region, parameters: ArrayAttr[ParamDeclAttr] = ArrayAttr([]), visibility: str | StringAttr | None = None)

Source code in xdsl/dialects/hw.py
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
def __init__(
    self,
    sym_name: StringAttr,
    module_type: ModuleType,
    body: Region,
    parameters: ArrayAttr[ParamDeclAttr] = ArrayAttr([]),
    visibility: str | StringAttr | None = None,
):
    attributes: dict[str, Attribute] = {
        "sym_name": sym_name,
        "module_type": module_type,
        "parameters": parameters,
    }

    if visibility:
        if isinstance(visibility, str):
            visibility = StringAttr(visibility)
        attributes["sym_visibility"] = visibility

    return super().__init__(
        attributes=attributes,
        regions=[body],
    )

verify_() -> None

Source code in xdsl/dialects/hw.py
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def verify_(self) -> None:
    if self.parameters is not None:
        # FIXME: once xDSL supports typed attributes, check that parameter
        # types are consistent with their default values
        param_names = [param.port_name.data for param in self.parameters.data]
        if len(set(param_names)) != len(param_names):
            raise VerifyException("module has two parameters of same name")
    block_args = iter(self.body.block.args)
    for i, port in enumerate(self.module_type.ports.data):
        if not port.dir.data.is_input_like():
            continue
        if (next_block_arg := next(block_args, None)) is None:
            raise VerifyException("missing block arguments in module block")
        if port.type != next_block_arg.type:
            raise VerifyException(
                f"input-like port #{i} has inconsistent type with its matching "
                f"module block argument (expected {port.type}, block argument "
                f"is of type {next_block_arg.type})"
            )
    if next(block_args, None) is not None:
        raise VerifyException("too many block arguments in module block")

parse(parser: Parser) -> HWModuleOp classmethod

Source code in xdsl/dialects/hw.py
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
@classmethod
def parse(cls, parser: Parser) -> HWModuleOp:
    module_header = ParsedModuleHeader.parse(parser)

    attrs = parser.parse_optional_attr_dict_with_keyword(
        _MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT
    )

    # Create a body region suitable for the ports of the module.
    region_args = tuple(arg.port_ssa for arg in module_header.args if arg.port_ssa)
    body = parser.parse_region(region_args)

    module_op = cls(
        module_header.module_name,
        module_header.get_module_type(),
        body,
        module_header.parameters,
        module_header.visibility,
    )

    if attrs is not None:
        module_op.attributes.update(attrs.data)

    return module_op

print(printer: Printer)

Source code in xdsl/dialects/hw.py
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
def print(self, printer: Printer):
    print_module_header(
        printer=printer,
        visibility=self.sym_visibility,
        module_name=self.sym_name,
        parameters=self.parameters,
        arg_ssa_iter=self.body.block.args,
        module_type=self.module_type,
    )
    printer.print_op_attributes(
        self.attributes,
        reserved_attr_names=_MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT,
        print_keyword=True,
    )
    printer.print_string(" ")
    printer.print_region(self.body, print_entry_block_args=False)

HWModuleExternOp

Bases: IRDLOperation

The "hw.module.extern" operation represents an external reference to a Verilog module, including a given name and a list of ports.

The 'verilogName' attribute (when present) specifies the spelling of the module name in Verilog we can use.

Source code in xdsl/dialects/hw.py
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
@irdl_op_definition
class HWModuleExternOp(IRDLOperation):
    """
    The "hw.module.extern" operation represents an external reference to a
    Verilog module, including a given name and a list of ports.

    The 'verilogName' attribute (when present) specifies the spelling of the
    module name in Verilog we can use.
    """

    name = "hw.module.extern"

    sym_name = attr_def(SymbolNameConstraint())
    module_type = attr_def(ModuleType)
    sym_visibility = opt_attr_def(StringAttr)
    parameters = opt_attr_def(ArrayAttr[ParamDeclAttr])
    verilog_name = opt_attr_def(StringAttr, attr_name="verilogName")

    traits = lazy_traits_def(
        lambda: (
            SymbolOpInterface(),
            HWModulesHWModuleLike(),
        )
    )

    def __init__(
        self,
        sym_name: StringAttr,
        module_type: ModuleType,
        parameters: ArrayAttr[ParamDeclAttr] = ArrayAttr([]),
        visibility: str | StringAttr | None = None,
    ):
        attributes: dict[str, Attribute] = {
            "sym_name": sym_name,
            "module_type": module_type,
            "parameters": parameters,
        }

        if visibility:
            if isinstance(visibility, str):
                visibility = StringAttr(visibility)
            attributes["sym_visibility"] = visibility

        return super().__init__(attributes=attributes)

    @classmethod
    def parse(cls, parser: Parser) -> HWModuleExternOp:
        module_header = ParsedModuleHeader.parse(parser)

        attrs = parser.parse_optional_attr_dict_with_keyword(
            _MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT
        )

        module_op = cls(
            module_header.module_name,
            module_header.get_module_type(),
            module_header.parameters,
            module_header.visibility,
        )

        if attrs is not None:
            module_op.attributes.update(attrs.data)

        return module_op

    def print(self, printer: Printer):
        # TODO: use the actual port name when it is a valid SSA name
        arg_ssa_names = tuple(
            f"port{i}"
            for i, port in enumerate(self.module_type.ports.data)
            if port.dir.data.is_input_like()
        )
        print_module_header(
            printer=printer,
            visibility=self.sym_visibility,
            module_name=self.sym_name,
            parameters=self.parameters,
            arg_ssa_iter=arg_ssa_names,
            module_type=self.module_type,
        )
        printer.print_op_attributes(
            self.attributes,
            reserved_attr_names=_MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT,
            print_keyword=True,
        )

name = 'hw.module.extern' class-attribute instance-attribute

sym_name = attr_def(SymbolNameConstraint()) class-attribute instance-attribute

module_type = attr_def(ModuleType) class-attribute instance-attribute

sym_visibility = opt_attr_def(StringAttr) class-attribute instance-attribute

parameters = opt_attr_def(ArrayAttr[ParamDeclAttr]) class-attribute instance-attribute

verilog_name = opt_attr_def(StringAttr, attr_name='verilogName') class-attribute instance-attribute

traits = lazy_traits_def(lambda: (SymbolOpInterface(), HWModulesHWModuleLike())) class-attribute instance-attribute

__init__(sym_name: StringAttr, module_type: ModuleType, parameters: ArrayAttr[ParamDeclAttr] = ArrayAttr([]), visibility: str | StringAttr | None = None)

Source code in xdsl/dialects/hw.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
def __init__(
    self,
    sym_name: StringAttr,
    module_type: ModuleType,
    parameters: ArrayAttr[ParamDeclAttr] = ArrayAttr([]),
    visibility: str | StringAttr | None = None,
):
    attributes: dict[str, Attribute] = {
        "sym_name": sym_name,
        "module_type": module_type,
        "parameters": parameters,
    }

    if visibility:
        if isinstance(visibility, str):
            visibility = StringAttr(visibility)
        attributes["sym_visibility"] = visibility

    return super().__init__(attributes=attributes)

parse(parser: Parser) -> HWModuleExternOp classmethod

Source code in xdsl/dialects/hw.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
@classmethod
def parse(cls, parser: Parser) -> HWModuleExternOp:
    module_header = ParsedModuleHeader.parse(parser)

    attrs = parser.parse_optional_attr_dict_with_keyword(
        _MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT
    )

    module_op = cls(
        module_header.module_name,
        module_header.get_module_type(),
        module_header.parameters,
        module_header.visibility,
    )

    if attrs is not None:
        module_op.attributes.update(attrs.data)

    return module_op

print(printer: Printer)

Source code in xdsl/dialects/hw.py
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def print(self, printer: Printer):
    # TODO: use the actual port name when it is a valid SSA name
    arg_ssa_names = tuple(
        f"port{i}"
        for i, port in enumerate(self.module_type.ports.data)
        if port.dir.data.is_input_like()
    )
    print_module_header(
        printer=printer,
        visibility=self.sym_visibility,
        module_name=self.sym_name,
        parameters=self.parameters,
        arg_ssa_iter=arg_ssa_names,
        module_type=self.module_type,
    )
    printer.print_op_attributes(
        self.attributes,
        reserved_attr_names=_MODULE_OP_ATTRS_HANDLED_BY_CUSTOM_FORMAT,
        print_keyword=True,
    )

InstanceOp

Bases: IRDLOperation

This represents an instance of a module. The inputs and outputs are the referenced module's inputs and outputs. The argNames and resultNames attributes must match the referenced module's input and output names.

Source code in xdsl/dialects/hw.py
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
@irdl_op_definition
class InstanceOp(IRDLOperation):
    """
    This represents an instance of a module. The inputs and outputs are the
    referenced module's inputs and outputs. The argNames and resultNames
    attributes must match the referenced module's input and output names.
    """

    name = "hw.instance"

    instance_name = attr_def(StringAttr, attr_name="instanceName")
    module_name = attr_def(FlatSymbolRefAttrConstr, attr_name="moduleName")
    inputs = var_operand_def()
    outputs = var_result_def()
    arg_names = attr_def(ArrayAttr[StringAttr], attr_name="argNames")
    result_names = attr_def(ArrayAttr[StringAttr], attr_name="resultNames")
    inner_sym = opt_attr_def(InnerSymAttr)

    def __init__(
        self,
        instance_name: str,
        module_name: FlatSymbolRefAttr,
        inputs: Iterable[tuple[str, SSAValue]],
        outputs: Iterable[tuple[str, TypeAttribute]],
        inner_sym: InnerSymAttr | None = None,
    ):
        arg_names = ArrayAttr(StringAttr(port[0]) for port in inputs)
        result_names = ArrayAttr(StringAttr(port[0]) for port in outputs)
        attributes: dict[str, Attribute] = {
            "instanceName": StringAttr(instance_name),
            "moduleName": module_name,
            "argNames": arg_names,
            "resultNames": result_names,
        }
        if inner_sym is not None:
            attributes["inner_sym"] = inner_sym
        super().__init__(
            operands=(tuple(port[1] for port in inputs),),
            result_types=(tuple(port[1] for port in outputs),),
            attributes=attributes,
        )

    def verify_(self) -> None:
        if len(self.arg_names.data) != len(self.inputs):
            raise VerifyException(
                "Instance has a different amount of argument names "
                f"({len(self.arg_names.data)}) "
                f"and arguments ({len(self.inputs)})"
            )
        if len(self.result_names.data) != len(self.outputs):
            raise VerifyException(
                "Instance has a different amount of result names "
                f"({len(self.result_names.data)}) "
                f"and results ({len(self.outputs)})"
            )

        module = SymbolTable.lookup_symbol(self, self.module_name)
        if module is None:
            raise VerifyException(f"Module {self.module_name} not found")

        hw_module_like = module.get_trait(HWModuleLike)
        if hw_module_like is None:
            raise VerifyException(
                f"Module {self.module_name} must be a HWModuleLike, "
                f"found '{module.name}'"
            )

        def check_same_or_exception(
            reference: Iterable[str], candidate: Iterable[str], kind: str
        ):
            reference_set = set(reference)
            visited: set[str] = set()
            for candidate in candidate:
                if candidate in visited:
                    raise VerifyException(
                        f"Multiple definitions for {kind} '{candidate}'"
                    )
                visited.add(candidate)
                if candidate not in reference_set:
                    raise VerifyException(f"Unknown {kind} '{candidate}'")
                reference_set.remove(candidate)
            if len(reference_set) != 0:
                raise VerifyException(f"Missing {kind} '{reference_set.pop()}'")

        module_args = (
            port.port_name.data
            for port in hw_module_like.get_hw_module_type(module).ports
            if port.dir.data.is_input_like()
        )
        result_args = (
            port.port_name.data
            for port in hw_module_like.get_hw_module_type(module).ports
            if port.dir.data.is_output_like()
        )

        check_same_or_exception(
            module_args, (arg.data for arg in self.arg_names.data), "input port"
        )

        check_same_or_exception(
            result_args,
            (result.data for result in self.result_names.data),
            "output port",
        )

    @classmethod
    def parse(cls, parser: Parser) -> InstanceOp:
        instance_name = parser.parse_str_literal(" (instance name)")
        inner_sym = None
        if parser.parse_optional_keyword("sym") is not None:
            inner_sym = parser.parse_attribute()
            if not isinstance(inner_sym, InnerSymAttr):
                parser.raise_error("Expected inner symbol attribute")
        module_name = parser.parse_attribute()
        if (
            not isinstance(module_name, SymbolRefAttr)
            or len(module_name.nested_references.data) != 0
        ):
            parser.raise_error("Expected flat symbol reference")
        if parser.parse_optional_punctuation("<") is not None:
            parser.raise_error("Instance parameters are not supported yet")

        def parse_input_port():
            port_name = (
                parser.parse_optional_str_literal()
                or parser.parse_optional_identifier()
            )
            if port_name is None:
                parser.raise_error("Expected port name as identifier or string literal")
            parser.parse_punctuation(":")
            port_operand = parser.parse_unresolved_operand()
            parser.parse_punctuation(":")
            port_type = parser.parse_type()
            port_value = parser.resolve_operand(port_operand, port_type)
            return (port_name, port_value)

        def parse_output_port():
            port_name = (
                parser.parse_optional_str_literal()
                or parser.parse_optional_identifier()
            )
            if port_name is None:
                parser.raise_error("Expected port name as identifier or string literal")
            parser.parse_punctuation(":")
            port_type = parser.parse_type()
            return (port_name, port_type)

        input_ports = parser.parse_comma_separated_list(
            Parser.Delimiter.PAREN, parse_input_port, "input port list expected"
        )
        parser.parse_punctuation("->")
        output_ports = parser.parse_comma_separated_list(
            Parser.Delimiter.PAREN, parse_output_port, "output port list expected"
        )
        attributes_attr = parser.parse_optional_attr_dict_with_reserved_attr_names(
            (
                "instanceName",
                "moduleName",
                "argNames",
                "resultNames",
                "inner_sym",
            )
        )
        attributes = dict(attributes_attr.data) if attributes_attr is not None else {}

        operands = tuple(port[1] for port in input_ports)
        result_types = tuple(port[1] for port in output_ports)
        attributes["instanceName"] = StringAttr(instance_name)
        attributes["moduleName"] = module_name
        attributes["argNames"] = ArrayAttr(StringAttr(port[0]) for port in input_ports)
        attributes["resultNames"] = ArrayAttr(
            StringAttr(port[0]) for port in output_ports
        )
        if inner_sym is not None:
            attributes["inner_sym"] = inner_sym
        return cls.create(
            operands=operands, result_types=result_types, attributes=attributes
        )

    def print(self, printer: Printer) -> None:
        printer.print_string(" ")
        printer.print_attribute(self.instance_name)
        printer.print_string(" ")
        if self.inner_sym is not None:
            printer.print_string("sym ")
            printer.print_attribute(self.inner_sym)
            printer.print_string(" ")
        printer.print_attribute(self.module_name)

        def print_input_port(name: str, operand: SSAValue):
            printer.print_identifier_or_string_literal(name)
            printer.print_string(": ")
            printer.print_operand(operand)
            printer.print_string(": ")
            printer.print_attribute(operand.type)

        def print_output_port(name: str, port_type: Attribute):
            printer.print_identifier_or_string_literal(name)
            printer.print_string(": ")
            printer.print_attribute(port_type)

        with printer.in_parens():
            printer.print_list(
                zip((name.data for name in self.arg_names), self.operands),
                lambda x: print_input_port(*x),
            )
        printer.print_string(" -> ")
        with printer.in_parens():
            printer.print_list(
                zip(
                    (name.data for name in self.result_names),
                    self.result_types,
                ),
                lambda x: print_output_port(*x),
            )
        printer.print_op_attributes(
            self.attributes,
            reserved_attr_names=(
                "instanceName",
                "moduleName",
                "argNames",
                "resultNames",
                "inner_sym",
            ),
        )

name = 'hw.instance' class-attribute instance-attribute

instance_name = attr_def(StringAttr, attr_name='instanceName') class-attribute instance-attribute

module_name = attr_def(FlatSymbolRefAttrConstr, attr_name='moduleName') class-attribute instance-attribute

inputs = var_operand_def() class-attribute instance-attribute

outputs = var_result_def() class-attribute instance-attribute

arg_names = attr_def(ArrayAttr[StringAttr], attr_name='argNames') class-attribute instance-attribute

result_names = attr_def(ArrayAttr[StringAttr], attr_name='resultNames') class-attribute instance-attribute

inner_sym = opt_attr_def(InnerSymAttr) class-attribute instance-attribute

__init__(instance_name: str, module_name: FlatSymbolRefAttr, inputs: Iterable[tuple[str, SSAValue]], outputs: Iterable[tuple[str, TypeAttribute]], inner_sym: InnerSymAttr | None = None)

Source code in xdsl/dialects/hw.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
def __init__(
    self,
    instance_name: str,
    module_name: FlatSymbolRefAttr,
    inputs: Iterable[tuple[str, SSAValue]],
    outputs: Iterable[tuple[str, TypeAttribute]],
    inner_sym: InnerSymAttr | None = None,
):
    arg_names = ArrayAttr(StringAttr(port[0]) for port in inputs)
    result_names = ArrayAttr(StringAttr(port[0]) for port in outputs)
    attributes: dict[str, Attribute] = {
        "instanceName": StringAttr(instance_name),
        "moduleName": module_name,
        "argNames": arg_names,
        "resultNames": result_names,
    }
    if inner_sym is not None:
        attributes["inner_sym"] = inner_sym
    super().__init__(
        operands=(tuple(port[1] for port in inputs),),
        result_types=(tuple(port[1] for port in outputs),),
        attributes=attributes,
    )

verify_() -> None

Source code in xdsl/dialects/hw.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
def verify_(self) -> None:
    if len(self.arg_names.data) != len(self.inputs):
        raise VerifyException(
            "Instance has a different amount of argument names "
            f"({len(self.arg_names.data)}) "
            f"and arguments ({len(self.inputs)})"
        )
    if len(self.result_names.data) != len(self.outputs):
        raise VerifyException(
            "Instance has a different amount of result names "
            f"({len(self.result_names.data)}) "
            f"and results ({len(self.outputs)})"
        )

    module = SymbolTable.lookup_symbol(self, self.module_name)
    if module is None:
        raise VerifyException(f"Module {self.module_name} not found")

    hw_module_like = module.get_trait(HWModuleLike)
    if hw_module_like is None:
        raise VerifyException(
            f"Module {self.module_name} must be a HWModuleLike, "
            f"found '{module.name}'"
        )

    def check_same_or_exception(
        reference: Iterable[str], candidate: Iterable[str], kind: str
    ):
        reference_set = set(reference)
        visited: set[str] = set()
        for candidate in candidate:
            if candidate in visited:
                raise VerifyException(
                    f"Multiple definitions for {kind} '{candidate}'"
                )
            visited.add(candidate)
            if candidate not in reference_set:
                raise VerifyException(f"Unknown {kind} '{candidate}'")
            reference_set.remove(candidate)
        if len(reference_set) != 0:
            raise VerifyException(f"Missing {kind} '{reference_set.pop()}'")

    module_args = (
        port.port_name.data
        for port in hw_module_like.get_hw_module_type(module).ports
        if port.dir.data.is_input_like()
    )
    result_args = (
        port.port_name.data
        for port in hw_module_like.get_hw_module_type(module).ports
        if port.dir.data.is_output_like()
    )

    check_same_or_exception(
        module_args, (arg.data for arg in self.arg_names.data), "input port"
    )

    check_same_or_exception(
        result_args,
        (result.data for result in self.result_names.data),
        "output port",
    )

parse(parser: Parser) -> InstanceOp classmethod

Source code in xdsl/dialects/hw.py
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
@classmethod
def parse(cls, parser: Parser) -> InstanceOp:
    instance_name = parser.parse_str_literal(" (instance name)")
    inner_sym = None
    if parser.parse_optional_keyword("sym") is not None:
        inner_sym = parser.parse_attribute()
        if not isinstance(inner_sym, InnerSymAttr):
            parser.raise_error("Expected inner symbol attribute")
    module_name = parser.parse_attribute()
    if (
        not isinstance(module_name, SymbolRefAttr)
        or len(module_name.nested_references.data) != 0
    ):
        parser.raise_error("Expected flat symbol reference")
    if parser.parse_optional_punctuation("<") is not None:
        parser.raise_error("Instance parameters are not supported yet")

    def parse_input_port():
        port_name = (
            parser.parse_optional_str_literal()
            or parser.parse_optional_identifier()
        )
        if port_name is None:
            parser.raise_error("Expected port name as identifier or string literal")
        parser.parse_punctuation(":")
        port_operand = parser.parse_unresolved_operand()
        parser.parse_punctuation(":")
        port_type = parser.parse_type()
        port_value = parser.resolve_operand(port_operand, port_type)
        return (port_name, port_value)

    def parse_output_port():
        port_name = (
            parser.parse_optional_str_literal()
            or parser.parse_optional_identifier()
        )
        if port_name is None:
            parser.raise_error("Expected port name as identifier or string literal")
        parser.parse_punctuation(":")
        port_type = parser.parse_type()
        return (port_name, port_type)

    input_ports = parser.parse_comma_separated_list(
        Parser.Delimiter.PAREN, parse_input_port, "input port list expected"
    )
    parser.parse_punctuation("->")
    output_ports = parser.parse_comma_separated_list(
        Parser.Delimiter.PAREN, parse_output_port, "output port list expected"
    )
    attributes_attr = parser.parse_optional_attr_dict_with_reserved_attr_names(
        (
            "instanceName",
            "moduleName",
            "argNames",
            "resultNames",
            "inner_sym",
        )
    )
    attributes = dict(attributes_attr.data) if attributes_attr is not None else {}

    operands = tuple(port[1] for port in input_ports)
    result_types = tuple(port[1] for port in output_ports)
    attributes["instanceName"] = StringAttr(instance_name)
    attributes["moduleName"] = module_name
    attributes["argNames"] = ArrayAttr(StringAttr(port[0]) for port in input_ports)
    attributes["resultNames"] = ArrayAttr(
        StringAttr(port[0]) for port in output_ports
    )
    if inner_sym is not None:
        attributes["inner_sym"] = inner_sym
    return cls.create(
        operands=operands, result_types=result_types, attributes=attributes
    )

print(printer: Printer) -> None

Source code in xdsl/dialects/hw.py
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
def print(self, printer: Printer) -> None:
    printer.print_string(" ")
    printer.print_attribute(self.instance_name)
    printer.print_string(" ")
    if self.inner_sym is not None:
        printer.print_string("sym ")
        printer.print_attribute(self.inner_sym)
        printer.print_string(" ")
    printer.print_attribute(self.module_name)

    def print_input_port(name: str, operand: SSAValue):
        printer.print_identifier_or_string_literal(name)
        printer.print_string(": ")
        printer.print_operand(operand)
        printer.print_string(": ")
        printer.print_attribute(operand.type)

    def print_output_port(name: str, port_type: Attribute):
        printer.print_identifier_or_string_literal(name)
        printer.print_string(": ")
        printer.print_attribute(port_type)

    with printer.in_parens():
        printer.print_list(
            zip((name.data for name in self.arg_names), self.operands),
            lambda x: print_input_port(*x),
        )
    printer.print_string(" -> ")
    with printer.in_parens():
        printer.print_list(
            zip(
                (name.data for name in self.result_names),
                self.result_types,
            ),
            lambda x: print_output_port(*x),
        )
    printer.print_op_attributes(
        self.attributes,
        reserved_attr_names=(
            "instanceName",
            "moduleName",
            "argNames",
            "resultNames",
            "inner_sym",
        ),
    )

OutputOp

Bases: IRDLOperation

Source code in xdsl/dialects/hw.py
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
@irdl_op_definition
class OutputOp(IRDLOperation):
    name = "hw.output"

    inputs = var_operand_def()

    traits = traits_def(IsTerminator(), HasParent(HWModuleOp))

    def __init__(self, ops: Sequence[SSAValue | Operation]):
        super().__init__(operands=[ops])

    def verify_(self) -> None:
        parent = self.parent_op()
        assert isinstance(parent, HWModuleOp)

        expected_results = tuple(
            port.type
            for port in parent.module_type.ports.data
            if port.dir.data == Direction.OUTPUT
        )

        if len(expected_results) != len(self.inputs):
            raise VerifyException(
                f"wrong amount of output values (expected {len(expected_results)}, got {len(self.inputs)})"
            )

        for i, (got, expected) in enumerate(zip(self.inputs, expected_results)):
            if got.type != expected:
                raise VerifyException(
                    f"output #{i} is of unexpected type (expected {expected}, got {got.type})"
                )

    @classmethod
    def parse(cls, parser: Parser) -> OutputOp:
        operands = parser.parse_optional_undelimited_comma_separated_list(
            parser.parse_optional_unresolved_operand, parser.parse_unresolved_operand
        )
        if operands is None:
            return cls(())

        parser.parse_punctuation(":")
        types = parser.parse_comma_separated_list(
            parser.Delimiter.NONE, parser.parse_attribute
        )
        operands = parser.resolve_operands(operands, types, parser.pos)
        return cls(operands)

    def print(self, printer: Printer):
        if len(self.inputs) == 0:
            return

        printer.print_string(" ")
        printer.print_list(self.inputs, printer.print_operand)
        printer.print_string(" : ")
        printer.print_list(self.inputs.types, printer.print_attribute)

name = 'hw.output' class-attribute instance-attribute

inputs = var_operand_def() class-attribute instance-attribute

traits = traits_def(IsTerminator(), HasParent(HWModuleOp)) class-attribute instance-attribute

__init__(ops: Sequence[SSAValue | Operation])

Source code in xdsl/dialects/hw.py
1326
1327
def __init__(self, ops: Sequence[SSAValue | Operation]):
    super().__init__(operands=[ops])

verify_() -> None

Source code in xdsl/dialects/hw.py
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
def verify_(self) -> None:
    parent = self.parent_op()
    assert isinstance(parent, HWModuleOp)

    expected_results = tuple(
        port.type
        for port in parent.module_type.ports.data
        if port.dir.data == Direction.OUTPUT
    )

    if len(expected_results) != len(self.inputs):
        raise VerifyException(
            f"wrong amount of output values (expected {len(expected_results)}, got {len(self.inputs)})"
        )

    for i, (got, expected) in enumerate(zip(self.inputs, expected_results)):
        if got.type != expected:
            raise VerifyException(
                f"output #{i} is of unexpected type (expected {expected}, got {got.type})"
            )

parse(parser: Parser) -> OutputOp classmethod

Source code in xdsl/dialects/hw.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
@classmethod
def parse(cls, parser: Parser) -> OutputOp:
    operands = parser.parse_optional_undelimited_comma_separated_list(
        parser.parse_optional_unresolved_operand, parser.parse_unresolved_operand
    )
    if operands is None:
        return cls(())

    parser.parse_punctuation(":")
    types = parser.parse_comma_separated_list(
        parser.Delimiter.NONE, parser.parse_attribute
    )
    operands = parser.resolve_operands(operands, types, parser.pos)
    return cls(operands)

print(printer: Printer)

Source code in xdsl/dialects/hw.py
1365
1366
1367
1368
1369
1370
1371
1372
def print(self, printer: Printer):
    if len(self.inputs) == 0:
        return

    printer.print_string(" ")
    printer.print_list(self.inputs, printer.print_operand)
    printer.print_string(" : ")
    printer.print_list(self.inputs.types, printer.print_attribute)

ArrayCreateOp

Bases: IRDLOperation

Create an array from values. Creates an array from a variable set of values. One or more values must be listed.

Source code in xdsl/dialects/hw.py
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@irdl_op_definition
class ArrayCreateOp(IRDLOperation):
    """
    Create an array from values.
    Creates an array from a variable set of values. One or more values must be listed.
    """

    I: ClassVar = VarConstraint("I", AnyAttr())  # Constrain all types to be equal

    name = "hw.array_create"
    inputs = var_operand_def(RangeOf(I).of_length(AtLeast(1)))
    result = result_def(ArrayType)

    def __init__(
        self, first_input: Operation | SSAValue, *other_inputs: Operation | SSAValue
    ):
        inputs = (first_input, *other_inputs)
        el_type = SSAValue.get(
            first_input, type=AnySignlessIntegerType | ArrayType
        ).type
        out_type = ArrayType(el_type, len(inputs))
        super().__init__(operands=(inputs,), result_types=[out_type])

    def print(self, printer: Printer):
        printer.print_string(" ")
        printer.print_list(self.inputs, printer.print_operand)
        printer.print_string(" : ")
        printer.print_attribute(self.inputs[0].type)

    @classmethod
    def parse(cls, parser: Parser) -> ArrayCreateOp:
        operands = parser.parse_comma_separated_list(
            parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        in_type = parser.parse_type()
        types = [in_type for _ in range(len(operands))]
        operands = parser.resolve_operands(operands, types, parser.pos)
        return cls(*operands)

I: ClassVar = VarConstraint('I', AnyAttr()) class-attribute instance-attribute

name = 'hw.array_create' class-attribute instance-attribute

inputs = var_operand_def(RangeOf(I).of_length(AtLeast(1))) class-attribute instance-attribute

result = result_def(ArrayType) class-attribute instance-attribute

__init__(first_input: Operation | SSAValue, *other_inputs: Operation | SSAValue)

Source code in xdsl/dialects/hw.py
1388
1389
1390
1391
1392
1393
1394
1395
1396
def __init__(
    self, first_input: Operation | SSAValue, *other_inputs: Operation | SSAValue
):
    inputs = (first_input, *other_inputs)
    el_type = SSAValue.get(
        first_input, type=AnySignlessIntegerType | ArrayType
    ).type
    out_type = ArrayType(el_type, len(inputs))
    super().__init__(operands=(inputs,), result_types=[out_type])

print(printer: Printer)

Source code in xdsl/dialects/hw.py
1398
1399
1400
1401
1402
def print(self, printer: Printer):
    printer.print_string(" ")
    printer.print_list(self.inputs, printer.print_operand)
    printer.print_string(" : ")
    printer.print_attribute(self.inputs[0].type)

parse(parser: Parser) -> ArrayCreateOp classmethod

Source code in xdsl/dialects/hw.py
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@classmethod
def parse(cls, parser: Parser) -> ArrayCreateOp:
    operands = parser.parse_comma_separated_list(
        parser.Delimiter.NONE, parser.parse_unresolved_operand
    )
    parser.parse_punctuation(":")
    in_type = parser.parse_type()
    types = [in_type for _ in range(len(operands))]
    operands = parser.resolve_operands(operands, types, parser.pos)
    return cls(*operands)

ArrayGetOp

Bases: IRDLOperation

Extract an element from an array Extracts the element at index from the given input array. The index must be exactly ceil(log2(length(input))) bits wide.

Source code in xdsl/dialects/hw.py
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
@irdl_op_definition
class ArrayGetOp(IRDLOperation):
    """
    Extract an element from an array
    Extracts the element at index from the given input array.
    The index must be exactly ceil(log2(length(input))) bits wide.
    """

    name = "hw.array_get"
    input = operand_def(ArrayType)
    index = operand_def(IntegerType)
    result = result_def(IntegerType)

    def __init__(self, input: Operation | SSAValue, index: Operation | SSAValue):
        typ = SSAValue.get(input, type=ArrayType).type
        assert isinstance(typ, ArrayType)
        out_type = typ.get_element_type()
        super().__init__(operands=[input, index], result_types=[out_type])

    def verify_(self) -> None:
        input_typ = cast(ArrayType, self.input.type)  # Checked by IRDL
        index_typ = cast(IntegerType, self.index.type)  # Checked by IRDL
        index_width = index_typ.bitwidth
        shape_width = (len(input_typ) - 1).bit_length()
        if index_width != shape_width:
            raise VerifyException(
                f"The index ({index_width} bits wide) must be exactly ceil(log2(length(input))) = {shape_width} bits wide"
            )

    def print(self, printer: Printer):
        printer.print_string(" ")
        printer.print_operand(self.input)
        with printer.in_square_brackets():
            printer.print_operand(self.index)
        printer.print_string(" : ")
        printer.print_attribute(self.input.type)
        printer.print_string(", ")
        printer.print_attribute(self.index.type)

    @classmethod
    def parse(cls, parser: Parser) -> ArrayGetOp:
        input = parser.parse_unresolved_operand()
        parser.parse_punctuation("[")
        index = parser.parse_unresolved_operand()
        parser.parse_punctuation("]")
        parser.parse_punctuation(":")
        input_type = parser.parse_type()
        parser.parse_punctuation(",")
        index_type = parser.parse_type()
        operands = parser.resolve_operands(
            [input, index], [input_type, index_type], parser.pos
        )
        return cls(operands[0], operands[1])

name = 'hw.array_get' class-attribute instance-attribute

input = operand_def(ArrayType) class-attribute instance-attribute

index = operand_def(IntegerType) class-attribute instance-attribute

result = result_def(IntegerType) class-attribute instance-attribute

__init__(input: Operation | SSAValue, index: Operation | SSAValue)

Source code in xdsl/dialects/hw.py
1429
1430
1431
1432
1433
def __init__(self, input: Operation | SSAValue, index: Operation | SSAValue):
    typ = SSAValue.get(input, type=ArrayType).type
    assert isinstance(typ, ArrayType)
    out_type = typ.get_element_type()
    super().__init__(operands=[input, index], result_types=[out_type])

verify_() -> None

Source code in xdsl/dialects/hw.py
1435
1436
1437
1438
1439
1440
1441
1442
1443
def verify_(self) -> None:
    input_typ = cast(ArrayType, self.input.type)  # Checked by IRDL
    index_typ = cast(IntegerType, self.index.type)  # Checked by IRDL
    index_width = index_typ.bitwidth
    shape_width = (len(input_typ) - 1).bit_length()
    if index_width != shape_width:
        raise VerifyException(
            f"The index ({index_width} bits wide) must be exactly ceil(log2(length(input))) = {shape_width} bits wide"
        )

print(printer: Printer)

Source code in xdsl/dialects/hw.py
1445
1446
1447
1448
1449
1450
1451
1452
1453
def print(self, printer: Printer):
    printer.print_string(" ")
    printer.print_operand(self.input)
    with printer.in_square_brackets():
        printer.print_operand(self.index)
    printer.print_string(" : ")
    printer.print_attribute(self.input.type)
    printer.print_string(", ")
    printer.print_attribute(self.index.type)

parse(parser: Parser) -> ArrayGetOp classmethod

Source code in xdsl/dialects/hw.py
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
@classmethod
def parse(cls, parser: Parser) -> ArrayGetOp:
    input = parser.parse_unresolved_operand()
    parser.parse_punctuation("[")
    index = parser.parse_unresolved_operand()
    parser.parse_punctuation("]")
    parser.parse_punctuation(":")
    input_type = parser.parse_type()
    parser.parse_punctuation(",")
    index_type = parser.parse_type()
    operands = parser.resolve_operands(
        [input, index], [input_type, index_type], parser.pos
    )
    return cls(operands[0], operands[1])

BitcastOp

Bases: IRDLOperation

Source code in xdsl/dialects/hw.py
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
@irdl_op_definition
class BitcastOp(IRDLOperation):
    name = "hw.bitcast"

    input = operand_def()
    result = result_def()

    assembly_format = "$input attr-dict `:` functional-type($input, $result)"

    def __init__(self, inp: SSAValue | Operation, out_t: Attribute):
        super().__init__(
            operands=[SSAValue.get(inp)],
            result_types=[out_t],
        )

name = 'hw.bitcast' class-attribute instance-attribute

input = operand_def() class-attribute instance-attribute

result = result_def() class-attribute instance-attribute

assembly_format = '$input attr-dict `:` functional-type($input, $result)' class-attribute instance-attribute

__init__(inp: SSAValue | Operation, out_t: Attribute)

Source code in xdsl/dialects/hw.py
1480
1481
1482
1483
1484
def __init__(self, inp: SSAValue | Operation, out_t: Attribute):
    super().__init__(
        operands=[SSAValue.get(inp)],
        result_types=[out_t],
    )

print_module_header(*, printer: Printer, visibility: StringAttr | None, module_name: StringAttr, parameters: ArrayAttr[ParamDeclAttr] | None, arg_ssa_iter: Iterable[SSAValue | str], module_type: ModuleType)

Prints the common header of a module. The arg_ssa_iter parameter provides the SSA names to be used for input-like parameters, either using the print name of an SSA value, or a string decided beforehand.

Source code in xdsl/dialects/hw.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
def print_module_header(
    *,
    printer: Printer,
    visibility: StringAttr | None,
    module_name: StringAttr,
    parameters: ArrayAttr[ParamDeclAttr] | None,
    arg_ssa_iter: Iterable[SSAValue | str],
    module_type: ModuleType,
):
    """
    Prints the common header of a module.
    The `arg_ssa_iter` parameter provides the SSA names to be
    used for input-like parameters, either using the print
    name of an SSA value, or a string decided beforehand.
    """
    if visibility is not None:
        printer.print_string(" ")
        printer.print_string(visibility.data)
    printer.print_string(" ")
    printer.print_symbol_name(module_name.data)

    # Print parameters
    if parameters is not None and len(parameters.data) != 0:
        with printer.in_angle_brackets():
            printer.print_list(
                parameters.data,
                lambda x: x.print_free_standing_parameters(printer),
            )

    arg_iter = iter(arg_ssa_iter)

    def print_port(port: ModulePort):
        ssa_arg = next(arg_iter) if port.dir.data.is_input_like() else None
        port.dir.data.print(printer, short=True)
        printer.print_string(" ")

        # Print argument
        if ssa_arg is not None:
            if isinstance(ssa_arg, SSAValue):
                used_name = printer.print_ssa_value(ssa_arg)
            else:
                assert isinstance(ssa_arg, str)
                printer.print_string("%")
                printer.print_string(ssa_arg)
                used_name = ssa_arg
            if port.port_name.data != used_name:
                printer.print_string(" ")
                printer.print_identifier_or_string_literal(port.port_name.data)
        else:
            printer.print_identifier_or_string_literal(port.port_name.data)
        printer.print_string(": ")
        printer.print_attribute(port.type)

    with printer.in_parens():
        printer.print_list(module_type.ports.data, print_port)