CIRCT 24.0.0git
Loading...
Searching...
No Matches
FIRRTLTypes.cpp
Go to the documentation of this file.
1//===- FIRRTLTypes.cpp - Implement the FIRRTL dialect type system ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implement the FIRRTL dialect type system.
10//
11//===----------------------------------------------------------------------===//
12
17#include "mlir/IR/DialectImplementation.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/StringSwitch.h"
20#include "llvm/ADT/TypeSwitch.h"
21
22using namespace circt;
23using namespace firrtl;
24
25using mlir::OptionalParseResult;
26using mlir::TypeStorageAllocator;
27
28//===----------------------------------------------------------------------===//
29// TableGen generated logic.
30//===----------------------------------------------------------------------===//
31
32// Provide the autogenerated implementation for types.
33#define GET_TYPEDEF_CLASSES
34#include "circt/Dialect/FIRRTL/FIRRTLTypes.cpp.inc"
35
36//===----------------------------------------------------------------------===//
37// Type Printing
38//===----------------------------------------------------------------------===//
39
40// NOLINTBEGIN(misc-no-recursion)
41/// Print a type with a custom printer implementation.
42///
43/// This only prints a subset of all types in the dialect. Use `printNestedType`
44/// instead, which will call this function in turn, as appropriate.
45static LogicalResult customTypePrinter(Type type, AsmPrinter &os) {
46 if (isConst(type))
47 os << "const.";
48
49 auto printWidthQualifier = [&](std::optional<int32_t> width) {
50 if (width)
51 os << '<' << *width << '>';
52 };
53 bool anyFailed = false;
54 TypeSwitch<Type>(type)
55 .Case<ClockType>([&](auto) { os << "clock"; })
56 .Case<ResetType>([&](auto) { os << "reset"; })
57 .Case<AsyncResetType>([&](auto) { os << "asyncreset"; })
58 .Case<SIntType>([&](auto sIntType) {
59 os << "sint";
60 printWidthQualifier(sIntType.getWidth());
61 })
62 .Case<UIntType>([&](auto uIntType) {
63 os << "uint";
64 printWidthQualifier(uIntType.getWidth());
65 })
66 .Case<AnalogType>([&](auto analogType) {
67 os << "analog";
68 printWidthQualifier(analogType.getWidth());
69 })
70 .Case<BundleType, OpenBundleType>([&](auto bundleType) {
72 os << "open";
73 os << "bundle<";
74 llvm::interleaveComma(bundleType, os, [&](auto element) {
75 StringRef fieldName = element.name.getValue();
76 bool isLiteralIdentifier =
77 !fieldName.empty() && llvm::isDigit(fieldName.front());
78 if (isLiteralIdentifier)
79 os << "\"";
80 os << element.name.getValue();
81 if (isLiteralIdentifier)
82 os << "\"";
83 if (element.isFlip)
84 os << " flip";
85 os << ": ";
86 printNestedType(element.type, os);
87 });
88 os << '>';
89 })
90 .Case<FEnumType>([&](auto fenumType) {
91 os << "enum<";
92 std::optional<APInt> previous;
93 llvm::interleaveComma(
94 fenumType, os, [&](FEnumType::EnumElement element) {
95 // Print the variant name.
96 os << element.name.getValue();
97
98 // Print the variant value.
99 auto value = element.value.getValue();
100 if (previous) {
101 // This APInt should have enough space to
102 // safely add 1 without overflowing.
103 *previous += 1;
104 if (value != previous) {
105 os << " = ";
106 os.printAttributeWithoutType(element.value);
107 }
108 } else if (!element.value.getValue().isZero()) {
109 os << " = ";
110 os.printAttributeWithoutType(element.value);
111 }
112 previous = value;
113
114 // Print the data type.
115 bool skipType = false;
116 if (auto type = dyn_cast<UIntType>(element.type))
117 if (type.getWidth() == 0)
118 skipType = true;
119 if (!skipType) {
120 os << ": ";
121 printNestedType(element.type, os);
122 }
123 });
124 os << '>';
125 })
126 .Case<FVectorType, OpenVectorType>([&](auto vectorType) {
127 if (firrtl::type_isa<OpenVectorType>(vectorType))
128 os << "open";
129 os << "vector<";
130 printNestedType(vectorType.getElementType(), os);
131 os << ", " << vectorType.getNumElements() << '>';
132 })
133 .Case<RefType>([&](RefType refType) {
134 if (refType.getForceable())
135 os << "rw";
136 os << "probe<";
137 printNestedType(refType.getType(), os);
138 if (auto layer = refType.getLayer())
139 os << ", " << layer;
140 os << '>';
141 })
142 .Case<LHSType>([&](LHSType lhstype) {
143 os << "lhs<";
144 printNestedType(lhstype.getType(), os);
145 os << ">";
146 })
147 .Case<StringType>([&](auto stringType) { os << "string"; })
148 .Case<FIntegerType>([&](auto integerType) { os << "integer"; })
149 .Case<BoolType>([&](auto boolType) { os << "bool"; })
150 .Case<DoubleType>([&](auto doubleType) { os << "double"; })
151 .Case<ListType>([&](auto listType) {
152 os << "list<";
153 printNestedType(listType.getElementType(), os);
154 os << '>';
155 })
156 .Case([&](OptionType optionType) {
157 os << "option<";
158 printNestedType(optionType.getElementType(), os);
159 os << '>';
160 })
161 .Case<RegistryType>([&](auto registryType) {
162 os << "registry<";
163 printNestedType(registryType.getElementType(), os);
164 os << '>';
165 })
166 .Case<PathType>([&](auto pathType) { os << "path"; })
167 .Case<BaseTypeAliasType>([&](BaseTypeAliasType alias) {
168 os << "alias<" << alias.getName().getValue() << ", ";
169 printNestedType(alias.getInnerType(), os);
170 os << '>';
171 })
172 .Case<ClassType>([&](ClassType type) {
173 os << "class<";
174 type.printInterface(os);
175 os << ">";
176 })
177 .Case<AnyRefType>([&](AnyRefType type) { os << "anyref"; })
178 .Case<FStringType>([&](auto) { os << "fstring"; })
179 .Case<DomainType>([&](DomainType type) {
180 os << "domain<";
181 os.printSymbolName(type.getName().getValue());
182 os << "(";
183 llvm::interleaveComma(type.getFields(), os, [&](Attribute attr) {
184 auto field = cast<DomainFieldAttr>(attr);
185 os << field.getName().getValue() << ": ";
186 os.printType(field.getType());
187 });
188 os << ")";
189 os << ">";
190 })
191 .Default([&](auto) { anyFailed = true; });
192 return failure(anyFailed);
193}
194// NOLINTEND(misc-no-recursion)
195
196/// Print a type defined by this dialect.
197void circt::firrtl::printNestedType(Type type, AsmPrinter &os) {
198 // Try the custom type printer.
199 if (succeeded(customTypePrinter(type, os)))
200 return;
201
202 // None of the above recognized the type, so we bail.
203 assert(false && "type to print unknown to FIRRTL dialect");
204}
205
206//===----------------------------------------------------------------------===//
207// Type Parsing
208//===----------------------------------------------------------------------===//
209
210/// Parse a type with a custom parser implementation.
211///
212/// This only accepts a subset of all types in the dialect. Use `parseType`
213/// instead, which will call this function in turn, as appropriate.
214///
215/// Returns `std::nullopt` if the type `name` is not covered by the custom
216/// parsers. Otherwise returns success or failure as appropriate. On success,
217/// `result` is set to the resulting type.
218///
219/// ```plain
220/// firrtl-type
221/// ::= clock
222/// ::= reset
223/// ::= asyncreset
224/// ::= sint ('<' int '>')?
225/// ::= uint ('<' int '>')?
226/// ::= analog ('<' int '>')?
227/// ::= bundle '<' (bundle-elt (',' bundle-elt)*)? '>'
228/// ::= enum '<' (enum-elt (',' enum-elt)*)? '>'
229/// ::= vector '<' type ',' int '>'
230/// ::= const '.' type
231/// ::= 'property.' firrtl-phased-type
232/// bundle-elt ::= identifier flip? ':' type
233/// enum-elt ::= identifier ':' type
234/// ```
235static OptionalParseResult customTypeParser(AsmParser &parser, StringRef name,
236 Type &result) {
237 bool isConst = false;
238 const char constPrefix[] = "const.";
239 if (name.starts_with(constPrefix)) {
240 isConst = true;
241 name = name.drop_front(std::size(constPrefix) - 1);
242 }
243
244 auto *context = parser.getContext();
245 if (name == "clock")
246 return result = ClockType::get(context, isConst), success();
247 if (name == "reset")
248 return result = ResetType::get(context, isConst), success();
249 if (name == "asyncreset")
250 return result = AsyncResetType::get(context, isConst), success();
251
252 if (name == "sint" || name == "uint" || name == "analog") {
253 // Parse the width specifier if it exists.
254 int32_t width = -1;
255 if (!parser.parseOptionalLess()) {
256 if (parser.parseInteger(width) || parser.parseGreater())
257 return failure();
258
259 if (width < 0)
260 return parser.emitError(parser.getNameLoc(), "unknown width"),
261 failure();
262 }
263
264 if (name == "sint")
265 result = SIntType::get(context, width, isConst);
266 else if (name == "uint")
267 result = UIntType::get(context, width, isConst);
268 else {
269 assert(name == "analog");
270 result = AnalogType::get(context, width, isConst);
271 }
272 return success();
273 }
274
275 if (name == "bundle") {
276 SmallVector<BundleType::BundleElement, 4> elements;
277
278 auto parseBundleElement = [&]() -> ParseResult {
279 std::string nameStr;
280 StringRef name;
281 FIRRTLBaseType type;
282
283 if (failed(parser.parseKeywordOrString(&nameStr)))
284 return failure();
285 name = nameStr;
286
287 bool isFlip = succeeded(parser.parseOptionalKeyword("flip"));
288 if (parser.parseColon() || parseNestedBaseType(type, parser))
289 return failure();
290
291 elements.push_back({StringAttr::get(context, name), isFlip, type});
292 return success();
293 };
294
295 if (parser.parseCommaSeparatedList(mlir::AsmParser::Delimiter::LessGreater,
296 parseBundleElement))
297 return failure();
298
299 result = parser.getChecked<BundleType>(context, elements, isConst);
300 return failure(!result);
301 }
302 if (name == "openbundle") {
303 SmallVector<OpenBundleType::BundleElement, 4> elements;
304
305 auto parseBundleElement = [&]() -> ParseResult {
306 std::string nameStr;
307 StringRef name;
308 FIRRTLType type;
309
310 if (failed(parser.parseKeywordOrString(&nameStr)))
311 return failure();
312 name = nameStr;
313
314 bool isFlip = succeeded(parser.parseOptionalKeyword("flip"));
315 if (parser.parseColon() || parseNestedType(type, parser))
316 return failure();
317
318 elements.push_back({StringAttr::get(context, name), isFlip, type});
319 return success();
320 };
321
322 if (parser.parseCommaSeparatedList(mlir::AsmParser::Delimiter::LessGreater,
323 parseBundleElement))
324 return failure();
325
326 result = parser.getChecked<OpenBundleType>(context, elements, isConst);
327 return failure(!result);
328 }
329
330 if (name == "enum") {
331 SmallVector<StringAttr> names;
332 SmallVector<APInt> values;
333 SmallVector<FIRRTLBaseType> types;
334 auto parseEnumElement = [&]() -> ParseResult {
335 // Parse the variant tag.
336 std::string nameStr;
337 if (failed(parser.parseKeywordOrString(&nameStr)))
338 return failure();
339 names.push_back(StringAttr::get(context, nameStr));
340
341 // Parse the integer value if it exists. If its the first element of the
342 // enum, it implicitly has a value of 0, otherwise it defaults to the
343 // previous value + 1.
344 APInt value;
345 if (succeeded(parser.parseOptionalEqual())) {
346 if (parser.parseInteger(value))
347 return failure();
348 } else if (values.empty()) {
349 // This is the first enum variant, so it defaults to 0.
350 value = APInt(1, 0);
351 } else {
352 // This value is not specified, so it defaults to the previous value
353 // + 1.
354 auto &prev = values.back();
355 if (prev.isMaxValue())
356 value = prev.zext(prev.getBitWidth() + 1);
357 else
358 value = prev;
359 ++value;
360 }
361 values.push_back(std::move(value));
362
363 // Parse the type of the variant data.
364 FIRRTLBaseType type;
365 if (succeeded(parser.parseOptionalColon())) {
366 if (parseNestedBaseType(type, parser))
367 return failure();
368 } else {
369 type = UIntType::get(parser.getContext(), 0);
370 }
371 types.push_back(type);
372
373 return success();
374 };
375
376 if (parser.parseCommaSeparatedList(mlir::AsmParser::Delimiter::LessGreater,
377 parseEnumElement))
378 return failure();
379
380 // Find the bitwidth of the enum.
381 unsigned bitwidth = 0;
382 for (auto &value : values)
383 bitwidth = std::max(bitwidth, value.getActiveBits());
384 auto tagType = IntegerType::get(context, bitwidth, IntegerType::Unsigned);
385
386 SmallVector<FEnumType::EnumElement, 4> elements;
387 for (auto [name, value, type] : llvm::zip(names, values, types)) {
388 auto tagValue = value.zextOrTrunc(bitwidth);
389 elements.push_back({name, IntegerAttr::get(tagType, tagValue), type});
390 }
391
392 if (failed(FEnumType::verify(
393 [&]() { return parser.emitError(parser.getNameLoc()); }, elements,
394 isConst)))
395 return failure();
396
397 result = parser.getChecked<FEnumType>(context, elements, isConst);
398 return failure(!result);
399 }
400
401 if (name == "vector") {
403 uint64_t width = 0;
404
405 if (parser.parseLess() || parseNestedBaseType(elementType, parser) ||
406 parser.parseComma() || parser.parseInteger(width) ||
407 parser.parseGreater())
408 return failure();
409
410 return result = FVectorType::get(elementType, width, isConst), success();
411 }
412 if (name == "openvector") {
414 uint64_t width = 0;
415
416 if (parser.parseLess() || parseNestedType(elementType, parser) ||
417 parser.parseComma() || parser.parseInteger(width) ||
418 parser.parseGreater())
419 return failure();
420
421 result =
422 parser.getChecked<OpenVectorType>(context, elementType, width, isConst);
423 return failure(!result);
424 }
425
426 // For now, support both firrtl.ref and firrtl.probe.
427 if (name == "ref" || name == "probe") {
428 FIRRTLBaseType type;
429 SymbolRefAttr layer;
430 // Don't pass `isConst` to `parseNestedBaseType since `ref` can point to
431 // either `const` or non-`const` types
432 if (parser.parseLess() || parseNestedBaseType(type, parser))
433 return failure();
434 if (parser.parseOptionalComma().succeeded())
435 if (parser.parseOptionalAttribute(layer).value())
436 return parser.emitError(parser.getNameLoc(),
437 "expected symbol reference");
438 if (parser.parseGreater())
439 return failure();
440
441 if (failed(RefType::verify(
442 [&]() { return parser.emitError(parser.getNameLoc()); }, type,
443 false, layer)))
444 return failure();
445
446 return result = RefType::get(type, false, layer), success();
447 }
448 if (name == "lhs") {
449 FIRRTLType type;
450 if (parser.parseLess() || parseNestedType(type, parser) ||
451 parser.parseGreater())
452 return failure();
453 if (!isa<FIRRTLBaseType>(type))
454 return parser.emitError(parser.getNameLoc(), "expected base type");
455 result = parser.getChecked<LHSType>(context, cast<FIRRTLBaseType>(type));
456 return failure(!result);
457 }
458 if (name == "rwprobe") {
459 FIRRTLBaseType type;
460 SymbolRefAttr layer;
461 if (parser.parseLess() || parseNestedBaseType(type, parser))
462 return failure();
463 if (parser.parseOptionalComma().succeeded())
464 if (parser.parseOptionalAttribute(layer).value())
465 return parser.emitError(parser.getNameLoc(),
466 "expected symbol reference");
467 if (parser.parseGreater())
468 return failure();
469
470 if (failed(RefType::verify(
471 [&]() { return parser.emitError(parser.getNameLoc()); }, type, true,
472 layer)))
473 return failure();
474
475 return result = RefType::get(type, true, layer), success();
476 }
477 if (name == "class") {
478 if (isConst)
479 return parser.emitError(parser.getNameLoc(), "classes cannot be const");
480 ClassType classType;
481 if (parser.parseLess() || ClassType::parseInterface(parser, classType) ||
482 parser.parseGreater())
483 return failure();
484 result = classType;
485 return success();
486 }
487 if (name == "anyref") {
488 if (isConst)
489 return parser.emitError(parser.getNameLoc(), "any refs cannot be const");
490
491 result = AnyRefType::get(parser.getContext());
492 return success();
493 }
494 if (name == "string") {
495 if (isConst) {
496 parser.emitError(parser.getNameLoc(), "strings cannot be const");
497 return failure();
498 }
499 result = StringType::get(parser.getContext());
500 return success();
501 }
502 if (name == "integer") {
503 if (isConst) {
504 parser.emitError(parser.getNameLoc(), "bigints cannot be const");
505 return failure();
506 }
507 result = FIntegerType::get(parser.getContext());
508 return success();
509 }
510 if (name == "bool") {
511 if (isConst) {
512 parser.emitError(parser.getNameLoc(), "bools cannot be const");
513 return failure();
514 }
515 result = BoolType::get(parser.getContext());
516 return success();
517 }
518 if (name == "double") {
519 if (isConst) {
520 parser.emitError(parser.getNameLoc(), "doubles cannot be const");
521 return failure();
522 }
523 result = DoubleType::get(parser.getContext());
524 return success();
525 }
526 if (name == "list") {
527 if (isConst) {
528 parser.emitError(parser.getNameLoc(), "lists cannot be const");
529 return failure();
530 }
532 if (parser.parseLess() || parseNestedPropertyType(elementType, parser) ||
533 parser.parseGreater())
534 return failure();
535 result = parser.getChecked<ListType>(context, elementType);
536 if (!result)
537 return failure();
538 return success();
539 }
540 if (name == "option") {
541 if (isConst)
542 return parser.emitError(parser.getNameLoc(), "options cannot be const");
544 if (parser.parseLess() || parseNestedPropertyType(elementType, parser) ||
545 parser.parseGreater())
546 return failure();
547 result = OptionType::get(context, elementType);
548 return success();
549 }
550 if (name == "registry") {
551 if (isConst) {
552 parser.emitError(parser.getNameLoc(), "registries cannot be const");
553 return failure();
554 }
556 if (parser.parseLess() || parseNestedPropertyType(elementType, parser) ||
557 parser.parseGreater())
558 return failure();
559 result = RegistryType::get(context, elementType);
560 if (!result)
561 return failure();
562 return success();
563 }
564 if (name == "path") {
565 if (isConst) {
566 parser.emitError(parser.getNameLoc(), "path cannot be const");
567 return failure();
568 }
569 result = PathType::get(parser.getContext());
570 return success();
571 }
572 if (name == "alias") {
573 FIRRTLBaseType type;
574 StringRef name;
575 if (parser.parseLess() || parser.parseKeyword(&name) ||
576 parser.parseComma() || parseNestedBaseType(type, parser) ||
577 parser.parseGreater())
578 return failure();
579
580 return result =
581 BaseTypeAliasType::get(StringAttr::get(context, name), type),
582 success();
583 }
584 if (name == "fstring") {
585 return result = FStringType::get(context), success();
586 }
587 if (name == "domain") {
588 // Parse: !firrtl.domain<@SymbolName> or
589 // !firrtl.domain<@SymbolName(name: type, ...)>
590 DomainType domainType;
591 if (parser.parseLess() || DomainType::parseInterface(parser, domainType) ||
592 parser.parseGreater())
593 return failure();
594
595 result = domainType;
596 return success();
597 }
598
599 return {};
600}
601
602/// Parse a type defined by this dialect.
603///
604/// This will first try the generated type parsers and then resort to the custom
605/// parser implementation. Emits an error and returns failure if `name` does not
606/// refer to a type defined in this dialect.
607static ParseResult parseType(Type &result, StringRef name, AsmParser &parser) {
608 // Try the custom type parser.
609 OptionalParseResult parseResult = customTypeParser(parser, name, result);
610 if (parseResult.has_value())
611 return parseResult.value();
612
613 // None of the above recognized the type, so we bail.
614 parser.emitError(parser.getNameLoc(), "unknown FIRRTL dialect type: \"")
615 << name << "\"";
616 return failure();
617}
618
619/// Parse a `FIRRTLType` with a `name` that has already been parsed.
620///
621/// Note that only a subset of types defined in the FIRRTL dialect inherit from
622/// `FIRRTLType`. Use `parseType` to parse *any* of the defined types.
623static ParseResult parseFIRRTLType(FIRRTLType &result, StringRef name,
624 AsmParser &parser) {
625 Type type;
626 if (failed(parseType(type, name, parser)))
627 return failure();
628 result = type_dyn_cast<FIRRTLType>(type);
629 if (result)
630 return success();
631 parser.emitError(parser.getNameLoc(), "unknown FIRRTL type: \"")
632 << name << "\"";
633 return failure();
634}
635
636static ParseResult parseFIRRTLBaseType(FIRRTLBaseType &result, StringRef name,
637 AsmParser &parser) {
638 FIRRTLType type;
639 if (failed(parseFIRRTLType(type, name, parser)))
640 return failure();
641 if (auto base = type_dyn_cast<FIRRTLBaseType>(type)) {
642 result = base;
643 return success();
644 }
645 parser.emitError(parser.getNameLoc(), "expected base type, found ") << type;
646 return failure();
647}
648
649static ParseResult parseFIRRTLPropertyType(PropertyType &result, StringRef name,
650 AsmParser &parser) {
651 FIRRTLType type;
652 if (failed(parseFIRRTLType(type, name, parser)))
653 return failure();
654 if (auto prop = type_dyn_cast<PropertyType>(type)) {
655 result = prop;
656 return success();
657 }
658 parser.emitError(parser.getNameLoc(), "expected property type, found ")
659 << type;
660 return failure();
661}
662
663// NOLINTBEGIN(misc-no-recursion)
664/// Parse a `FIRRTLType`.
665///
666/// Note that only a subset of types defined in the FIRRTL dialect inherit from
667/// `FIRRTLType`. Use `parseType` to parse *any* of the defined types.
669 AsmParser &parser) {
670 StringRef name;
671 if (parser.parseKeyword(&name))
672 return failure();
673 return parseFIRRTLType(result, name, parser);
674}
675// NOLINTEND(misc-no-recursion)
676
677// NOLINTBEGIN(misc-no-recursion)
679 AsmParser &parser) {
680 StringRef name;
681 if (parser.parseKeyword(&name))
682 return failure();
683 return parseFIRRTLBaseType(result, name, parser);
684}
685// NOLINTEND(misc-no-recursion)
686
687// NOLINTBEGIN(misc-no-recursion)
689 AsmParser &parser) {
690 StringRef name;
691 if (parser.parseKeyword(&name))
692 return failure();
693 return parseFIRRTLPropertyType(result, name, parser);
694}
695// NOLINTEND(misc-no-recursion)
696
697//===---------------------------------------------------------------------===//
698// Dialect Type Parsing and Printing
699//===----------------------------------------------------------------------===//
700
701/// Print a type registered to this dialect.
702void FIRRTLDialect::printType(Type type, DialectAsmPrinter &os) const {
703 printNestedType(type, os);
704}
705
706/// Parse a type registered to this dialect.
707Type FIRRTLDialect::parseType(DialectAsmParser &parser) const {
708 StringRef name;
709 Type result;
710 if (parser.parseKeyword(&name) || ::parseType(result, name, parser))
711 return Type();
712 return result;
713}
714
715//===----------------------------------------------------------------------===//
716// Recursive Type Properties
717//===----------------------------------------------------------------------===//
718
719enum {
720 /// Bit set if the type only contains passive elements.
722 /// Bit set if the type contains an analog type.
724 /// Bit set fi the type has any uninferred bit widths.
726};
727
728//===----------------------------------------------------------------------===//
729// FIRRTLBaseType Implementation
730//===----------------------------------------------------------------------===//
731
733 // Use `char` instead of `bool` since llvm already provides a
734 // DenseMapInfo<char> specialization
735 using KeyTy = char;
736
737 FIRRTLBaseTypeStorage(bool isConst) : isConst(static_cast<char>(isConst)) {}
738
739 bool operator==(const KeyTy &key) const { return key == isConst; }
740
741 KeyTy getAsKey() const { return isConst; }
742
743 static FIRRTLBaseTypeStorage *construct(TypeStorageAllocator &allocator,
744 KeyTy key) {
745 return new (allocator.allocate<FIRRTLBaseTypeStorage>())
747 }
748
750};
751
752/// Return true if this is a 'ground' type, aka a non-aggregate type.
754 return TypeSwitch<FIRRTLType, bool>(*this)
755 .Case<ClockType, ResetType, AsyncResetType, SIntType, UIntType,
756 AnalogType>([](Type) { return true; })
757 .Case<BundleType, FVectorType, FEnumType, OpenBundleType, OpenVectorType>(
758 [](Type) { return false; })
759 .Case<BaseTypeAliasType>([](BaseTypeAliasType alias) {
760 return alias.getAnonymousType().isGround();
761 })
762 // Not ground per spec, but leaf of aggregate.
763 .Case<PropertyType, RefType>([](Type) { return false; })
764 .Default([](Type) {
765 llvm_unreachable("unknown FIRRTL type");
766 return false;
767 });
768}
769
770bool FIRRTLType::isConst() const {
771 return TypeSwitch<FIRRTLType, bool>(*this)
772 .Case<FIRRTLBaseType, OpenBundleType, OpenVectorType>(
773 [](auto type) { return type.isConst(); })
774 .Default(false);
775}
776
777bool FIRRTLBaseType::isConst() const { return getImpl()->isConst; }
778
780 return TypeSwitch<FIRRTLType, RecursiveTypeProperties>(*this)
781 .Case<ClockType, ResetType, AsyncResetType>([](FIRRTLBaseType type) {
782 return RecursiveTypeProperties{true,
783 false,
784 false,
785 type.isConst(),
786 false,
787 false,
789 })
790 .Case<SIntType, UIntType>([](auto type) {
792 true, false, false, type.isConst(), false, !type.hasWidth(), false};
793 })
794 .Case<AnalogType>([](auto type) {
795 return RecursiveTypeProperties{
796 true, false, true, type.isConst(), false, !type.hasWidth(), false};
797 })
798 .Case<BundleType, FVectorType, FEnumType, OpenBundleType, OpenVectorType,
799 RefType, BaseTypeAliasType>(
800 [](auto type) { return type.getRecursiveTypeProperties(); })
801 .Case<PropertyType>([](auto type) {
802 return RecursiveTypeProperties{true, false, false, false,
803 false, false, false};
804 })
805 .Case<LHSType>(
806 [](auto type) { return type.getType().getRecursiveTypeProperties(); })
807 .Case<FStringType>([](auto type) {
808 return RecursiveTypeProperties{true, false, false, false,
809 false, false, false};
810 })
811 .Case<DomainType>([](auto type) {
812 return RecursiveTypeProperties{true, false, false, false,
813 false, false, false};
814 })
815 .Default([](Type) {
816 llvm_unreachable("unknown FIRRTL type");
817 return RecursiveTypeProperties{};
818 });
819}
820
821/// Return this type with any type aliases recursively removed from itself.
823 return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
824 .Case<ClockType, ResetType, AsyncResetType, SIntType, UIntType,
825 AnalogType>([&](Type) { return *this; })
826 .Case<BundleType, FVectorType, FEnumType, BaseTypeAliasType>(
827 [](auto type) { return type.getAnonymousType(); })
828 .Default([](Type) {
829 llvm_unreachable("unknown FIRRTL type");
830 return FIRRTLBaseType();
831 });
832}
833
834/// Return this type with any flip types recursively removed from itself.
836 return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
837 .Case<ClockType, ResetType, AsyncResetType, SIntType, UIntType,
838 AnalogType, FEnumType>([&](Type) { return *this; })
839 .Case<BundleType, FVectorType, FEnumType, BaseTypeAliasType>(
840 [](auto type) { return type.getPassiveType(); })
841 .Default([](Type) {
842 llvm_unreachable("unknown FIRRTL type");
843 return FIRRTLBaseType();
844 });
845}
846
847/// Return a 'const' or non-'const' version of this type.
849 return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
850 .Case<ClockType, ResetType, AsyncResetType, AnalogType, SIntType,
851 UIntType, BundleType, FVectorType, FEnumType, BaseTypeAliasType>(
852 [&](auto type) { return type.getConstType(isConst); })
853 .Default([](Type) {
854 llvm_unreachable("unknown FIRRTL type");
855 return FIRRTLBaseType();
856 });
857}
858
859/// Return this type with a 'const' modifiers dropped
861 return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
862 .Case<ClockType, ResetType, AsyncResetType, AnalogType, SIntType,
863 UIntType>([&](auto type) { return type.getConstType(false); })
864 .Case<BundleType, FVectorType, FEnumType, BaseTypeAliasType>(
865 [&](auto type) { return type.getAllConstDroppedType(); })
866 .Default([](Type) {
867 llvm_unreachable("unknown FIRRTL type");
868 return FIRRTLBaseType();
869 });
870}
871
872/// Return this type with all ground types replaced with UInt<1>. This is
873/// used for `mem` operations.
875 return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
876 .Case<ClockType, ResetType, AsyncResetType, SIntType, UIntType,
877 AnalogType, FEnumType>([&](Type) {
878 return UIntType::get(this->getContext(), 1, this->isConst());
879 })
880 .Case<BundleType>([&](BundleType bundleType) {
881 SmallVector<BundleType::BundleElement, 4> newElements;
882 newElements.reserve(bundleType.getElements().size());
883 for (auto elt : bundleType)
884 newElements.push_back(
885 {elt.name, false /* FIXME */, elt.type.getMaskType()});
886 return BundleType::get(this->getContext(), newElements,
887 bundleType.isConst());
888 })
889 .Case<FVectorType>([](FVectorType vectorType) {
890 return FVectorType::get(vectorType.getElementType().getMaskType(),
891 vectorType.getNumElements(),
892 vectorType.isConst());
893 })
894 .Case<BaseTypeAliasType>([](BaseTypeAliasType base) {
895 return base.getModifiedType(base.getInnerType().getMaskType());
896 })
897 .Default([](Type) {
898 llvm_unreachable("unknown FIRRTL type");
899 return FIRRTLBaseType();
900 });
901}
902
903/// Remove the widths from this type. All widths are replaced with an
904/// unknown width.
906 return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
907 .Case<ClockType, ResetType, AsyncResetType>([](auto a) { return a; })
908 .Case<UIntType, SIntType, AnalogType>(
909 [&](auto a) { return a.get(this->getContext(), -1, a.isConst()); })
910 .Case<BundleType>([&](auto a) {
911 SmallVector<BundleType::BundleElement, 4> newElements;
912 newElements.reserve(a.getElements().size());
913 for (auto elt : a)
914 newElements.push_back(
915 {elt.name, elt.isFlip, elt.type.getWidthlessType()});
916 return BundleType::get(this->getContext(), newElements, a.isConst());
917 })
918 .Case<FVectorType>([](auto a) {
919 return FVectorType::get(a.getElementType().getWidthlessType(),
920 a.getNumElements(), a.isConst());
921 })
922 .Case<FEnumType>([&](FEnumType a) {
923 SmallVector<FEnumType::EnumElement, 4> newElements;
924 newElements.reserve(a.getNumElements());
925 for (auto elt : a)
926 newElements.push_back(
927 {elt.name, elt.value, elt.type.getWidthlessType()});
928 return FEnumType::get(this->getContext(), newElements, a.isConst());
929 })
930 .Case<BaseTypeAliasType>([](BaseTypeAliasType type) {
931 return type.getModifiedType(type.getInnerType().getWidthlessType());
932 })
933 .Default([](auto) {
934 llvm_unreachable("unknown FIRRTL type");
935 return FIRRTLBaseType();
936 });
937}
938
939/// If this is an IntType, AnalogType, or sugar type for a single bit (Clock,
940/// Reset, etc) then return the bitwidth. Return -1 if the is one of these
941/// types but without a specified bitwidth. Return -2 if this isn't a simple
942/// type.
944 return TypeSwitch<FIRRTLBaseType, int32_t>(*this)
945 .Case<ClockType, ResetType, AsyncResetType>([](Type) { return 1; })
946 .Case<SIntType, UIntType>(
947 [&](IntType intType) { return intType.getWidthOrSentinel(); })
948 .Case<AnalogType>(
949 [](AnalogType analogType) { return analogType.getWidthOrSentinel(); })
950 .Case<FEnumType>([&](FEnumType fenum) { return fenum.getBitWidth(); })
951 .Case<BundleType, FVectorType>([](Type) { return -2; })
952 .Case<BaseTypeAliasType>([](BaseTypeAliasType type) {
953 // It's faster to use its anonymous type.
954 return type.getAnonymousType().getBitWidthOrSentinel();
955 })
956 .Default([](Type) {
957 llvm_unreachable("unknown FIRRTL type");
958 return -2;
959 });
960}
961
962/// Return true if this is a type usable as a reset. This must be
963/// either an abstract reset, a concrete 1-bit UInt, an
964/// asynchronous reset, or an uninfered width UInt.
966 return TypeSwitch<FIRRTLType, bool>(*this)
967 .Case<ResetType, AsyncResetType>([](Type) { return true; })
968 .Case<UIntType>(
969 [](UIntType a) { return !a.hasWidth() || a.getWidth() == 1; })
970 .Case<BaseTypeAliasType>(
971 [](auto type) { return type.getInnerType().isResetType(); })
972 .Default([](Type) { return false; });
973}
974
975bool firrtl::isConst(Type type) {
976 return TypeSwitch<Type, bool>(type)
977 .Case<FIRRTLBaseType, OpenBundleType, OpenVectorType>(
978 [](auto base) { return base.isConst(); })
979 .Default(false);
980}
981
982bool firrtl::containsConst(Type type) {
983 return TypeSwitch<Type, bool>(type)
984 .Case<FIRRTLBaseType, OpenBundleType, OpenVectorType>(
985 [](auto base) { return base.containsConst(); })
986 .Default(false);
987}
988
989// NOLINTBEGIN(misc-no-recursion)
992 .Case<BundleType>([&](auto bundle) {
993 for (size_t i = 0, e = bundle.getNumElements(); i < e; ++i) {
994 auto elt = bundle.getElement(i);
995 if (hasZeroBitWidth(elt.type))
996 return true;
997 }
998 return bundle.getNumElements() == 0;
999 })
1000 .Case<FVectorType>([&](auto vector) {
1001 if (vector.getNumElements() == 0)
1002 return true;
1003 return hasZeroBitWidth(vector.getElementType());
1004 })
1005 .Case<FIRRTLBaseType>([](auto groundType) {
1006 return firrtl::getBitWidth(groundType).value_or(0) == 0;
1007 })
1008 .Case<RefType>([](auto ref) { return hasZeroBitWidth(ref.getType()); })
1009 .Default([](auto) { return false; });
1010}
1011// NOLINTEND(misc-no-recursion)
1012
1013/// Helper to implement the equivalence logic for a pair of bundle elements.
1014/// Note that the FIRRTL spec requires bundle elements to have the same
1015/// orientation, but this only compares their passive types. The FIRRTL dialect
1016/// differs from the spec in how it uses flip types for module output ports and
1017/// canonicalizes flips in bundles, so only passive types can be compared here.
1018static bool areBundleElementsEquivalent(BundleType::BundleElement destElement,
1019 BundleType::BundleElement srcElement,
1020 bool destOuterTypeIsConst,
1021 bool srcOuterTypeIsConst,
1022 bool requiresSameWidth) {
1023 if (destElement.name != srcElement.name)
1024 return false;
1025 if (destElement.isFlip != srcElement.isFlip)
1026 return false;
1027
1028 if (destElement.isFlip) {
1029 std::swap(destElement, srcElement);
1030 std::swap(destOuterTypeIsConst, srcOuterTypeIsConst);
1031 }
1032
1033 return areTypesEquivalent(destElement.type, srcElement.type,
1034 destOuterTypeIsConst, srcOuterTypeIsConst,
1035 requiresSameWidth);
1036}
1037
1038/// Returns whether the two types are equivalent. This implements the exact
1039/// definition of type equivalence in the FIRRTL spec. If the types being
1040/// compared have any outer flips that encode FIRRTL module directions (input or
1041/// output), these should be stripped before using this method.
1043 bool destOuterTypeIsConst,
1044 bool srcOuterTypeIsConst,
1045 bool requireSameWidths) {
1046 auto destType = type_dyn_cast<FIRRTLBaseType>(destFType);
1047 auto srcType = type_dyn_cast<FIRRTLBaseType>(srcFType);
1048
1049 // For non-base types, only equivalent if identical.
1050 if (!destType || !srcType)
1051 return destFType == srcFType;
1052
1053 bool srcIsConst = srcOuterTypeIsConst || srcFType.isConst();
1054 bool destIsConst = destOuterTypeIsConst || destFType.isConst();
1055
1056 // Vector types can be connected if they have the same size and element type.
1057 auto destVectorType = type_dyn_cast<FVectorType>(destType);
1058 auto srcVectorType = type_dyn_cast<FVectorType>(srcType);
1059 if (destVectorType && srcVectorType)
1060 return destVectorType.getNumElements() == srcVectorType.getNumElements() &&
1061 areTypesEquivalent(destVectorType.getElementType(),
1062 srcVectorType.getElementType(), destIsConst,
1063 srcIsConst, requireSameWidths);
1064
1065 // Bundle types can be connected if they have the same size, element names,
1066 // and element types.
1067 auto destBundleType = type_dyn_cast<BundleType>(destType);
1068 auto srcBundleType = type_dyn_cast<BundleType>(srcType);
1069 if (destBundleType && srcBundleType) {
1070 auto destElements = destBundleType.getElements();
1071 auto srcElements = srcBundleType.getElements();
1072 size_t numDestElements = destElements.size();
1073 if (numDestElements != srcElements.size())
1074 return false;
1075
1076 for (size_t i = 0; i < numDestElements; ++i) {
1077 auto destElement = destElements[i];
1078 auto srcElement = srcElements[i];
1079 if (!areBundleElementsEquivalent(destElement, srcElement, destIsConst,
1080 srcIsConst, requireSameWidths))
1081 return false;
1082 }
1083 return true;
1084 }
1085
1086 // Enum types can be connected if they have the same size, element names, and
1087 // element types.
1088 auto dstEnumType = type_dyn_cast<FEnumType>(destType);
1089 auto srcEnumType = type_dyn_cast<FEnumType>(srcType);
1090
1091 if (dstEnumType && srcEnumType) {
1092 if (dstEnumType.getNumElements() != srcEnumType.getNumElements())
1093 return false;
1094 // Enums requires the types to match exactly.
1095 for (const auto &[dst, src] : llvm::zip(dstEnumType, srcEnumType)) {
1096 // The variant names must match.
1097 if (dst.name != src.name)
1098 return false;
1099 // Enumeration types can only be connected if the inner types have the
1100 // same width.
1101 if (!areTypesEquivalent(dst.type, src.type, destIsConst, srcIsConst,
1102 true))
1103 return false;
1104 }
1105 return true;
1106 }
1107
1108 // Ground type connections must be const compatible.
1109 if (destIsConst && !srcIsConst)
1110 return false;
1111
1112 // Reset types can be driven by UInt<1>, AsyncReset, or Reset types.
1113 if (firrtl::type_isa<ResetType>(destType))
1114 return srcType.isResetType();
1115
1116 // Reset types can drive UInt<1>, AsyncReset, or Reset types.
1117 if (firrtl::type_isa<ResetType>(srcType))
1118 return destType.isResetType();
1119
1120 // If we can implicitly truncate or extend the bitwidth, or either width is
1121 // currently uninferred, then compare the widthless version of these types.
1122 if (!requireSameWidths || destType.getBitWidthOrSentinel() == -1)
1123 srcType = srcType.getWidthlessType();
1124 if (!requireSameWidths || srcType.getBitWidthOrSentinel() == -1)
1125 destType = destType.getWidthlessType();
1126
1127 // Ground types can be connected if their constless types are the same
1128 return destType.getConstType(false) == srcType.getConstType(false);
1129}
1130
1131/// Returns whether the srcType can be const-casted to the destType.
1133 bool srcOuterTypeIsConst) {
1134 // Identical types are always castable
1135 if (destFType == srcFType)
1136 return true;
1137
1138 auto destType = type_dyn_cast<FIRRTLBaseType>(destFType);
1139 auto srcType = type_dyn_cast<FIRRTLBaseType>(srcFType);
1140
1141 // For non-base types, only castable if identical.
1142 if (!destType || !srcType)
1143 return false;
1144
1145 // Types must be passive
1146 if (!destType.isPassive() || !srcType.isPassive())
1147 return false;
1148
1149 bool srcIsConst = srcType.isConst() || srcOuterTypeIsConst;
1150
1151 // Cannot cast non-'const' src to 'const' dest
1152 if (destType.isConst() && !srcIsConst)
1153 return false;
1154
1155 // Vector types can be casted if they have the same size and castable element
1156 // type.
1157 auto destVectorType = type_dyn_cast<FVectorType>(destType);
1158 auto srcVectorType = type_dyn_cast<FVectorType>(srcType);
1159 if (destVectorType && srcVectorType)
1160 return destVectorType.getNumElements() == srcVectorType.getNumElements() &&
1161 areTypesConstCastable(destVectorType.getElementType(),
1162 srcVectorType.getElementType(), srcIsConst);
1163 if (destVectorType != srcVectorType)
1164 return false;
1165
1166 // Bundle types can be casted if they have the same size, element names,
1167 // and castable element types.
1168 auto destBundleType = type_dyn_cast<BundleType>(destType);
1169 auto srcBundleType = type_dyn_cast<BundleType>(srcType);
1170 if (destBundleType && srcBundleType) {
1171 auto destElements = destBundleType.getElements();
1172 auto srcElements = srcBundleType.getElements();
1173 size_t numDestElements = destElements.size();
1174 if (numDestElements != srcElements.size())
1175 return false;
1176
1177 return llvm::all_of_zip(
1178 destElements, srcElements,
1179 [&](const auto &destElement, const auto &srcElement) {
1180 return destElement.name == srcElement.name &&
1181 areTypesConstCastable(destElement.type, srcElement.type,
1182 srcIsConst);
1183 });
1184 }
1185 if (destBundleType != srcBundleType)
1186 return false;
1187
1188 // Ground types can be casted if the source type is a const
1189 // version of the destination type
1190 return destType == srcType.getConstType(destType.isConst());
1191}
1192
1193bool firrtl::areTypesRefCastable(Type dstType, Type srcType) {
1194 auto dstRefType = type_dyn_cast<RefType>(dstType);
1195 auto srcRefType = type_dyn_cast<RefType>(srcType);
1196 if (!dstRefType || !srcRefType)
1197 return false;
1198 if (dstRefType == srcRefType)
1199 return true;
1200 if (dstRefType.getForceable() && !srcRefType.getForceable())
1201 return false;
1202
1203 // Okay walk the types recursively. They must be identical "structurally"
1204 // with exception leaf (ground) types of destination can be uninferred
1205 // versions of the corresponding source type. (can lose width information or
1206 // become a more general reset type)
1207 // In addition, while not explicitly in spec its useful to allow probes
1208 // to have const cast away, especially for probes of literals and expressions
1209 // derived from them. Check const as with const cast.
1210 // NOLINTBEGIN(misc-no-recursion)
1211 auto recurse = [&](auto &&f, FIRRTLBaseType dest, FIRRTLBaseType src,
1212 bool srcOuterTypeIsConst) -> bool {
1213 // Fast-path for identical types.
1214 if (dest == src)
1215 return true;
1216
1217 // Always passive inside probes, but for sanity assert this.
1218 assert(dest.isPassive() && src.isPassive());
1219
1220 bool srcIsConst = src.isConst() || srcOuterTypeIsConst;
1221
1222 // Cannot cast non-'const' src to 'const' dest
1223 if (dest.isConst() && !srcIsConst)
1224 return false;
1225
1226 // Recurse through aggregates to get the leaves, checking
1227 // structural equivalence re:element count + names.
1228
1229 if (auto destVectorType = type_dyn_cast<FVectorType>(dest)) {
1230 auto srcVectorType = type_dyn_cast<FVectorType>(src);
1231 return srcVectorType &&
1232 destVectorType.getNumElements() ==
1233 srcVectorType.getNumElements() &&
1234 f(f, destVectorType.getElementType(),
1235 srcVectorType.getElementType(), srcIsConst);
1236 }
1237
1238 if (auto destBundleType = type_dyn_cast<BundleType>(dest)) {
1239 auto srcBundleType = type_dyn_cast<BundleType>(src);
1240 if (!srcBundleType)
1241 return false;
1242 // (no need to check orientation, these are always passive)
1243 auto destElements = destBundleType.getElements();
1244 auto srcElements = srcBundleType.getElements();
1245
1246 return destElements.size() == srcElements.size() &&
1247 llvm::all_of_zip(
1248 destElements, srcElements,
1249 [&](const auto &destElement, const auto &srcElement) {
1250 return destElement.name == srcElement.name &&
1251 f(f, destElement.type, srcElement.type, srcIsConst);
1252 });
1253 }
1254
1255 if (auto destEnumType = type_dyn_cast<FEnumType>(dest)) {
1256 auto srcEnumType = type_dyn_cast<FEnumType>(src);
1257 if (!srcEnumType)
1258 return false;
1259 auto destElements = destEnumType.getElements();
1260 auto srcElements = srcEnumType.getElements();
1261
1262 return destElements.size() == srcElements.size() &&
1263 llvm::all_of_zip(
1264 destElements, srcElements,
1265 [&](const auto &destElement, const auto &srcElement) {
1266 return destElement.name == srcElement.name &&
1267 f(f, destElement.type, srcElement.type, srcIsConst);
1268 });
1269 }
1270
1271 // Reset types can be driven by UInt<1>, AsyncReset, or Reset types.
1272 if (type_isa<ResetType>(dest))
1273 return src.isResetType();
1274 // (but don't allow the other direction, can only become more general)
1275
1276 // Compare against const src if dest is const.
1277 src = src.getConstType(dest.isConst());
1278
1279 // Compare against widthless src if dest is widthless.
1280 if (dest.getBitWidthOrSentinel() == -1)
1281 src = src.getWidthlessType();
1282
1283 return dest == src;
1284 };
1285
1286 return recurse(recurse, dstRefType.getType(), srcRefType.getType(), false);
1287 // NOLINTEND(misc-no-recursion)
1288}
1289
1290// NOLINTBEGIN(misc-no-recursion)
1291/// Returns true if the destination is at least as wide as an equivalent source.
1293 return TypeSwitch<FIRRTLBaseType, bool>(dstType)
1294 .Case<BundleType>([&](auto dstBundle) {
1295 auto srcBundle = type_cast<BundleType>(srcType);
1296 for (size_t i = 0, n = dstBundle.getNumElements(); i < n; ++i) {
1297 auto srcElem = srcBundle.getElement(i);
1298 auto dstElem = dstBundle.getElement(i);
1299 if (dstElem.isFlip) {
1300 if (!isTypeLarger(srcElem.type, dstElem.type))
1301 return false;
1302 } else {
1303 if (!isTypeLarger(dstElem.type, srcElem.type))
1304 return false;
1305 }
1306 }
1307 return true;
1308 })
1309 .Case<FVectorType>([&](auto vector) {
1310 return isTypeLarger(vector.getElementType(),
1311 type_cast<FVectorType>(srcType).getElementType());
1312 })
1313 .Default([&](auto dstGround) {
1314 int32_t destWidth = dstType.getPassiveType().getBitWidthOrSentinel();
1315 int32_t srcWidth = srcType.getPassiveType().getBitWidthOrSentinel();
1316 return destWidth <= -1 || srcWidth <= -1 || destWidth >= srcWidth;
1317 });
1318}
1319// NOLINTEND(misc-no-recursion)
1320
1325
1326bool firrtl::areAnonymousTypesEquivalent(mlir::Type lhs, mlir::Type rhs) {
1327 if (auto destBaseType = type_dyn_cast<FIRRTLBaseType>(lhs))
1328 if (auto srcBaseType = type_dyn_cast<FIRRTLBaseType>(rhs))
1329 return areAnonymousTypesEquivalent(destBaseType, srcBaseType);
1330
1331 if (auto destRefType = type_dyn_cast<RefType>(lhs))
1332 if (auto srcRefType = type_dyn_cast<RefType>(rhs))
1333 return areAnonymousTypesEquivalent(destRefType.getType(),
1334 srcRefType.getType());
1335
1336 return lhs == rhs;
1337}
1338
1339/// Return the passive version of a firrtl type
1340/// top level for ODS constraint usage
1341Type firrtl::getPassiveType(Type anyBaseFIRRTLType) {
1342 return type_cast<FIRRTLBaseType>(anyBaseFIRRTLType).getPassiveType();
1343}
1344
1345bool firrtl::isTypeInOut(Type type) {
1346 return llvm::TypeSwitch<Type, bool>(type)
1347 .Case<FIRRTLBaseType>([](auto type) {
1348 return !type.containsReference() &&
1349 (!type.isPassive() || type.containsAnalog());
1350 })
1351 .Default(false);
1352}
1353
1354// NOLINTBEGIN(misc-no-recursion)
1356 // Is a hardware base type
1357 if (isa<FIRRTLBaseType>(type))
1358 return true;
1359 // Check each element of the aggregate
1360 if (auto bundle = dyn_cast<OpenBundleType>(type))
1361 return llvm::any_of(bundle,
1362 [](auto elt) { return hasHardwareElements(elt.type); });
1363 if (auto vector = dyn_cast<OpenVectorType>(type))
1364 return hasHardwareElements(vector.getElementType());
1365 return false;
1366}
1367// NOLINTEND(misc-no-recursion)
1368
1369//===----------------------------------------------------------------------===//
1370// IntType
1371//===----------------------------------------------------------------------===//
1372
1373/// Return a SIntType or UIntType with the specified signedness, width, and
1374/// constness
1376 int32_t widthOrSentinel, bool isConst) {
1377 if (isSigned)
1378 return SIntType::get(context, widthOrSentinel, isConst);
1379 return UIntType::get(context, widthOrSentinel, isConst);
1380}
1381
1383 if (auto sintType = type_dyn_cast<SIntType>(*this))
1384 return sintType.getWidthOrSentinel();
1385 if (auto uintType = type_dyn_cast<UIntType>(*this))
1386 return uintType.getWidthOrSentinel();
1387 return -1;
1388}
1389
1390//===----------------------------------------------------------------------===//
1391// WidthTypeStorage
1392//===----------------------------------------------------------------------===//
1393
1397 using KeyTy = std::tuple<int32_t, char>;
1398
1399 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
1400
1401 KeyTy getAsKey() const { return KeyTy(width, isConst); }
1402
1403 static WidthTypeStorage *construct(TypeStorageAllocator &allocator,
1404 const KeyTy &key) {
1405 return new (allocator.allocate<WidthTypeStorage>())
1406 WidthTypeStorage(std::get<0>(key), std::get<1>(key));
1407 }
1408
1409 int32_t width;
1410};
1411
1413
1414 if (auto sIntType = type_dyn_cast<SIntType>(*this))
1415 return sIntType.getConstType(isConst);
1417}
1418
1419//===----------------------------------------------------------------------===//
1420// SIntType
1421//===----------------------------------------------------------------------===//
1422
1423SIntType SIntType::get(MLIRContext *context) { return get(context, -1, false); }
1424
1425SIntType SIntType::get(MLIRContext *context, std::optional<int32_t> width,
1426 bool isConst) {
1427 return get(context, width ? *width : -1, isConst);
1428}
1429
1430LogicalResult SIntType::verify(function_ref<InFlightDiagnostic()> emitError,
1431 int32_t widthOrSentinel, bool isConst) {
1432 if (widthOrSentinel < -1)
1433 return emitError() << "invalid width";
1434 return success();
1435}
1436
1437int32_t SIntType::getWidthOrSentinel() const { return getImpl()->width; }
1438
1439SIntType SIntType::getConstType(bool isConst) const {
1440 if (isConst == this->isConst())
1441 return *this;
1442 return get(getContext(), getWidthOrSentinel(), isConst);
1443}
1444
1445//===----------------------------------------------------------------------===//
1446// UIntType
1447//===----------------------------------------------------------------------===//
1448
1449UIntType UIntType::get(MLIRContext *context) { return get(context, -1, false); }
1450
1451UIntType UIntType::get(MLIRContext *context, std::optional<int32_t> width,
1452 bool isConst) {
1453 return get(context, width ? *width : -1, isConst);
1454}
1455
1456LogicalResult UIntType::verify(function_ref<InFlightDiagnostic()> emitError,
1457 int32_t widthOrSentinel, bool isConst) {
1458 if (widthOrSentinel < -1)
1459 return emitError() << "invalid width";
1460 return success();
1461}
1462
1463int32_t UIntType::getWidthOrSentinel() const { return getImpl()->width; }
1464
1465UIntType UIntType::getConstType(bool isConst) const {
1466 if (isConst == this->isConst())
1467 return *this;
1468 return get(getContext(), getWidthOrSentinel(), isConst);
1469}
1470
1471//===----------------------------------------------------------------------===//
1472// Bundle Type
1473//===----------------------------------------------------------------------===//
1474
1477 using KeyTy = std::tuple<ArrayRef<BundleType::BundleElement>, char>;
1478
1479 BundleTypeStorage(ArrayRef<BundleType::BundleElement> elements, bool isConst)
1481 elements(elements.begin(), elements.end()),
1482 props{true, false, false, isConst, false, false, false} {
1483 uint64_t fieldID = 0;
1484 fieldIDs.reserve(elements.size());
1485 for (auto &element : elements) {
1486 auto type = element.type;
1487 auto eltInfo = type.getRecursiveTypeProperties();
1488 props.isPassive &= eltInfo.isPassive & !element.isFlip;
1489 props.containsAnalog |= eltInfo.containsAnalog;
1490 props.containsReference |= eltInfo.containsReference;
1491 props.containsConst |= eltInfo.containsConst;
1492 props.containsTypeAlias |= eltInfo.containsTypeAlias;
1493 props.hasUninferredWidth |= eltInfo.hasUninferredWidth;
1494 props.hasUninferredReset |= eltInfo.hasUninferredReset;
1495 fieldID += 1;
1496 fieldIDs.push_back(fieldID);
1497 // Increment the field ID for the next field by the number of subfields.
1498 fieldID += hw::FieldIdImpl::getMaxFieldID(type);
1499 }
1500 maxFieldID = fieldID;
1501 }
1502
1503 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
1504
1505 KeyTy getAsKey() const { return KeyTy(elements, isConst); }
1506
1507 static llvm::hash_code hashKey(const KeyTy &key) {
1508 return llvm::hash_value(key);
1509 }
1510
1511 static BundleTypeStorage *construct(TypeStorageAllocator &allocator,
1512 KeyTy key) {
1513 return new (allocator.allocate<BundleTypeStorage>()) BundleTypeStorage(
1514 std::get<0>(key), static_cast<bool>(std::get<1>(key)));
1515 }
1516
1517 SmallVector<BundleType::BundleElement, 4> elements;
1518 SmallVector<uint64_t, 4> fieldIDs;
1519 uint64_t maxFieldID;
1520
1521 /// This holds the bits for the type's recursive properties, and can hold a
1522 /// pointer to a passive version of the type.
1524 BundleType passiveType;
1525 BundleType anonymousType;
1526};
1527
1528BundleType BundleType::get(MLIRContext *context,
1529 ArrayRef<BundleElement> elements, bool isConst) {
1530 return Base::get(context, elements, isConst);
1531}
1532
1533auto BundleType::getElements() const -> ArrayRef<BundleElement> {
1534 return getImpl()->elements;
1535}
1536
1537/// Return a pair with the 'isPassive' and 'containsAnalog' bits.
1538RecursiveTypeProperties BundleType::getRecursiveTypeProperties() const {
1539 return getImpl()->props;
1540}
1541
1542/// Return this type with any flip types recursively removed from itself.
1543FIRRTLBaseType BundleType::getPassiveType() {
1544 auto *impl = getImpl();
1545
1546 // If we've already determined and cached the passive type, use it.
1547 if (impl->passiveType)
1548 return impl->passiveType;
1549
1550 // If this type is already passive, use it and remember for next time.
1551 if (impl->props.isPassive) {
1552 impl->passiveType = *this;
1553 return *this;
1554 }
1555
1556 // Otherwise at least one element is non-passive, rebuild a passive version.
1557 SmallVector<BundleType::BundleElement, 16> newElements;
1558 newElements.reserve(impl->elements.size());
1559 for (auto &elt : impl->elements) {
1560 newElements.push_back({elt.name, false, elt.type.getPassiveType()});
1561 }
1562
1563 auto passiveType = BundleType::get(getContext(), newElements, isConst());
1564 impl->passiveType = passiveType;
1565 return passiveType;
1566}
1567
1568BundleType BundleType::getConstType(bool isConst) const {
1569 if (isConst == this->isConst())
1570 return *this;
1571 return get(getContext(), getElements(), isConst);
1572}
1573
1574BundleType BundleType::getAllConstDroppedType() {
1575 if (!containsConst())
1576 return *this;
1577
1578 SmallVector<BundleElement> constDroppedElements(
1579 llvm::map_range(getElements(), [](BundleElement element) {
1580 element.type = element.type.getAllConstDroppedType();
1581 return element;
1582 }));
1583 return get(getContext(), constDroppedElements, false);
1584}
1585
1586std::optional<unsigned> BundleType::getElementIndex(StringAttr name) {
1587 for (const auto &it : llvm::enumerate(getElements())) {
1588 auto element = it.value();
1589 if (element.name == name) {
1590 return unsigned(it.index());
1591 }
1592 }
1593 return std::nullopt;
1594}
1595
1596std::optional<unsigned> BundleType::getElementIndex(StringRef name) {
1597 for (const auto &it : llvm::enumerate(getElements())) {
1598 auto element = it.value();
1599 if (element.name.getValue() == name) {
1600 return unsigned(it.index());
1601 }
1602 }
1603 return std::nullopt;
1604}
1605
1606StringAttr BundleType::getElementNameAttr(size_t index) {
1607 assert(index < getNumElements() &&
1608 "index must be less than number of fields in bundle");
1609 return getElements()[index].name;
1610}
1611
1612StringRef BundleType::getElementName(size_t index) {
1613 return getElementNameAttr(index).getValue();
1614}
1615
1616std::optional<BundleType::BundleElement>
1617BundleType::getElement(StringAttr name) {
1618 if (auto maybeIndex = getElementIndex(name))
1619 return getElements()[*maybeIndex];
1620 return std::nullopt;
1621}
1622
1623std::optional<BundleType::BundleElement>
1624BundleType::getElement(StringRef name) {
1625 if (auto maybeIndex = getElementIndex(name))
1626 return getElements()[*maybeIndex];
1627 return std::nullopt;
1628}
1629
1630/// Look up an element by index.
1631BundleType::BundleElement BundleType::getElement(size_t index) {
1632 assert(index < getNumElements() &&
1633 "index must be less than number of fields in bundle");
1634 return getElements()[index];
1635}
1636
1637FIRRTLBaseType BundleType::getElementType(StringAttr name) {
1638 auto element = getElement(name);
1639 return element ? element->type : FIRRTLBaseType();
1640}
1641
1642FIRRTLBaseType BundleType::getElementType(StringRef name) {
1643 auto element = getElement(name);
1644 return element ? element->type : FIRRTLBaseType();
1645}
1646
1647FIRRTLBaseType BundleType::getElementType(size_t index) const {
1648 assert(index < getNumElements() &&
1649 "index must be less than number of fields in bundle");
1650 return getElements()[index].type;
1651}
1652
1653uint64_t BundleType::getFieldID(uint64_t index) const {
1654 return getImpl()->fieldIDs[index];
1655}
1656
1657uint64_t BundleType::getIndexForFieldID(uint64_t fieldID) const {
1658 assert(!getElements().empty() && "Bundle must have >0 fields");
1659 auto fieldIDs = getImpl()->fieldIDs;
1660 auto *it = std::prev(llvm::upper_bound(fieldIDs, fieldID));
1661 return std::distance(fieldIDs.begin(), it);
1662}
1663
1664std::pair<uint64_t, uint64_t>
1665BundleType::getIndexAndSubfieldID(uint64_t fieldID) const {
1666 auto index = getIndexForFieldID(fieldID);
1667 auto elementFieldID = getFieldID(index);
1668 return {index, fieldID - elementFieldID};
1669}
1670
1671std::pair<Type, uint64_t>
1672BundleType::getSubTypeByFieldID(uint64_t fieldID) const {
1673 if (fieldID == 0)
1674 return {*this, 0};
1675 auto subfieldIndex = getIndexForFieldID(fieldID);
1676 auto subfieldType = getElementType(subfieldIndex);
1677 auto subfieldID = fieldID - getFieldID(subfieldIndex);
1678 return {subfieldType, subfieldID};
1679}
1680
1681uint64_t BundleType::getMaxFieldID() const { return getImpl()->maxFieldID; }
1682
1683std::pair<uint64_t, bool>
1684BundleType::projectToChildFieldID(uint64_t fieldID, uint64_t index) const {
1685 auto childRoot = getFieldID(index);
1686 auto rangeEnd = index + 1 >= getNumElements() ? getMaxFieldID()
1687 : (getFieldID(index + 1) - 1);
1688 return std::make_pair(fieldID - childRoot,
1689 fieldID >= childRoot && fieldID <= rangeEnd);
1690}
1691
1692bool BundleType::isConst() const { return getImpl()->isConst; }
1693
1694BundleType::ElementType
1695BundleType::getElementTypePreservingConst(size_t index) {
1696 auto type = getElementType(index);
1697 return type.getConstType(type.isConst() || isConst());
1698}
1699
1700/// Return this type with any type aliases recursively removed from itself.
1701FIRRTLBaseType BundleType::getAnonymousType() {
1702 auto *impl = getImpl();
1703
1704 // If we've already determined and cached the anonymous type, use it.
1705 if (impl->anonymousType)
1706 return impl->anonymousType;
1707
1708 // If this type is already anonymous, use it and remember for next time.
1709 if (!impl->props.containsTypeAlias) {
1710 impl->anonymousType = *this;
1711 return *this;
1712 }
1713
1714 // Otherwise at least one element has an alias type, rebuild an anonymous
1715 // version.
1716 SmallVector<BundleType::BundleElement, 16> newElements;
1717 newElements.reserve(impl->elements.size());
1718 for (auto &elt : impl->elements)
1719 newElements.push_back({elt.name, elt.isFlip, elt.type.getAnonymousType()});
1720
1721 auto anonymousType = BundleType::get(getContext(), newElements, isConst());
1722 impl->anonymousType = anonymousType;
1723 return anonymousType;
1724}
1725
1726LogicalResult BundleType::verify(function_ref<InFlightDiagnostic()> emitErrorFn,
1727 ArrayRef<BundleElement> elements,
1728 bool isConst) {
1729 SmallPtrSet<StringAttr, 4> nameSet;
1730 for (auto &element : elements) {
1731 if (!nameSet.insert(element.name).second)
1732 return emitErrorFn() << "duplicate field name " << element.name
1733 << " in bundle";
1734 }
1735
1736 return success();
1737}
1738
1739//===----------------------------------------------------------------------===//
1740// OpenBundle Type
1741//===----------------------------------------------------------------------===//
1742
1744 using KeyTy = std::tuple<ArrayRef<OpenBundleType::BundleElement>, char>;
1745
1746 OpenBundleTypeStorage(ArrayRef<OpenBundleType::BundleElement> elements,
1747 bool isConst)
1748 : elements(elements.begin(), elements.end()),
1749 props{true, false, false, isConst, false, false, false},
1750 isConst(static_cast<char>(isConst)) {
1751 uint64_t fieldID = 0;
1752 fieldIDs.reserve(elements.size());
1753 for (auto &element : elements) {
1754 auto type = element.type;
1755 auto eltInfo = type.getRecursiveTypeProperties();
1756 props.isPassive &= eltInfo.isPassive & !element.isFlip;
1757 props.containsAnalog |= eltInfo.containsAnalog;
1758 props.containsReference |= eltInfo.containsReference;
1759 props.containsConst |= eltInfo.containsConst;
1760 props.containsTypeAlias |= eltInfo.containsTypeAlias;
1761 props.hasUninferredWidth |= eltInfo.hasUninferredWidth;
1762 props.hasUninferredReset |= eltInfo.hasUninferredReset;
1763 fieldID += 1;
1764 fieldIDs.push_back(fieldID);
1765 // Increment the field ID for the next field by the number of subfields.
1766 // TODO: Maybe just have elementType be FieldIDTypeInterface ?
1767 fieldID += hw::FieldIdImpl::getMaxFieldID(type);
1768 }
1769 maxFieldID = fieldID;
1770 }
1771
1772 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
1773
1774 static llvm::hash_code hashKey(const KeyTy &key) {
1775 return llvm::hash_value(key);
1776 }
1777
1778 KeyTy getAsKey() const { return KeyTy(elements, isConst); }
1779
1780 static OpenBundleTypeStorage *construct(TypeStorageAllocator &allocator,
1781 KeyTy key) {
1782 return new (allocator.allocate<OpenBundleTypeStorage>())
1783 OpenBundleTypeStorage(std::get<0>(key),
1784 static_cast<bool>(std::get<1>(key)));
1785 }
1786
1787 SmallVector<OpenBundleType::BundleElement, 4> elements;
1788 SmallVector<uint64_t, 4> fieldIDs;
1789 uint64_t maxFieldID;
1790
1791 /// This holds the bits for the type's recursive properties, and can hold a
1792 /// pointer to a passive version of the type.
1794
1795 // Whether this is 'const'.
1797};
1798
1799OpenBundleType OpenBundleType::get(MLIRContext *context,
1800 ArrayRef<BundleElement> elements,
1801 bool isConst) {
1802 return Base::get(context, elements, isConst);
1803}
1804
1805OpenBundleType
1806OpenBundleType::getChecked(function_ref<InFlightDiagnostic()> emitErrorFn,
1807 MLIRContext *context,
1808 ArrayRef<BundleElement> elements, bool isConst) {
1809 if (failed(verify(emitErrorFn, elements, isConst)))
1810 return {};
1811 return get(context, elements, isConst);
1812}
1813
1814auto OpenBundleType::getElements() const -> ArrayRef<BundleElement> {
1815 return getImpl()->elements;
1816}
1817
1818/// Return a pair with the 'isPassive' and 'containsAnalog' bits.
1819RecursiveTypeProperties OpenBundleType::getRecursiveTypeProperties() const {
1820 return getImpl()->props;
1821}
1822
1823OpenBundleType OpenBundleType::getConstType(bool isConst) const {
1824 if (isConst == this->isConst())
1825 return *this;
1826 return get(getContext(), getElements(), isConst);
1827}
1828
1829std::optional<unsigned> OpenBundleType::getElementIndex(StringAttr name) {
1830 for (const auto &it : llvm::enumerate(getElements())) {
1831 auto element = it.value();
1832 if (element.name == name) {
1833 return unsigned(it.index());
1834 }
1835 }
1836 return std::nullopt;
1837}
1838
1839std::optional<unsigned> OpenBundleType::getElementIndex(StringRef name) {
1840 for (const auto &it : llvm::enumerate(getElements())) {
1841 auto element = it.value();
1842 if (element.name.getValue() == name) {
1843 return unsigned(it.index());
1844 }
1845 }
1846 return std::nullopt;
1847}
1848
1849StringAttr OpenBundleType::getElementNameAttr(size_t index) {
1850 assert(index < getNumElements() &&
1851 "index must be less than number of fields in bundle");
1852 return getElements()[index].name;
1853}
1854
1855StringRef OpenBundleType::getElementName(size_t index) {
1856 return getElementNameAttr(index).getValue();
1857}
1858
1859std::optional<OpenBundleType::BundleElement>
1860OpenBundleType::getElement(StringAttr name) {
1861 if (auto maybeIndex = getElementIndex(name))
1862 return getElements()[*maybeIndex];
1863 return std::nullopt;
1864}
1865
1866std::optional<OpenBundleType::BundleElement>
1867OpenBundleType::getElement(StringRef name) {
1868 if (auto maybeIndex = getElementIndex(name))
1869 return getElements()[*maybeIndex];
1870 return std::nullopt;
1871}
1872
1873/// Look up an element by index.
1874OpenBundleType::BundleElement OpenBundleType::getElement(size_t index) {
1875 assert(index < getNumElements() &&
1876 "index must be less than number of fields in bundle");
1877 return getElements()[index];
1878}
1879
1880OpenBundleType::ElementType OpenBundleType::getElementType(StringAttr name) {
1881 auto element = getElement(name);
1882 return element ? element->type : FIRRTLBaseType();
1883}
1884
1885OpenBundleType::ElementType OpenBundleType::getElementType(StringRef name) {
1886 auto element = getElement(name);
1887 return element ? element->type : FIRRTLBaseType();
1888}
1889
1890OpenBundleType::ElementType OpenBundleType::getElementType(size_t index) const {
1891 assert(index < getNumElements() &&
1892 "index must be less than number of fields in bundle");
1893 return getElements()[index].type;
1894}
1895
1896uint64_t OpenBundleType::getFieldID(uint64_t index) const {
1897 return getImpl()->fieldIDs[index];
1898}
1899
1900uint64_t OpenBundleType::getIndexForFieldID(uint64_t fieldID) const {
1901 assert(!getElements().empty() && "Bundle must have >0 fields");
1902 auto fieldIDs = getImpl()->fieldIDs;
1903 auto *it = std::prev(llvm::upper_bound(fieldIDs, fieldID));
1904 return std::distance(fieldIDs.begin(), it);
1905}
1906
1907std::pair<uint64_t, uint64_t>
1908OpenBundleType::getIndexAndSubfieldID(uint64_t fieldID) const {
1909 auto index = getIndexForFieldID(fieldID);
1910 auto elementFieldID = getFieldID(index);
1911 return {index, fieldID - elementFieldID};
1912}
1913
1914std::pair<Type, uint64_t>
1915OpenBundleType::getSubTypeByFieldID(uint64_t fieldID) const {
1916 if (fieldID == 0)
1917 return {*this, 0};
1918 auto subfieldIndex = getIndexForFieldID(fieldID);
1919 auto subfieldType = getElementType(subfieldIndex);
1920 auto subfieldID = fieldID - getFieldID(subfieldIndex);
1921 return {subfieldType, subfieldID};
1922}
1923
1924uint64_t OpenBundleType::getMaxFieldID() const { return getImpl()->maxFieldID; }
1925
1926std::pair<uint64_t, bool>
1927OpenBundleType::projectToChildFieldID(uint64_t fieldID, uint64_t index) const {
1928 auto childRoot = getFieldID(index);
1929 auto rangeEnd = index + 1 >= getNumElements() ? getMaxFieldID()
1930 : (getFieldID(index + 1) - 1);
1931 return std::make_pair(fieldID - childRoot,
1932 fieldID >= childRoot && fieldID <= rangeEnd);
1933}
1934
1935bool OpenBundleType::isConst() const { return getImpl()->isConst; }
1936
1937OpenBundleType::ElementType
1938OpenBundleType::getElementTypePreservingConst(size_t index) {
1939 auto type = getElementType(index);
1940 // TODO: ConstTypeInterface / Trait ?
1941 return TypeSwitch<FIRRTLType, ElementType>(type)
1942 .Case<FIRRTLBaseType, OpenBundleType, OpenVectorType>([&](auto type) {
1943 return type.getConstType(type.isConst() || isConst());
1944 })
1945 .Default(type);
1946}
1947
1948LogicalResult
1949OpenBundleType::verify(function_ref<InFlightDiagnostic()> emitErrorFn,
1950 ArrayRef<BundleElement> elements, bool isConst) {
1951 SmallPtrSet<StringAttr, 4> nameSet;
1952 for (auto &element : elements) {
1953 if (!nameSet.insert(element.name).second)
1954 return emitErrorFn() << "duplicate field name " << element.name
1955 << " in openbundle";
1956 if (FIRRTLType(element.type).containsReference() && isConst)
1957 return emitErrorFn()
1958 << "'const' bundle cannot have references, but element "
1959 << element.name << " has type " << element.type;
1960 if (type_isa<LHSType>(element.type))
1961 return emitErrorFn() << "bundle element " << element.name
1962 << " cannot have a left-hand side type";
1963 if (type_isa<DomainType>(element.type))
1964 return emitErrorFn() << "bundle element " << element.name
1965 << " cannot have a domain type";
1966 }
1967
1968 return success();
1969}
1970
1971//===----------------------------------------------------------------------===//
1972// FVectorType
1973//===----------------------------------------------------------------------===//
1974
1977 using KeyTy = std::tuple<FIRRTLBaseType, size_t, char>;
1978
1980 bool isConst)
1983 props(elementType.getRecursiveTypeProperties()) {
1984 props.containsConst |= isConst;
1985 }
1986
1987 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
1988
1990
1991 static FVectorTypeStorage *construct(TypeStorageAllocator &allocator,
1992 KeyTy key) {
1993 return new (allocator.allocate<FVectorTypeStorage>())
1994 FVectorTypeStorage(std::get<0>(key), std::get<1>(key),
1995 static_cast<bool>(std::get<2>(key)));
1996 }
1997
2000
2001 /// This holds the bits for the type's recursive properties, and can hold a
2002 /// pointer to a passive version of the type.
2006};
2007
2008FVectorType FVectorType::get(FIRRTLBaseType elementType, size_t numElements,
2009 bool isConst) {
2010 return Base::get(elementType.getContext(), elementType, numElements, isConst);
2011}
2012
2013FIRRTLBaseType FVectorType::getElementType() const {
2014 return getImpl()->elementType;
2015}
2016
2017size_t FVectorType::getNumElements() const { return getImpl()->numElements; }
2018
2019/// Return the recursive properties of the type.
2020RecursiveTypeProperties FVectorType::getRecursiveTypeProperties() const {
2021 return getImpl()->props;
2022}
2023
2024/// Return this type with any flip types recursively removed from itself.
2025FIRRTLBaseType FVectorType::getPassiveType() {
2026 auto *impl = getImpl();
2027
2028 // If we've already determined and cached the passive type, use it.
2029 if (impl->passiveType)
2030 return impl->passiveType;
2031
2032 // If this type is already passive, return it and remember for next time.
2033 if (impl->elementType.getRecursiveTypeProperties().isPassive)
2034 return impl->passiveType = *this;
2035
2036 // Otherwise, rebuild a passive version.
2037 auto passiveType = FVectorType::get(getElementType().getPassiveType(),
2038 getNumElements(), isConst());
2039 impl->passiveType = passiveType;
2040 return passiveType;
2041}
2042
2043FVectorType FVectorType::getConstType(bool isConst) const {
2044 if (isConst == this->isConst())
2045 return *this;
2046 return get(getElementType(), getNumElements(), isConst);
2047}
2048
2049FVectorType FVectorType::getAllConstDroppedType() {
2050 if (!containsConst())
2051 return *this;
2052 return get(getElementType().getAllConstDroppedType(), getNumElements(),
2053 false);
2054}
2055
2056/// Return this type with any type aliases recursively removed from itself.
2057FIRRTLBaseType FVectorType::getAnonymousType() {
2058 auto *impl = getImpl();
2059
2060 if (impl->anonymousType)
2061 return impl->anonymousType;
2062
2063 // If this type is already anonymous, return it and remember for next time.
2064 if (!impl->props.containsTypeAlias)
2065 return impl->anonymousType = *this;
2066
2067 // Otherwise, rebuild an anonymous version.
2068 auto anonymousType = FVectorType::get(getElementType().getAnonymousType(),
2069 getNumElements(), isConst());
2070 impl->anonymousType = anonymousType;
2071 return anonymousType;
2072}
2073
2074uint64_t FVectorType::getFieldID(uint64_t index) const {
2075 return 1 + index * (hw::FieldIdImpl::getMaxFieldID(getElementType()) + 1);
2076}
2077
2078uint64_t FVectorType::getIndexForFieldID(uint64_t fieldID) const {
2079 assert(fieldID && "fieldID must be at least 1");
2080 // Divide the field ID by the number of fieldID's per element.
2081 return (fieldID - 1) / (hw::FieldIdImpl::getMaxFieldID(getElementType()) + 1);
2082}
2083
2084std::pair<uint64_t, uint64_t>
2085FVectorType::getIndexAndSubfieldID(uint64_t fieldID) const {
2086 auto index = getIndexForFieldID(fieldID);
2087 auto elementFieldID = getFieldID(index);
2088 return {index, fieldID - elementFieldID};
2089}
2090
2091std::pair<Type, uint64_t>
2092FVectorType::getSubTypeByFieldID(uint64_t fieldID) const {
2093 if (fieldID == 0)
2094 return {*this, 0};
2095 return {getElementType(), getIndexAndSubfieldID(fieldID).second};
2096}
2097
2098uint64_t FVectorType::getMaxFieldID() const {
2099 return getNumElements() *
2100 (hw::FieldIdImpl::getMaxFieldID(getElementType()) + 1);
2101}
2102
2103std::pair<uint64_t, bool>
2104FVectorType::projectToChildFieldID(uint64_t fieldID, uint64_t index) const {
2105 auto childRoot = getFieldID(index);
2106 auto rangeEnd =
2107 index >= getNumElements() ? getMaxFieldID() : (getFieldID(index + 1) - 1);
2108 return std::make_pair(fieldID - childRoot,
2109 fieldID >= childRoot && fieldID <= rangeEnd);
2110}
2111
2112bool FVectorType::isConst() const { return getImpl()->isConst; }
2113
2114FVectorType::ElementType FVectorType::getElementTypePreservingConst() {
2115 auto type = getElementType();
2116 return type.getConstType(type.isConst() || isConst());
2117}
2118
2119//===----------------------------------------------------------------------===//
2120// OpenVectorType
2121//===----------------------------------------------------------------------===//
2122
2124 using KeyTy = std::tuple<FIRRTLType, size_t, char>;
2125
2127 bool isConst)
2129 isConst(static_cast<char>(isConst)) {
2130 props = elementType.getRecursiveTypeProperties();
2131 props.containsConst |= isConst;
2132 }
2133
2134 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
2135
2137
2138 static OpenVectorTypeStorage *construct(TypeStorageAllocator &allocator,
2139 KeyTy key) {
2140 return new (allocator.allocate<OpenVectorTypeStorage>())
2141 OpenVectorTypeStorage(std::get<0>(key), std::get<1>(key),
2142 static_cast<bool>(std::get<2>(key)));
2143 }
2144
2147
2150};
2151
2152OpenVectorType OpenVectorType::get(FIRRTLType elementType, size_t numElements,
2153 bool isConst) {
2154 return Base::get(elementType.getContext(), elementType, numElements, isConst);
2155}
2156
2157OpenVectorType
2158OpenVectorType::getChecked(function_ref<InFlightDiagnostic()> emitErrorFn,
2160 bool isConst) {
2161 if (failed(verify(emitErrorFn, elementType, numElements, isConst)))
2162 return {};
2163 return get(elementType, numElements, isConst);
2164}
2165
2166FIRRTLType OpenVectorType::getElementType() const {
2167 return getImpl()->elementType;
2168}
2169
2170size_t OpenVectorType::getNumElements() const { return getImpl()->numElements; }
2171
2172/// Return the recursive properties of the type.
2173RecursiveTypeProperties OpenVectorType::getRecursiveTypeProperties() const {
2174 return getImpl()->props;
2175}
2176
2177OpenVectorType OpenVectorType::getConstType(bool isConst) const {
2178 if (isConst == this->isConst())
2179 return *this;
2180 return get(getElementType(), getNumElements(), isConst);
2181}
2182
2183uint64_t OpenVectorType::getFieldID(uint64_t index) const {
2184 return 1 + index * (hw::FieldIdImpl::getMaxFieldID(getElementType()) + 1);
2185}
2186
2187uint64_t OpenVectorType::getIndexForFieldID(uint64_t fieldID) const {
2188 assert(fieldID && "fieldID must be at least 1");
2189 // Divide the field ID by the number of fieldID's per element.
2190 return (fieldID - 1) / (hw::FieldIdImpl::getMaxFieldID(getElementType()) + 1);
2191}
2192
2193std::pair<uint64_t, uint64_t>
2194OpenVectorType::getIndexAndSubfieldID(uint64_t fieldID) const {
2195 auto index = getIndexForFieldID(fieldID);
2196 auto elementFieldID = getFieldID(index);
2197 return {index, fieldID - elementFieldID};
2198}
2199
2200std::pair<Type, uint64_t>
2201OpenVectorType::getSubTypeByFieldID(uint64_t fieldID) const {
2202 if (fieldID == 0)
2203 return {*this, 0};
2204 return {getElementType(), getIndexAndSubfieldID(fieldID).second};
2205}
2206
2207uint64_t OpenVectorType::getMaxFieldID() const {
2208 // If this is requirement, make ODS constraint or actual elementType.
2209 return getNumElements() *
2210 (hw::FieldIdImpl::getMaxFieldID(getElementType()) + 1);
2211}
2212
2213std::pair<uint64_t, bool>
2214OpenVectorType::projectToChildFieldID(uint64_t fieldID, uint64_t index) const {
2215 auto childRoot = getFieldID(index);
2216 auto rangeEnd =
2217 index >= getNumElements() ? getMaxFieldID() : (getFieldID(index + 1) - 1);
2218 return std::make_pair(fieldID - childRoot,
2219 fieldID >= childRoot && fieldID <= rangeEnd);
2220}
2221
2222bool OpenVectorType::isConst() const { return getImpl()->isConst; }
2223
2224OpenVectorType::ElementType OpenVectorType::getElementTypePreservingConst() {
2225 auto type = getElementType();
2226 // TODO: ConstTypeInterface / Trait ?
2227 return TypeSwitch<FIRRTLType, ElementType>(type)
2228 .Case<FIRRTLBaseType, OpenBundleType, OpenVectorType>([&](auto type) {
2229 return type.getConstType(type.isConst() || isConst());
2230 })
2231 .Default(type);
2232}
2233
2234LogicalResult
2235OpenVectorType::verify(function_ref<InFlightDiagnostic()> emitErrorFn,
2237 bool isConst) {
2238 if (elementType.containsReference() && isConst)
2239 return emitErrorFn() << "vector cannot be const with references";
2241 return emitErrorFn() << "vector cannot have a left-hand side type";
2243 return emitErrorFn() << "vector cannot have a domain type";
2244 return success();
2245}
2246
2247//===----------------------------------------------------------------------===//
2248// FEnum Type
2249//===----------------------------------------------------------------------===//
2250
2252 using KeyTy = std::tuple<ArrayRef<FEnumType::EnumElement>, char>;
2253
2254 FEnumTypeStorage(ArrayRef<FEnumType::EnumElement> elements, bool isConst)
2256 elements(elements.begin(), elements.end()) {
2257 RecursiveTypeProperties props{true, false, false, isConst,
2258 false, false, false};
2259 dataSize = 0;
2260 for (auto &element : elements) {
2261 auto type = element.type;
2262 auto eltInfo = type.getRecursiveTypeProperties();
2263 props.containsConst |= eltInfo.containsConst;
2264 props.containsTypeAlias |= eltInfo.containsTypeAlias;
2265
2266 dataSize = std::max((size_t)type.getBitWidthOrSentinel(), dataSize);
2267 }
2268 recProps = props;
2269 }
2270
2271 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
2272
2273 KeyTy getAsKey() const { return KeyTy(elements, isConst); }
2274
2275 static llvm::hash_code hashKey(const KeyTy &key) {
2276 return llvm::hash_value(key);
2277 }
2278
2279 static FEnumTypeStorage *construct(TypeStorageAllocator &allocator,
2280 KeyTy key) {
2281 return new (allocator.allocate<FEnumTypeStorage>())
2282 FEnumTypeStorage(std::get<0>(key), static_cast<bool>(std::get<1>(key)));
2283 }
2284
2285 SmallVector<FEnumType::EnumElement, 4> elements;
2287 size_t dataSize;
2289};
2290
2291FEnumType FEnumType::get(::mlir::MLIRContext *context,
2292 ArrayRef<EnumElement> elements, bool isConst) {
2293 return Base::get(context, elements, isConst);
2294}
2295
2296ArrayRef<FEnumType::EnumElement> FEnumType::getElements() const {
2297 return getImpl()->elements;
2298}
2299
2300FEnumType FEnumType::getConstType(bool isConst) const {
2301 return get(getContext(), getElements(), isConst);
2302}
2303
2304FEnumType FEnumType::getAllConstDroppedType() {
2305 if (!containsConst())
2306 return *this;
2307
2308 SmallVector<EnumElement> constDroppedElements(
2309 llvm::map_range(getElements(), [](EnumElement element) {
2310 element.type = element.type.getAllConstDroppedType();
2311 return element;
2312 }));
2313 return get(getContext(), constDroppedElements, false);
2314}
2315
2316/// Return a pair with the 'isPassive' and 'containsAnalog' bits.
2317RecursiveTypeProperties FEnumType::getRecursiveTypeProperties() const {
2318 return getImpl()->recProps;
2319}
2320
2321std::optional<unsigned> FEnumType::getElementIndex(StringAttr name) {
2322 for (const auto &it : llvm::enumerate(getElements())) {
2323 auto element = it.value();
2324 if (element.name == name) {
2325 return unsigned(it.index());
2326 }
2327 }
2328 return std::nullopt;
2329}
2330
2331size_t FEnumType::getBitWidth() { return getDataWidth() + getTagWidth(); }
2332
2333size_t FEnumType::getDataWidth() { return getImpl()->dataSize; }
2334
2335size_t FEnumType::getTagWidth() {
2336 if (getElements().size() == 0)
2337 return 0;
2338 // Each tag has the same type.
2339 return cast<IntegerType>(getElements()[0].value.getType()).getWidth();
2340}
2341
2342std::optional<unsigned> FEnumType::getElementIndex(StringRef name) {
2343 for (const auto &it : llvm::enumerate(getElements())) {
2344 auto element = it.value();
2345 if (element.name.getValue() == name) {
2346 return unsigned(it.index());
2347 }
2348 }
2349 return std::nullopt;
2350}
2351
2352StringAttr FEnumType::getElementNameAttr(size_t index) {
2353 assert(index < getNumElements() &&
2354 "index must be less than number of fields in enum");
2355 return getElements()[index].name;
2356}
2357
2358StringRef FEnumType::getElementName(size_t index) {
2359 return getElementNameAttr(index).getValue();
2360}
2361
2362IntegerAttr FEnumType::getElementValueAttr(size_t index) {
2363 return getElements()[index].value;
2364}
2365
2366APInt FEnumType::getElementValue(size_t index) {
2367 return getElementValueAttr(index).getValue();
2368}
2369
2370FIRRTLBaseType FEnumType::getElementType(size_t index) {
2371 return getElements()[index].type;
2372}
2373
2374std::optional<FEnumType::EnumElement> FEnumType::getElement(StringAttr name) {
2375 if (auto maybeIndex = getElementIndex(name))
2376 return getElements()[*maybeIndex];
2377 return std::nullopt;
2378}
2379
2380std::optional<FEnumType::EnumElement> FEnumType::getElement(StringRef name) {
2381 if (auto maybeIndex = getElementIndex(name))
2382 return getElements()[*maybeIndex];
2383 return std::nullopt;
2384}
2385
2386/// Look up an element by index.
2387FEnumType::EnumElement FEnumType::getElement(size_t index) {
2388 assert(index < getNumElements() &&
2389 "index must be less than number of fields in enum");
2390 return getElements()[index];
2391}
2392
2393FIRRTLBaseType FEnumType::getElementType(StringAttr name) {
2394 auto element = getElement(name);
2395 return element ? element->type : FIRRTLBaseType();
2396}
2397
2398FIRRTLBaseType FEnumType::getElementType(StringRef name) {
2399 auto element = getElement(name);
2400 return element ? element->type : FIRRTLBaseType();
2401}
2402
2403FIRRTLBaseType FEnumType::getElementType(size_t index) const {
2404 assert(index < getNumElements() &&
2405 "index must be less than number of fields in enum");
2406 return getElements()[index].type;
2407}
2408
2409FIRRTLBaseType FEnumType::getElementTypePreservingConst(size_t index) {
2410 auto type = getElementType(index);
2411 return type.getConstType(type.isConst() || isConst());
2412}
2413
2414LogicalResult FEnumType::verify(function_ref<InFlightDiagnostic()> emitErrorFn,
2415 ArrayRef<EnumElement> elements, bool isConst) {
2416 bool first = true;
2417 IntegerAttr previous;
2418 SmallPtrSet<Attribute, 4> nameSet;
2419
2420 for (auto &elt : elements) {
2421 auto r = elt.type.getRecursiveTypeProperties();
2422 if (!r.isPassive)
2423 return emitErrorFn() << "enum field " << elt.name << " not passive";
2424 if (r.containsAnalog)
2425 return emitErrorFn() << "enum field " << elt.name << " contains analog";
2426 if (r.hasUninferredWidth)
2427 return emitErrorFn() << "enum field " << elt.name
2428 << " has uninferred width";
2429 if (r.hasUninferredReset)
2430 return emitErrorFn() << "enum field " << elt.name
2431 << " has uninferred reset";
2432 if (r.containsConst && !isConst)
2433 return emitErrorFn() << "enum with 'const' elements must be 'const'";
2434 // Ensure that each tag has a unique name.
2435 if (!nameSet.insert(elt.name).second)
2436 return emitErrorFn() << "duplicate variant name " << elt.name
2437 << " in enum";
2438 // Ensure that each tag is increasing and unique.
2439 if (first) {
2440 previous = elt.value;
2441 first = false;
2442 } else {
2443 auto current = elt.value;
2444 if (previous.getType() != current.getType())
2445 return emitErrorFn() << "enum variant " << elt.name << " has type"
2446 << current.getType()
2447 << " which is different than previous variant "
2448 << previous.getType();
2449
2450 if (previous.getValue().getBitWidth() != current.getValue().getBitWidth())
2451 return emitErrorFn() << "enum variant " << elt.name << " has bitwidth"
2452 << current.getValue().getBitWidth()
2453 << " which is different than previous variant "
2454 << previous.getValue().getBitWidth();
2455 if (previous.getValue().uge(current.getValue()))
2456 return emitErrorFn()
2457 << "enum variant " << elt.name << " has value " << current
2458 << " which is not greater than previous variant " << previous;
2459 }
2460 // TODO: exclude reference containing
2461 }
2462 return success();
2463}
2464
2465/// Return this type with any type aliases recursively removed from itself.
2466FIRRTLBaseType FEnumType::getAnonymousType() {
2467 auto *impl = getImpl();
2468
2469 if (impl->anonymousType)
2470 return impl->anonymousType;
2471
2472 if (!impl->recProps.containsTypeAlias)
2473 return impl->anonymousType = *this;
2474
2475 SmallVector<FEnumType::EnumElement, 4> elements;
2476
2477 for (auto element : getElements())
2478 elements.push_back(
2479 {element.name, element.value, element.type.getAnonymousType()});
2480 return impl->anonymousType = FEnumType::get(getContext(), elements);
2481}
2482
2483//===----------------------------------------------------------------------===//
2484// BaseTypeAliasType
2485//===----------------------------------------------------------------------===//
2486
2489 using KeyTy = std::tuple<StringAttr, FIRRTLBaseType>;
2490
2494
2495 bool operator==(const KeyTy &key) const { return key == getAsKey(); }
2496
2497 KeyTy getAsKey() const { return KeyTy(name, innerType); }
2498
2499 static llvm::hash_code hashKey(const KeyTy &key) {
2500 return llvm::hash_value(key);
2501 }
2502
2503 static BaseTypeAliasStorage *construct(TypeStorageAllocator &allocator,
2504 KeyTy key) {
2505 return new (allocator.allocate<BaseTypeAliasStorage>())
2506 BaseTypeAliasStorage(std::get<0>(key), std::get<1>(key));
2507 }
2508 StringAttr name;
2511};
2512
2513auto BaseTypeAliasType::get(StringAttr name, FIRRTLBaseType innerType)
2514 -> BaseTypeAliasType {
2515 return Base::get(name.getContext(), name, innerType);
2516}
2517
2518auto BaseTypeAliasType::getName() const -> StringAttr {
2519 return getImpl()->name;
2520}
2521
2522auto BaseTypeAliasType::getInnerType() const -> FIRRTLBaseType {
2523 return getImpl()->innerType;
2524}
2525
2526FIRRTLBaseType BaseTypeAliasType::getAnonymousType() {
2527 auto *impl = getImpl();
2528 if (impl->anonymousType)
2529 return impl->anonymousType;
2530 return impl->anonymousType = getInnerType().getAnonymousType();
2531}
2532
2533FIRRTLBaseType BaseTypeAliasType::getPassiveType() {
2534 return getModifiedType(getInnerType().getPassiveType());
2535}
2536
2537RecursiveTypeProperties BaseTypeAliasType::getRecursiveTypeProperties() const {
2538 auto rtp = getInnerType().getRecursiveTypeProperties();
2539 rtp.containsTypeAlias = true;
2540 return rtp;
2541}
2542
2543// If a given `newInnerType` is identical to innerType, return `*this`
2544// because we can reuse the type alias. Otherwise return `newInnerType`.
2546BaseTypeAliasType::getModifiedType(FIRRTLBaseType newInnerType) const {
2547 if (newInnerType == getInnerType())
2548 return *this;
2549 return newInnerType;
2550}
2551
2552// FieldIDTypeInterface implementation.
2553FIRRTLBaseType BaseTypeAliasType::getAllConstDroppedType() {
2554 return getModifiedType(getInnerType().getAllConstDroppedType());
2555}
2556
2557FIRRTLBaseType BaseTypeAliasType::getConstType(bool isConst) const {
2558 return getModifiedType(getInnerType().getConstType(isConst));
2559}
2560
2561std::pair<Type, uint64_t>
2562BaseTypeAliasType::getSubTypeByFieldID(uint64_t fieldID) const {
2563 return hw::FieldIdImpl::getSubTypeByFieldID(getInnerType(), fieldID);
2564}
2565
2566uint64_t BaseTypeAliasType::getMaxFieldID() const {
2567 return hw::FieldIdImpl::getMaxFieldID(getInnerType());
2568}
2569
2570std::pair<uint64_t, bool>
2571BaseTypeAliasType::projectToChildFieldID(uint64_t fieldID,
2572 uint64_t index) const {
2573 return hw::FieldIdImpl::projectToChildFieldID(getInnerType(), fieldID, index);
2574}
2575
2576uint64_t BaseTypeAliasType::getIndexForFieldID(uint64_t fieldID) const {
2577 return hw::FieldIdImpl::getIndexForFieldID(getInnerType(), fieldID);
2578}
2579
2580uint64_t BaseTypeAliasType::getFieldID(uint64_t index) const {
2581 return hw::FieldIdImpl::getFieldID(getInnerType(), index);
2582}
2583
2584std::pair<uint64_t, uint64_t>
2585BaseTypeAliasType::getIndexAndSubfieldID(uint64_t fieldID) const {
2586 return hw::FieldIdImpl::getIndexAndSubfieldID(getInnerType(), fieldID);
2587}
2588
2589//===----------------------------------------------------------------------===//
2590// LHSType
2591//===----------------------------------------------------------------------===//
2592
2593LHSType LHSType::get(FIRRTLBaseType type) {
2594 return LHSType::get(type.getContext(), type);
2595}
2596
2597LogicalResult LHSType::verify(function_ref<InFlightDiagnostic()> emitError,
2598 FIRRTLBaseType type) {
2599 if (type.containsAnalog())
2600 return emitError() << "lhs type cannot contain an AnalogType";
2601 if (!type.isPassive())
2602 return emitError() << "lhs type cannot contain a non-passive type";
2603 if (type.containsReference())
2604 return emitError() << "lhs type cannot contain a reference";
2605 if (type_isa<LHSType>(type))
2606 return emitError() << "lhs type cannot contain a lhs type";
2607
2608 return success();
2609}
2610
2611//===----------------------------------------------------------------------===//
2612// RefType
2613//===----------------------------------------------------------------------===//
2614
2615auto RefType::get(FIRRTLBaseType type, bool forceable, SymbolRefAttr layer)
2616 -> RefType {
2617 return Base::get(type.getContext(), type, forceable, layer);
2618}
2619
2620auto RefType::verify(function_ref<InFlightDiagnostic()> emitErrorFn,
2621 FIRRTLBaseType base, bool forceable, SymbolRefAttr layer)
2622 -> LogicalResult {
2623 if (!base.isPassive())
2624 return emitErrorFn() << "reference base type must be passive";
2625 if (forceable && base.containsConst())
2626 return emitErrorFn()
2627 << "forceable reference base type cannot contain const";
2628 return success();
2629}
2630
2631RecursiveTypeProperties RefType::getRecursiveTypeProperties() const {
2632 auto rtp = getType().getRecursiveTypeProperties();
2633 rtp.containsReference = true;
2634 // References are not "passive", per FIRRTL spec.
2635 rtp.isPassive = false;
2636 return rtp;
2637}
2638
2639//===----------------------------------------------------------------------===//
2640// AnalogType
2641//===----------------------------------------------------------------------===//
2642
2643AnalogType AnalogType::get(mlir::MLIRContext *context) {
2644 return AnalogType::get(context, -1, false);
2645}
2646
2647AnalogType AnalogType::get(mlir::MLIRContext *context,
2648 std::optional<int32_t> width, bool isConst) {
2649 return AnalogType::get(context, width ? *width : -1, isConst);
2650}
2651
2652LogicalResult AnalogType::verify(function_ref<InFlightDiagnostic()> emitError,
2653 int32_t widthOrSentinel, bool isConst) {
2654 if (widthOrSentinel < -1)
2655 return emitError() << "invalid width";
2656 return success();
2657}
2658
2659int32_t AnalogType::getWidthOrSentinel() const { return getImpl()->width; }
2660
2661AnalogType AnalogType::getConstType(bool isConst) const {
2662 if (isConst == this->isConst())
2663 return *this;
2664 return get(getContext(), getWidthOrSentinel(), isConst);
2665}
2666
2667//===----------------------------------------------------------------------===//
2668// ClockType
2669//===----------------------------------------------------------------------===//
2670
2671ClockType ClockType::getConstType(bool isConst) const {
2672 if (isConst == this->isConst())
2673 return *this;
2674 return get(getContext(), isConst);
2675}
2676
2677//===----------------------------------------------------------------------===//
2678// ResetType
2679//===----------------------------------------------------------------------===//
2680
2681ResetType ResetType::getConstType(bool isConst) const {
2682 if (isConst == this->isConst())
2683 return *this;
2684 return get(getContext(), isConst);
2685}
2686
2687//===----------------------------------------------------------------------===//
2688// AsyncResetType
2689//===----------------------------------------------------------------------===//
2690
2691AsyncResetType AsyncResetType::getConstType(bool isConst) const {
2692 if (isConst == this->isConst())
2693 return *this;
2694 return get(getContext(), isConst);
2695}
2696
2697//===----------------------------------------------------------------------===//
2698// ClassType
2699//===----------------------------------------------------------------------===//
2700
2702 using KeyTy = std::tuple<FlatSymbolRefAttr, ArrayRef<ClassElement>>;
2703
2704 static ClassTypeStorage *construct(TypeStorageAllocator &allocator,
2705 KeyTy key) {
2706 auto name = std::get<0>(key);
2707 auto elements = allocator.copyInto(std::get<1>(key));
2708
2709 // build the field ID table
2710 SmallVector<uint64_t, 4> ids;
2711 uint64_t id = 0;
2712 ids.reserve(elements.size());
2713 for (auto &element : elements) {
2714 id += 1;
2715 ids.push_back(id);
2716 id += hw::FieldIdImpl::getMaxFieldID(element.type);
2717 }
2718
2719 auto fieldIDs = allocator.copyInto(ArrayRef(ids));
2720 auto maxFieldID = id;
2721
2722 return new (allocator.allocate<ClassTypeStorage>())
2724 }
2725
2726 ClassTypeStorage(FlatSymbolRefAttr name, ArrayRef<ClassElement> elements,
2727 ArrayRef<uint64_t> fieldIDs, uint64_t maxFieldID)
2730
2731 bool operator==(const KeyTy &key) const { return getAsKey() == key; }
2732
2733 KeyTy getAsKey() const { return KeyTy(name, elements); }
2734
2735 FlatSymbolRefAttr name;
2736 ArrayRef<ClassElement> elements;
2737 ArrayRef<uint64_t> fieldIDs;
2738 uint64_t maxFieldID;
2739};
2740
2741ClassType ClassType::get(FlatSymbolRefAttr name,
2742 ArrayRef<ClassElement> elements) {
2743 return get(name.getContext(), name, elements);
2744}
2745
2746StringRef ClassType::getName() const {
2747 return getNameAttr().getAttr().getValue();
2748}
2749
2750FlatSymbolRefAttr ClassType::getNameAttr() const { return getImpl()->name; }
2751
2752ArrayRef<ClassElement> ClassType::getElements() const {
2753 return getImpl()->elements;
2754}
2755
2756const ClassElement &ClassType::getElement(IntegerAttr index) const {
2757 return getElement(index.getValue().getZExtValue());
2758}
2759
2760const ClassElement &ClassType::getElement(size_t index) const {
2761 return getElements()[index];
2762}
2763
2764std::optional<uint64_t> ClassType::getElementIndex(StringRef fieldName) const {
2765 for (const auto [i, e] : llvm::enumerate(getElements()))
2766 if (fieldName == e.name)
2767 return i;
2768 return {};
2769}
2770
2771void ClassType::printInterface(AsmPrinter &p) const {
2772 p.printSymbolName(getName());
2773 p << "(";
2774 bool first = true;
2775 for (const auto &element : getElements()) {
2776 if (!first)
2777 p << ", ";
2778 p << element.direction << " ";
2779 p.printKeywordOrString(element.name);
2780 p << ": " << element.type;
2781 first = false;
2782 }
2783 p << ")";
2784}
2785
2786uint64_t ClassType::getFieldID(uint64_t index) const {
2787 return getImpl()->fieldIDs[index];
2788}
2789
2790uint64_t ClassType::getIndexForFieldID(uint64_t fieldID) const {
2791 assert(!getElements().empty() && "Class must have >0 fields");
2792 auto fieldIDs = getImpl()->fieldIDs;
2793 auto *it = std::prev(llvm::upper_bound(fieldIDs, fieldID));
2794 return std::distance(fieldIDs.begin(), it);
2795}
2796
2797std::pair<uint64_t, uint64_t>
2798ClassType::getIndexAndSubfieldID(uint64_t fieldID) const {
2799 auto index = getIndexForFieldID(fieldID);
2800 auto elementFieldID = getFieldID(index);
2801 return {index, fieldID - elementFieldID};
2802}
2803
2804std::pair<Type, uint64_t>
2805ClassType::getSubTypeByFieldID(uint64_t fieldID) const {
2806 if (fieldID == 0)
2807 return {*this, 0};
2808 auto subfieldIndex = getIndexForFieldID(fieldID);
2809 auto subfieldType = getElement(subfieldIndex).type;
2810 auto subfieldID = fieldID - getFieldID(subfieldIndex);
2811 return {subfieldType, subfieldID};
2812}
2813
2814uint64_t ClassType::getMaxFieldID() const { return getImpl()->maxFieldID; }
2815
2816std::pair<uint64_t, bool>
2817ClassType::projectToChildFieldID(uint64_t fieldID, uint64_t index) const {
2818 auto childRoot = getFieldID(index);
2819 auto rangeEnd = index + 1 >= getNumElements() ? getMaxFieldID()
2820 : (getFieldID(index + 1) - 1);
2821 return std::make_pair(fieldID - childRoot,
2822 fieldID >= childRoot && fieldID <= rangeEnd);
2823}
2824
2825namespace {
2826/// Helper to parse interface-like types (ClassType, DomainType).
2827/// This encapsulates the common pattern of parsing @SymbolName(field, field,
2828/// ...)
2829struct InterfaceParser {
2830 AsmParser &parser;
2831
2832 InterfaceParser(AsmParser &parser) : parser(parser) {}
2833
2834 /// Parse the common structure: @SymbolName(field, field, ...)
2835 template <typename FieldContainer>
2836 ParseResult parse(
2837 function_ref<ParseResult(FieldContainer &, AsmParser &parser)> parseField,
2838 StringAttr &symbolName, FieldContainer &fields) {
2839
2840 if (parser.parseSymbolName(symbolName))
2841 return failure();
2842
2843 // Parse required parentheses
2844 if (parser.parseLParen())
2845 return failure();
2846
2847 // Check for empty list (immediate closing paren)
2848 if (failed(parser.parseOptionalRParen())) {
2849 auto parseElement = [&]() -> ParseResult {
2850 return parseField(fields, parser);
2851 };
2852
2853 if (parser.parseCommaSeparatedList(parseElement) || parser.parseRParen())
2854 return failure();
2855 }
2856
2857 return success();
2858 }
2859};
2860} // namespace
2861
2862ParseResult ClassType::parseInterface(AsmParser &parser, ClassType &result) {
2863 InterfaceParser helper(parser);
2864
2865 auto parseField = [](SmallVector<ClassElement> &elements,
2866 AsmParser &parser) -> ParseResult {
2867 // Parse port direction.
2869 if (succeeded(parser.parseOptionalKeyword("out")))
2871 else if (succeeded(parser.parseKeyword("in", "or 'out'")))
2873 else
2874 return failure();
2875
2876 // Parse port name.
2877 std::string keyword;
2878 if (parser.parseKeywordOrString(&keyword))
2879 return failure();
2880 StringAttr name = StringAttr::get(parser.getContext(), keyword);
2881
2882 // Parse port type.
2883 Type type;
2884 if (parser.parseColonType(type))
2885 return failure();
2886
2887 elements.emplace_back(name, type, direction);
2888 return success();
2889 };
2890
2891 StringAttr symbolName;
2892 SmallVector<ClassElement> elements;
2893 if (helper.parse<SmallVector<ClassElement>>(parseField, symbolName, elements))
2894 return failure();
2895
2896 result = ClassType::get(FlatSymbolRefAttr::get(symbolName), elements);
2897 return success();
2898}
2899
2900//===----------------------------------------------------------------------===//
2901// DomainType
2902//===----------------------------------------------------------------------===//
2903
2904ParseResult DomainType::parseInterface(AsmParser &parser, DomainType &result) {
2905 InterfaceParser helper(parser);
2906
2907 auto parseField = [](SmallVector<Attribute> &fields,
2908 AsmParser &parser) -> ParseResult {
2909 std::string fieldNameStr;
2910 Type fieldTypeRaw;
2911 if (parser.parseKeywordOrString(&fieldNameStr) || parser.parseColon() ||
2912 parser.parseType(fieldTypeRaw))
2913 return failure();
2914
2915 auto fieldType = dyn_cast<PropertyType>(fieldTypeRaw);
2916 if (!fieldType)
2917 return parser.emitError(parser.getCurrentLocation(),
2918 "expected property type");
2919
2920 auto fieldName = StringAttr::get(parser.getContext(), fieldNameStr);
2921 fields.push_back(
2922 DomainFieldAttr::get(parser.getContext(), fieldName, fieldType));
2923 return success();
2924 };
2925
2926 StringAttr symbolName;
2927 SmallVector<Attribute> fields;
2928 if (helper.parse<SmallVector<Attribute>>(parseField, symbolName, fields))
2929 return failure();
2930
2931 result = DomainType::get(FlatSymbolRefAttr::get(symbolName),
2932 ArrayAttr::get(parser.getContext(), fields));
2933 return success();
2934}
2935
2936DomainType DomainType::get(FlatSymbolRefAttr name, ArrayAttr fields) {
2937 return Base::get(name.getContext(), name, fields);
2938}
2939
2940DomainType DomainType::getFromDomainOp(DomainOp domainOp) {
2941 auto name = FlatSymbolRefAttr::get(domainOp.getNameAttr());
2942 return DomainType::get(name, domainOp.getFieldsAttr());
2943}
2944
2945DomainFieldAttr DomainType::getField(size_t index) const {
2946 assert(index < getNumFields() && "index out of bounds");
2947 return cast<DomainFieldAttr>(getFields()[index]);
2948}
2949
2950std::optional<uint64_t> DomainType::getFieldIndex(StringRef fieldName) const {
2951 for (const auto [i, attr] : llvm::enumerate(getFields())) {
2952 auto field = cast<DomainFieldAttr>(attr);
2953 if (fieldName == field.getName())
2954 return i;
2955 }
2956 return {};
2957}
2958
2959std::pair<Type, uint64_t>
2960DomainType::getSubTypeByFieldID(uint64_t fieldID) const {
2961 if (fieldID == 0)
2962 return {*this, 0};
2963
2964 // Domain fields don't have sub-fieldIDs, so fieldID directly maps to field
2965 // index
2966 if (fieldID > getNumFields())
2967 return {Type(), fieldID};
2968
2969 return {getField(fieldID - 1).getType(), 0};
2970}
2971
2972uint64_t DomainType::getMaxFieldID() const {
2973 // Each field gets one fieldID
2974 return getNumFields();
2975}
2976
2977std::pair<uint64_t, bool>
2978DomainType::projectToChildFieldID(uint64_t fieldID, uint64_t index) const {
2979 // Domain fields are flat, so projection is simple
2980 if (index >= getNumFields())
2981 return {0, false};
2982
2983 uint64_t childFieldID = index + 1;
2984 return {0, fieldID == childFieldID};
2985}
2986
2987uint64_t DomainType::getFieldID(uint64_t index) const {
2988 // Domain fields are flat, so fieldID is just index + 1
2989 assert(index < getNumFields() && "index out of bounds");
2990 return index + 1;
2991}
2992
2993uint64_t DomainType::getIndexForFieldID(uint64_t fieldID) const {
2994 // Domain fields are flat, so index is just fieldID - 1
2995 assert(fieldID > 0 && fieldID <= getNumFields() && "fieldID out of bounds");
2996 return fieldID - 1;
2997}
2998
2999std::pair<uint64_t, uint64_t>
3000DomainType::getIndexAndSubfieldID(uint64_t fieldID) const {
3001 // Domain fields are flat (no sub-fields), so subfieldID is always 0
3002 assert(fieldID > 0 && fieldID <= getNumFields() && "fieldID out of bounds");
3003 return {fieldID - 1, 0};
3004}
3005
3006LogicalResult
3007DomainType::verifySymbolUses(Operation *op,
3008 SymbolTableCollection &symbolTable) const {
3009 // Find the circuit op to look up the domain definition
3010 auto circuitOp = op->getParentOfType<CircuitOp>();
3011 if (!circuitOp)
3012 return op->emitError() << "domain type used outside of a circuit";
3013
3014 // Check that the symbol exists
3015 auto *symbol = symbolTable.lookupSymbolIn(circuitOp, getName());
3016 if (!symbol)
3017 return op->emitError() << "domain type references undefined symbol '"
3018 << getName().getValue() << "'";
3019
3020 // Check that the symbol is a domain
3021 auto domainOp = dyn_cast<DomainOp>(symbol);
3022 if (!domainOp)
3023 return op->emitError() << "domain type references symbol '"
3024 << getName().getValue() << "' which is not a domain";
3025
3026 // Verify that the domain type fields match the domain definition
3027 auto expectedFields = domainOp.getFieldsAttr();
3028 auto actualFields = getFields();
3029
3030 // Check field count
3031 if (actualFields.size() != expectedFields.size())
3032 return op->emitError() << "domain type has " << actualFields.size()
3033 << " fields but domain definition has "
3034 << expectedFields.size() << " fields";
3035
3036 // Check each field
3037 for (size_t i = 0; i < actualFields.size(); ++i) {
3038 auto actualField = cast<DomainFieldAttr>(actualFields[i]);
3039 auto expectedField = cast<DomainFieldAttr>(expectedFields[i]);
3040
3041 // Check field name
3042 if (actualField.getName() != expectedField.getName())
3043 return op->emitError() << "domain type field " << i << " has name '"
3044 << actualField.getName().getValue()
3045 << "' but domain definition expects '"
3046 << expectedField.getName().getValue() << "'";
3047
3048 // Check field type
3049 if (actualField.getType() != expectedField.getType())
3050 return op->emitError()
3051 << "domain type field '" << actualField.getName().getValue()
3052 << "' has type " << actualField.getType()
3053 << " but domain definition expects " << expectedField.getType();
3054 }
3055
3056 return success();
3057}
3058
3059//===----------------------------------------------------------------------===//
3060// FIRRTLDialect
3061//===----------------------------------------------------------------------===//
3062
3063void FIRRTLDialect::registerTypes() {
3064 addTypes<
3065#define GET_TYPEDEF_LIST
3066#include "circt/Dialect/FIRRTL/FIRRTLTypes.cpp.inc"
3067 >();
3068}
3069
3070// Get the bit width for this type, return None if unknown. Unlike
3071// getBitWidthOrSentinel(), this can recursively compute the bitwidth of
3072// aggregate types. For bundle and vectors, recursively get the width of each
3073// field element and return the total bit width of the aggregate type. This
3074// returns None, if any of the bundle fields is a flip type, or ground type with
3075// unknown bit width.
3076std::optional<int64_t> firrtl::getBitWidth(FIRRTLBaseType type,
3077 bool ignoreFlip) {
3078 std::function<std::optional<int64_t>(FIRRTLBaseType)> getWidth =
3079 [&](FIRRTLBaseType type) -> std::optional<int64_t> {
3080 return TypeSwitch<FIRRTLBaseType, std::optional<int64_t>>(type)
3081 .Case<BundleType>([&](BundleType bundle) -> std::optional<int64_t> {
3082 int64_t width = 0;
3083 for (auto &elt : bundle) {
3084 if (elt.isFlip && !ignoreFlip)
3085 return std::nullopt;
3086 auto w = getBitWidth(elt.type);
3087 if (!w.has_value())
3088 return std::nullopt;
3089 width += *w;
3090 }
3091 return width;
3092 })
3093 .Case<FEnumType>([&](FEnumType fenum) -> std::optional<int64_t> {
3094 int64_t width = 0;
3095 for (auto &elt : fenum) {
3096 auto w = getBitWidth(elt.type);
3097 if (!w.has_value())
3098 return std::nullopt;
3099 width = std::max(width, *w);
3100 }
3101 return width + fenum.getTagWidth();
3102 })
3103 .Case<FVectorType>([&](auto vector) -> std::optional<int64_t> {
3104 auto w = getBitWidth(vector.getElementType());
3105 if (!w.has_value())
3106 return std::nullopt;
3107 return *w * vector.getNumElements();
3108 })
3109 .Case<IntType>([&](IntType iType) { return iType.getWidth(); })
3110 .Case<ClockType, ResetType, AsyncResetType>([](Type) { return 1; })
3111 .Default([&](auto t) { return std::nullopt; });
3112 };
3113 return getWidth(type);
3114}
assert(baseType &&"element must be base type")
MlirType uint64_t numElements
Definition CHIRRTL.cpp:30
MlirType elementType
Definition CHIRRTL.cpp:29
static std::unique_ptr< Context > context
static ParseResult parseFIRRTLBaseType(FIRRTLBaseType &result, StringRef name, AsmParser &parser)
static ParseResult parseFIRRTLPropertyType(PropertyType &result, StringRef name, AsmParser &parser)
static LogicalResult customTypePrinter(Type type, AsmPrinter &os)
Print a type with a custom printer implementation.
static OptionalParseResult customTypeParser(AsmParser &parser, StringRef name, Type &result)
Parse a type with a custom parser implementation.
static ParseResult parseType(Type &result, StringRef name, AsmParser &parser)
Parse a type defined by this dialect.
static bool areBundleElementsEquivalent(BundleType::BundleElement destElement, BundleType::BundleElement srcElement, bool destOuterTypeIsConst, bool srcOuterTypeIsConst, bool requiresSameWidth)
Helper to implement the equivalence logic for a pair of bundle elements.
@ ContainsAnalogBitMask
Bit set if the type contains an analog type.
@ HasUninferredWidthBitMask
Bit set fi the type has any uninferred bit widths.
@ IsPassiveBitMask
Bit set if the type only contains passive elements.
static ParseResult parseFIRRTLType(FIRRTLType &result, StringRef name, AsmParser &parser)
Parse a FIRRTLType with a name that has already been parsed.
static unsigned getFieldID(BundleType type, unsigned index)
static unsigned getIndexForFieldID(BundleType type, unsigned fieldID)
static unsigned getMaxFieldID(FIRRTLBaseType type)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
static InstancePath empty
FIRRTLBaseType getConstType(bool isConst) const
Return a 'const' or non-'const' version of this type.
FIRRTLBaseType getAnonymousType()
Return this type with any type alias types recursively removed from itself.
bool isResetType()
Return true if this is a valid "reset" type.
FIRRTLBaseType getMaskType()
Return this type with all ground types replaced with UInt<1>.
FIRRTLBaseType getPassiveType()
Return this type with any flip types recursively removed from itself.
int32_t getBitWidthOrSentinel()
If this is an IntType, AnalogType, or sugar type for a single bit (Clock, Reset, etc) then return the...
FIRRTLBaseType getAllConstDroppedType()
Return this type with a 'const' modifiers dropped.
bool isPassive() const
Return true if this is a "passive" type - one that contains no "flip" types recursively within itself...
FIRRTLBaseType getWidthlessType()
Return this type with widths of all ground types removed.
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
This class implements the same functionality as TypeSwitch except that it uses firrtl::type_dyn_cast ...
FIRRTLTypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
bool containsReference()
Return true if this is or contains a Reference type.
bool isGround()
Return true if this is a 'ground' type, aka a non-aggregate type.
RecursiveTypeProperties getRecursiveTypeProperties() const
Return the recursive properties of the type, containing the isPassive, containsAnalog,...
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
This is the common base class between SIntType and UIntType.
IntType getConstType(bool isConst) const
Return a 'const' or non-'const' version of this type.
int32_t getWidthOrSentinel() const
Return the width of this type, or -1 if it has none specified.
static IntType get(MLIRContext *context, bool isSigned, int32_t widthOrSentinel=-1, bool isConst=false)
Return an SIntType or UIntType with the specified signedness, width, and constness.
std::optional< int32_t > getWidth() const
Return an optional containing the width, if the width is known (or empty if width is unknown).
Represents a limited word-length unsigned integer in SystemC as described in IEEE 1666-2011 ยง7....
static UIntType get(MLIRContext *context, unsigned width)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:56
BaseTy type_cast(Type type)
Direction
This represents the direction of a single port.
Definition FIRRTLEnums.h:27
ParseResult parseNestedType(FIRRTLType &result, AsmParser &parser)
Parse a FIRRTLType.
bool areAnonymousTypesEquivalent(FIRRTLBaseType lhs, FIRRTLBaseType rhs)
Return true if anonymous types of given arguments are equivalent by pointer comparison.
ParseResult parseNestedBaseType(FIRRTLBaseType &result, AsmParser &parser)
bool isTypeInOut(mlir::Type type)
Returns true if the given type has some flipped (aka unaligned) dataflow.
bool areTypesRefCastable(Type dstType, Type srcType)
Return true if destination ref type can be cast from source ref type, per FIRRTL spec rules they must...
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
mlir::Type getPassiveType(mlir::Type anyBaseFIRRTLType)
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
bool containsConst(Type type)
Returns true if the type is or contains a 'const' type whose value is guaranteed to be unchanging at ...
bool hasZeroBitWidth(FIRRTLType type)
Return true if the type has zero bit width.
BaseTy type_dyn_cast(Type type)
void printNestedType(Type type, AsmPrinter &os)
Print a type defined by this dialect.
bool isConst(Type type)
Returns true if this is a 'const' type whose value is guaranteed to be unchanging at circuit executio...
bool hasHardwareElements(FIRRTLType type)
Return true if the given type contains any elements of hardware types.
bool areTypesConstCastable(FIRRTLType destType, FIRRTLType srcType, bool srcOuterTypeIsConst=false)
Returns whether the srcType can be const-casted to the destType.
bool type_isa(Type type)
ParseResult parseNestedPropertyType(PropertyType &result, AsmParser &parser)
std::optional< int64_t > getBitWidth(FIRRTLBaseType type, bool ignoreFlip=false)
std::pair< uint64_t, uint64_t > getIndexAndSubfieldID(Type type, uint64_t fieldID)
uint64_t getFieldID(Type type, uint64_t index)
std::pair<::mlir::Type, uint64_t > getSubTypeByFieldID(Type, uint64_t fieldID)
std::pair< uint64_t, bool > projectToChildFieldID(Type, uint64_t fieldID, uint64_t index)
uint64_t getIndexForFieldID(Type type, uint64_t fieldID)
uint64_t getMaxFieldID(Type)
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
llvm::hash_code hash_value(const DenseSet< T > &set)
A collection of bits indicating the recursive properties of a type.
Definition FIRRTLTypes.h:75
bool containsReference
Whether the type contains a reference type.
Definition FIRRTLTypes.h:79
bool containsTypeAlias
Whether the type contains a type alias.
Definition FIRRTLTypes.h:85
bool containsConst
Whether the type contains a const type.
Definition FIRRTLTypes.h:83
bool operator==(const KeyTy &key) const
static BaseTypeAliasStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
BaseTypeAliasStorage(StringAttr name, FIRRTLBaseType innerType)
std::tuple< StringAttr, FIRRTLBaseType > KeyTy
static llvm::hash_code hashKey(const KeyTy &key)
static BundleTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
std::tuple< ArrayRef< BundleType::BundleElement >, char > KeyTy
SmallVector< BundleType::BundleElement, 4 > elements
static llvm::hash_code hashKey(const KeyTy &key)
RecursiveTypeProperties props
This holds the bits for the type's recursive properties, and can hold a pointer to a passive version ...
BundleTypeStorage(ArrayRef< BundleType::BundleElement > elements, bool isConst)
bool operator==(const KeyTy &key) const
std::tuple< FlatSymbolRefAttr, ArrayRef< ClassElement > > KeyTy
bool operator==(const KeyTy &key) const
static ClassTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
ClassTypeStorage(FlatSymbolRefAttr name, ArrayRef< ClassElement > elements, ArrayRef< uint64_t > fieldIDs, uint64_t maxFieldID)
SmallVector< FEnumType::EnumElement, 4 > elements
static llvm::hash_code hashKey(const KeyTy &key)
bool operator==(const KeyTy &key) const
static FEnumTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
FEnumTypeStorage(ArrayRef< FEnumType::EnumElement > elements, bool isConst)
std::tuple< ArrayRef< FEnumType::EnumElement >, char > KeyTy
bool operator==(const KeyTy &key) const
static FIRRTLBaseTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
bool operator==(const KeyTy &key) const
RecursiveTypeProperties props
This holds the bits for the type's recursive properties, and can hold a pointer to a passive version ...
static FVectorTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
std::tuple< FIRRTLBaseType, size_t, char > KeyTy
FVectorTypeStorage(FIRRTLBaseType elementType, size_t numElements, bool isConst)
SmallVector< OpenBundleType::BundleElement, 4 > elements
static OpenBundleTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
static llvm::hash_code hashKey(const KeyTy &key)
RecursiveTypeProperties props
This holds the bits for the type's recursive properties, and can hold a pointer to a passive version ...
OpenBundleTypeStorage(ArrayRef< OpenBundleType::BundleElement > elements, bool isConst)
std::tuple< ArrayRef< OpenBundleType::BundleElement >, char > KeyTy
std::tuple< FIRRTLType, size_t, char > KeyTy
static OpenVectorTypeStorage * construct(TypeStorageAllocator &allocator, KeyTy key)
OpenVectorTypeStorage(FIRRTLType elementType, size_t numElements, bool isConst)
WidthTypeStorage(int32_t width, bool isConst)
std::tuple< int32_t, char > KeyTy
bool operator==(const KeyTy &key) const
static WidthTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)