21#include "mlir/IR/BuiltinOps.h"
22#include "mlir/Tools/mlir-translate/Translation.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/StringSet.h"
25#include "llvm/ADT/TypeSwitch.h"
26#include "llvm/Support/Debug.h"
28#define DEBUG_TYPE "export-firrtl"
42constexpr size_t defaultTargetLineLength = 80;
46 Emitter(llvm::raw_ostream &os,
FIRVersion version,
47 size_t targetLineLength = defaultTargetLineLength)
48 : pp(os, targetLineLength), ps(pp, saver), version(version) {
49 pp.setListener(&saver);
51 LogicalResult finalize();
54 void emitCircuit(CircuitOp op);
55 void emitModule(FModuleOp op);
56 void emitModule(FExtModuleOp op);
57 void emitModule(FIntModuleOp op);
58 void emitClass(ClassOp op);
59 void emitClass(ExtClassOp op);
60 void emitPortsAndBody(ArrayRef<PortInfo> ports,
Block &body);
61 void emitPorts(ArrayRef<PortInfo> ports,
62 Block::BlockArgListType arguments = {});
63 void emitModuleParameters(Operation *op, ArrayAttr parameters);
64 void emitDeclaration(DomainOp op);
65 void emitDeclaration(LayerOp op);
66 void emitDeclaration(OptionOp op);
67 void emitDeclaration(FormalOp op);
68 void emitDeclaration(SimulationOp op);
69 void emitFormalLike(Operation *op, StringRef keyword, StringAttr symName,
70 StringAttr moduleName, DictionaryAttr params);
71 void emitEnabledLayers(ArrayRef<Attribute> layers, Operation *op);
72 void emitKnownLayers(ArrayRef<Attribute> layers, Operation *op);
73 void emitRequirements(ArrayRef<Attribute> requirements);
74 void emitParamAssign(ParamDeclAttr param, Operation *op,
75 std::optional<PPExtString> wordBeforeLHS = std::nullopt);
76 void emitParamValue(Attribute value, Operation *op);
78 void emitGenericIntrinsic(GenericIntrinsicOp op);
81 void emitStatementsInBlock(
Block &block);
82 void emitStatement(WhenOp op);
83 void emitStatement(WireOp op);
84 void emitStatement(RegOp op);
85 void emitStatement(RegResetOp op);
86 void emitStatement(NodeOp op);
87 void emitStatement(StopOp op);
88 void emitStatement(SkipOp op);
89 void emitFormatString(Operation *op, StringRef formatString, OperandRange ops,
90 llvm::SmallVectorImpl<Value> &substitutions);
92 void emitPrintfLike(T op, StringAttr fileName);
93 void emitStatement(PrintFOp op);
94 void emitStatement(FPrintFOp op);
95 void emitStatement(FFlushOp op);
96 void emitStatement(ConnectOp op);
97 void emitStatement(MatchingConnectOp op);
98 void emitStatement(PropertyAssertOp op);
99 void emitStatement(PropAssignOp op);
100 void emitStatement(InstanceOp op);
101 void emitStatement(InstanceChoiceOp op);
102 void emitStatement(AttachOp op);
103 void emitStatement(MemOp op);
104 void emitStatement(InvalidValueOp op);
105 void emitStatement(CombMemOp op);
106 void emitStatement(SeqMemOp op);
107 void emitStatement(MemoryPortOp op);
108 void emitStatement(MemoryDebugPortOp op);
109 void emitStatement(MemoryPortAccessOp op);
110 void emitStatement(DomainDefineOp op);
111 void emitStatement(RefDefineOp op);
112 void emitStatement(RefForceOp op);
113 void emitStatement(RefForceInitialOp op);
114 void emitStatement(RefReleaseOp op);
115 void emitStatement(RefReleaseInitialOp op);
116 void emitStatement(LayerBlockOp op);
117 void emitStatement(GenericIntrinsicOp op);
118 void emitStatement(DomainCreateAnonOp op);
119 void emitStatement(DomainCreateOp op);
122 void emitVerifStatement(T op, StringRef mnemonic);
123 void emitStatement(AssertOp op) { emitVerifStatement(op,
"assert"); }
124 void emitStatement(AssumeOp op) { emitVerifStatement(op,
"assume"); }
125 void emitStatement(CoverOp op) { emitVerifStatement(op,
"cover"); }
128 void emitExpression(Value value);
129 void emitExpression(ConstantOp op);
130 void emitExpression(SpecialConstantOp op);
131 void emitExpression(SubfieldOp op);
132 void emitExpression(SubindexOp op);
133 void emitExpression(SubaccessOp op);
134 void emitExpression(OpenSubfieldOp op);
135 void emitExpression(DomainSubfieldOp op);
136 void emitExpression(OpenSubindexOp op);
137 void emitExpression(ObjectAnyRefCastOp op);
138 void emitExpression(DomainAnyRefCastOp op);
139 void emitExpression(RefResolveOp op);
140 void emitExpression(RefSendOp op);
141 void emitExpression(RefSubOp op);
142 void emitExpression(RWProbeOp op);
143 void emitExpression(RefCastOp op);
144 void emitExpression(UninferredResetCastOp op);
145 void emitExpression(ConstCastOp op);
146 void emitExpression(StringConstantOp op);
147 void emitExpression(FIntegerConstantOp op);
148 void emitExpression(BoolConstantOp op);
149 void emitExpression(DoubleConstantOp op);
150 void emitExpression(ListCreateOp op);
151 void emitExpression(OptionCreateOp op);
152 void emitExpression(UnresolvedPathOp op);
153 void emitExpression(GenericIntrinsicOp op);
154 void emitExpression(CatPrimOp op);
155 void emitExpression(UnsafeDomainCastOp op);
156 void emitExpression(UnknownValueOp op);
158 void emitPrimExpr(StringRef mnemonic, Operation *op,
159 ArrayRef<uint32_t>
attrs = {});
161 void emitExpression(BitsPrimOp op) {
162 emitPrimExpr(
"bits", op, {op.getHi(), op.getLo()});
164 void emitExpression(HeadPrimOp op) {
165 emitPrimExpr(
"head", op, op.getAmount());
167 void emitExpression(TailPrimOp op) {
168 emitPrimExpr(
"tail", op, op.getAmount());
170 void emitExpression(PadPrimOp op) { emitPrimExpr(
"pad", op, op.getAmount()); }
171 void emitExpression(ShlPrimOp op) { emitPrimExpr(
"shl", op, op.getAmount()); }
172 void emitExpression(ShrPrimOp op) { emitPrimExpr(
"shr", op, op.getAmount()); }
174 void emitExpression(TimeOp op) {}
177#define HANDLE(OPTYPE, MNEMONIC) \
178 void emitExpression(OPTYPE op) { emitPrimExpr(MNEMONIC, op); }
193 HANDLE(DShlPrimOp,
"dshl");
194 HANDLE(DShlwPrimOp,
"dshlw");
195 HANDLE(DShrPrimOp,
"dshr");
197 HANDLE(AsSIntPrimOp,
"asSInt");
198 HANDLE(AsUIntPrimOp,
"asUInt");
199 HANDLE(AsAsyncResetPrimOp,
"asAsyncReset");
200 HANDLE(AsResetPrimOp,
"asReset");
201 HANDLE(AsClockPrimOp,
"asClock");
205 HANDLE(AndRPrimOp,
"andr");
207 HANDLE(XorRPrimOp,
"xorr");
208 HANDLE(StringConcatOp,
"string_concat");
211 void emitExpression(PropEqOp op) {
212 if (failed(requireVersion({6, 0, 0}, op,
"property equality")))
216 "property equality with AnyRef or Class types")))
218 emitPrimExpr(
"prop_eq", op);
221 void emitExpression(ListLengthOp op) {
224 emitPrimExpr(
"list_length", op);
227 void emitExpression(OptionGetOrElseOp op) {
228 if (failed(requireVersion(
nextFIRVersion, op,
"option get or else")))
230 emitPrimExpr(
"option_get_or_else", op);
233 void emitExpression(ListContainsOp op) {
236 emitPrimExpr(
"list_contains", op);
239 void emitExpression(BoolAndOp op) {
240 if (failed(requireVersion({6, 0, 0}, op,
"boolean and")))
242 emitPrimExpr(
"bool_and", op);
245 void emitExpression(BoolOrOp op) {
246 if (failed(requireVersion({6, 0, 0}, op,
"boolean or")))
248 emitPrimExpr(
"bool_or", op);
251 void emitExpression(BoolXorOp op) {
252 if (failed(requireVersion({6, 0, 0}, op,
"boolean xor")))
254 emitPrimExpr(
"bool_xor", op);
257 void emitExpression(IntegerAndOp op) {
260 emitPrimExpr(
"integer_and", op);
263 void emitExpression(IntegerOrOp op) {
266 emitPrimExpr(
"integer_or", op);
269 void emitExpression(IntegerNotOp op) {
272 emitPrimExpr(
"integer_not", op);
276 void emitAttribute(MemDirAttr attr);
277 void emitAttribute(RUWBehaviorAttr attr);
280 void emitType(Type type,
bool includeConst =
true);
281 void emitTypeWithColon(Type type) {
282 ps << PP::space <<
":" << PP::nbsp;
287 void emitDomains(Attribute attr, ArrayRef<PortInfo> ports);
290 void emitLocation(Location loc);
291 void emitLocation(Operation *op) { emitLocation(op->getLoc()); }
292 template <
typename... Args>
293 void emitLocationAndNewLine(Args... args) {
296 ps << PP::neverbreak;
297 emitLocation(args...);
301 void emitAssignLike(llvm::function_ref<
void()> emitLHS,
302 llvm::function_ref<
void()> emitRHS,
303 PPExtString syntax = PPExtString(
"="),
304 std::optional<PPExtString> wordBeforeLHS = std::nullopt) {
306 ps.scopedBox(PP::ibox2, [&]() {
308 ps << *wordBeforeLHS << PP::space;
312 ps << PP::space << syntax << PP::nbsp;
314 ps.scopedBox(PP::ibox0, [&]() { emitRHS(); });
319 void emitSubExprIBox2(Value v) {
320 ps.scopedBox(PP::ibox2, [&]() { emitExpression(v); });
325 template <
typename Container,
typename EachFn>
326 void interleaveComma(
const Container &c, EachFn eachFn) {
327 llvm::interleave(c, eachFn, [&]() { ps <<
"," << PP::space; });
332 void interleaveComma(ValueRange ops) {
333 return interleaveComma(ops, [&](Value v) { emitSubExprIBox2(v); });
336 void emitStatementFunctionOp(PPExtString name, Operation *op) {
339 ps.scopedBox(PP::ibox0, [&]() {
340 interleaveComma(op->getOperands());
343 emitLocationAndNewLine(op);
346 template <
typename EachFn,
typename Range>
347 void emitLiteralExpression(Type type,
const Range &r, EachFn eachFn) {
350 ps.scopedBox(PP::ibox0, [&]() {
351 interleaveComma(r, eachFn);
356 void emitLiteralExpression(Type type, ValueRange values) {
357 return emitLiteralExpression(type, values,
358 [&](Value v) { emitSubExprIBox2(v); });
362 void emitSymbol(SymbolRefAttr symbol) {
363 ps.ibox(2, IndentStyle::Block);
364 ps << symbol.getRootReference();
365 for (
auto nested : symbol.getNestedReferences()) {
368 ps << nested.getAttr();
375 InFlightDiagnostic emitError(Operation *op,
const Twine &message) {
376 encounteredError =
true;
377 return op->emitError(message);
381 InFlightDiagnostic emitOpError(Operation *op,
const Twine &message) {
382 encounteredError =
true;
383 return op->emitOpError(message);
387 LogicalResult requireVersion(FIRVersion minVersion, Operation *op,
389 if (version >= minVersion)
392 return emitOpError(op, feature +
" requires FIRRTL ") << minVersion;
397 std::optional<StringRef> lookupEmittedName(Value value) {
398 auto it = valueNames.find(value);
399 if (it != valueNames.end())
406 void emitPendingNewlineIfNeeded() {
407 if (pendingNewline) {
408 pendingNewline =
false;
412 void setPendingNewline() {
414 pendingNewline =
true;
417 void startStatement() { emitPendingNewlineIfNeeded(); }
422 TokenStringSaver saver;
435 bool pendingNewline =
false;
438 bool encounteredError =
false;
443 DenseMap<Value, StringRef> valueNames;
444 StringSet<> valueNamesStorage;
448 StringAttr legalize(StringAttr attr) {
449 StringRef str = attr.getValue();
450 if (str.empty() || !
isdigit(str.front()))
452 return StringAttr::get(attr.getContext(),
"`" + Twine(attr) +
"`");
455 void addValueName(Value value, StringAttr attr) {
456 valueNames.insert({value, attr.getValue()});
458 void addValueName(Value value, StringRef str) {
459 auto it = valueNamesStorage.insert(str);
460 valueNames.insert({value, it.first->getKey()});
462 void addForceable(Forceable op, StringAttr attr) {
463 addValueName(op.getDataRaw() , attr);
464 if (op.isForceable()) {
465 SmallString<32> rwName;
466 (Twine(
"rwprobe(") + attr.strref() +
")").
toVector(rwName);
467 addValueName(op.getDataRef(), rwName);
472 CircuitNamespace circuitNamespace;
476 SymbolTable symbolTable;
477 hw::InnerSymbolTableCollection istc;
478 hw::InnerRefNamespace irn{symbolTable, istc};
479 SymInfos(Operation *op) : symbolTable(op), istc(op) {}
481 std::optional<std::reference_wrapper<SymInfos>> symInfos;
488LogicalResult Emitter::finalize() {
return failure(encounteredError); }
491void Emitter::emitCircuit(CircuitOp op) {
492 circuitNamespace.add(op);
493 SymInfos circuitSymInfos(op);
494 symInfos = circuitSymInfos;
496 ps <<
"FIRRTL version ";
503 ps <<
"circuit " << PPExtString(legalize(op.getNameAttr())) <<
" :";
506 for (
auto &bodyOp : *op.getBodyBlock()) {
507 if (encounteredError)
509 TypeSwitch<Operation *>(&bodyOp)
510 .Case<FModuleOp, FExtModuleOp, FIntModuleOp>([&](
auto op) {
514 .Case<ClassOp, ExtClassOp>([&](
auto op) {
518 .Case<DomainOp, LayerOp, OptionOp, FormalOp, SimulationOp>(
519 [&](
auto op) { emitDeclaration(op); })
520 .Default([&](
auto op) {
521 emitOpError(op,
"not supported for emission inside circuit");
525 circuitNamespace.clear();
526 symInfos = std::nullopt;
529void Emitter::emitEnabledLayers(ArrayRef<Attribute> layers, Operation *op) {
532 if (failed(requireVersion(FIRVersion(4, 0, 0), op,
"enabled layers")))
534 for (
auto layer : layers) {
536 ps.
cbox(2, IndentStyle::Block);
537 ps <<
"enablelayer" << PP::space;
538 emitSymbol(cast<SymbolRefAttr>(layer));
543void Emitter::emitKnownLayers(ArrayRef<Attribute> layers, Operation *op) {
546 if (failed(requireVersion({6, 0, 0}, op,
"known layers")))
548 for (
auto layer : layers) {
550 ps.
cbox(2, IndentStyle::Block);
551 ps <<
"knownlayer" << PP::space;
552 emitSymbol(cast<SymbolRefAttr>(layer));
557void Emitter::emitRequirements(ArrayRef<Attribute> requirements) {
558 if (requirements.empty())
561 ps.
cbox(2, IndentStyle::Block);
562 ps <<
"requires" << PP::space;
563 llvm::interleaveComma(requirements, ps, [&](Attribute req) {
569void Emitter::emitParamAssign(ParamDeclAttr param, Operation *op,
570 std::optional<PPExtString> wordBeforeLHS) {
572 ps << *wordBeforeLHS << PP::nbsp;
574 ps << PPExtString(param.getName().strref()) << PP::nbsp <<
"=" << PP::nbsp;
575 emitParamValue(param.getValue(), op);
578void Emitter::emitParamValue(Attribute value, Operation *op) {
579 TypeSwitch<Attribute>(value)
580 .Case<IntegerAttr>([&](
auto attr) { ps.
addAsString(attr.getValue()); })
581 .Case<FloatAttr>([&](
auto attr) {
583 attr.getValue().toString(str);
588 .Case<ArrayAttr>([&](
auto attr) {
591 interleaveComma(attr.getValue(),
592 [&](
auto element) { emitParamValue(element, op); });
596 .Case<DictionaryAttr>([&](
auto attr) {
599 interleaveComma(attr.getValue(), [&](
auto field) {
600 ps << PPExtString(field.getName()) << PP::nbsp <<
"=" << PP::nbsp;
601 emitParamValue(field.getValue(), op);
606 .Default([&](
auto attr) {
607 emitOpError(op,
"with unsupported parameter attribute: ") << attr;
608 ps <<
"<unsupported-attr ";
614void Emitter::emitGenericIntrinsic(GenericIntrinsicOp op) {
618 ps << op.getIntrinsic();
620 auto params = op.getParameters();
621 if (!params.empty()) {
625 params.getAsRange<ParamDeclAttr>(),
626 [&](ParamDeclAttr param) { emitParamAssign(param, op); });
631 if (op.getNumResults() != 0)
632 emitTypeWithColon(op.getResult().getType());
634 if (op.getNumOperands() != 0) {
635 ps <<
"," << PP::space;
636 ps.
scopedBox(PP::ibox0, [&]() { interleaveComma(op->getOperands()); });
643void Emitter::emitModule(FModuleOp op) {
645 ps.
cbox(4, IndentStyle::Block);
646 if (op.isPublic() && FIRVersion(3, 3, 0) <= version)
647 ps <<
"public" << PP::nbsp;
648 ps <<
"module " << PPExtString(legalize(op.getNameAttr()));
649 emitEnabledLayers(op.getLayers(), op);
650 ps << PP::nbsp <<
":" << PP::end;
653 emitPortsAndBody(op.getPorts(), *op.getBodyBlock());
657void Emitter::emitModule(FExtModuleOp op) {
659 ps.
cbox(4, IndentStyle::Block);
660 ps <<
"extmodule " << PPExtString(legalize(op.getNameAttr()));
661 emitKnownLayers(op.getKnownLayers(), op);
662 emitEnabledLayers(op.getLayers(), op);
663 if (
auto reqs = op.getExternalRequirements())
664 emitRequirements(reqs.getValue());
665 ps << PP::nbsp <<
":" << PP::end;
672 auto ports = op.getPorts();
676 if (op.getDefname() && !op.getDefname()->empty()) {
678 ps <<
"defname = " << PPExtString(*op.getDefname());
683 emitModuleParameters(op, op.getParameters());
688void Emitter::emitModule(FIntModuleOp op) {
689 if (FIRVersion(4, 0, 0) <= version) {
690 emitOpError(op,
"intrinsic modules were removed in FIRRTL 4.0.0");
694 ps.
cbox(4, IndentStyle::Block);
695 ps <<
"intmodule " << PPExtString(legalize(op.getNameAttr()));
696 emitEnabledLayers(op.getLayers(), op);
697 ps << PP::nbsp <<
":" << PP::end;
704 auto ports = op.getPorts();
708 ps <<
"intrinsic = " << PPExtString(op.getIntrinsic());
712 emitModuleParameters(op, op.getParameters());
717void Emitter::emitClass(ClassOp op) {
718 if (failed(requireVersion({6, 0, 0}, op,
"classes")))
721 ps <<
"class " << PPExtString(legalize(op.getNameAttr())) <<
" :";
723 emitPortsAndBody(op.getPorts(), *op.getBodyBlock());
727void Emitter::emitClass(ExtClassOp op) {
728 if (failed(requireVersion({6, 0, 0}, op,
"external classes")))
731 ps <<
"extclass " << PPExtString(legalize(op.getNameAttr())) <<
" :";
735 emitPorts(op.getPorts());
740void Emitter::emitPortsAndBody(ArrayRef<PortInfo> ports,
Block &body) {
743 emitPorts(ports, body.getArguments());
744 if (!ports.empty() && !body.empty())
746 emitStatementsInBlock(body);
749 valueNamesStorage.clear();
755void Emitter::emitPorts(ArrayRef<PortInfo> ports,
756 Block::BlockArgListType arguments) {
758 for (
unsigned i = 0, e = ports.size(); i < e; ++i) {
760 const auto &port = ports[i];
761 ps << (port.direction == Direction::In ?
"input " :
"output ");
762 auto legalName = legalize(port.name);
763 if (!arguments.empty())
764 addValueName(arguments[i], legalName);
765 ps << PPExtString(legalName) <<
" : ";
767 emitDomains(port.domains, ports);
768 emitLocation(ports[i].loc);
773void Emitter::emitModuleParameters(Operation *op, ArrayAttr parameters) {
774 for (
auto param : parameters.getAsRange<ParamDeclAttr>()) {
776 emitParamAssign(param, op, PPExtString(
"parameter"));
781void Emitter::emitDeclaration(DomainOp op) {
785 ps <<
"domain " << PPExtString(op.getSymName()) <<
" :";
786 emitLocationAndNewLine(op);
788 for (
auto attr : op.getFields()) {
789 auto fieldAttr = cast<DomainFieldAttr>(attr);
790 ps << PP::newline << PPExtString(fieldAttr.getName()) <<
" : ";
791 emitType(fieldAttr.getType());
797void Emitter::emitDeclaration(LayerOp op) {
798 if (failed(requireVersion(FIRVersion(3, 3, 0), op,
"layers")))
800 if (op.getConvention() == LayerConvention::Inline &&
801 failed(requireVersion(FIRVersion(4, 1, 0), op,
"inline layers")))
804 ps <<
"layer " << PPExtString(op.getSymName()) <<
", "
805 << PPExtString(stringifyLayerConvention(op.getConvention()));
807 if (
auto outputFile = op->getAttrOfType<hw::OutputFileAttr>(
"output_file")) {
813 emitLocationAndNewLine(op);
815 for (
auto &bodyOp : op.getBody().getOps()) {
816 TypeSwitch<Operation *>(&bodyOp)
817 .Case<LayerOp>([&](
auto op) { emitDeclaration(op); })
818 .Default([&](
auto op) {
820 "not supported for emission inside layer definition");
827void Emitter::emitDeclaration(OptionOp op) {
831 ps <<
"option " << PPExtString(legalize(op.getSymNameAttr())) <<
" :";
834 for (
auto caseOp : op.getBody().getOps<OptionCaseOp>()) {
836 ps << PPExtString(legalize(caseOp.getSymNameAttr()));
837 emitLocation(caseOp);
840 ps << PP::newline << PP::newline;
844void Emitter::emitDeclaration(FormalOp op) {
845 if (failed(requireVersion(FIRVersion(4, 0, 0), op,
"formal tests")))
847 emitFormalLike(op,
"formal", op.getSymNameAttr(),
848 op.getModuleNameAttr().getAttr(), op.getParameters());
852void Emitter::emitDeclaration(SimulationOp op) {
853 if (failed(requireVersion(
nextFIRVersion, op,
"simulation tests")))
855 emitFormalLike(op,
"simulation", op.getSymNameAttr(),
856 op.getModuleNameAttr().getAttr(), op.getParameters());
860void Emitter::emitFormalLike(Operation *op, StringRef keyword,
861 StringAttr symName, StringAttr moduleName,
862 DictionaryAttr params) {
864 ps.
cbox(4, IndentStyle::Block);
865 ps << keyword <<
" " << PPExtString(legalize(symName));
866 ps <<
" of " << PPExtString(legalize(moduleName));
867 ps << PP::nbsp <<
":" << PP::end;
872 for (
auto param : params) {
874 ps << PPExtString(param.getName()) << PP::nbsp <<
"=" << PP::nbsp;
875 emitParamValue(param.getValue(), op);
889 return (
isExpression(op) && !isa<InvalidValueOp>(op)) ||
890 (isa<GenericIntrinsicOp>(op) && op->hasOneUse() &&
894void Emitter::emitStatementsInBlock(
Block &block) {
895 for (
auto &bodyOp : block) {
896 if (encounteredError)
900 TypeSwitch<Operation *>(&bodyOp)
901 .Case<WhenOp, WireOp, RegOp, RegResetOp, NodeOp, StopOp, SkipOp,
902 PrintFOp, FPrintFOp, FFlushOp, AssertOp, AssumeOp, CoverOp,
903 ConnectOp, MatchingConnectOp, PropertyAssertOp, PropAssignOp,
904 InstanceOp, InstanceChoiceOp, AttachOp, MemOp, InvalidValueOp,
905 SeqMemOp, CombMemOp, MemoryPortOp, MemoryDebugPortOp,
906 MemoryPortAccessOp, DomainDefineOp, RefDefineOp, RefForceOp,
907 RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp,
908 LayerBlockOp, GenericIntrinsicOp, DomainCreateAnonOp,
909 DomainCreateOp>([&](
auto op) { emitStatement(op); })
910 .Default([&](
auto op) {
912 ps <<
"// operation " << PPExtString(op->getName().getStringRef());
914 emitOpError(op,
"not supported as statement");
919void Emitter::emitStatement(WhenOp op) {
922 emitExpression(op.getCondition());
924 emitLocationAndNewLine(op);
925 ps.
scopedBox(PP::bbox2, [&]() { emitStatementsInBlock(op.getThenBlock()); });
927 if (!op.hasElseRegion())
934 auto &elseBlock = op.getElseBlock();
935 if (!elseBlock.empty() && &elseBlock.front() == &elseBlock.back()) {
936 if (
auto whenOp = dyn_cast<WhenOp>(&elseBlock.front())) {
937 emitStatement(whenOp);
944 ps.
scopedBox(PP::bbox2, [&]() { emitStatementsInBlock(elseBlock); });
947void Emitter::emitStatement(WireOp op) {
948 auto legalName = legalize(op.getNameAttr());
949 addForceable(op, legalName);
952 ps <<
"wire " << PPExtString(legalName);
953 emitTypeWithColon(op.getResult().getType());
956 if (!op.getDomains().empty()) {
957 ps << PP::space <<
"domains" << PP::space <<
"[";
959 llvm::interleaveComma(op.getDomains(), ps, [&](Value domain) {
960 auto name = lookupEmittedName(domain);
961 assert(name &&
"domain value must have a name");
962 ps << PPExtString(*name);
968 emitLocationAndNewLine(op);
971void Emitter::emitStatement(RegOp op) {
972 auto legalName = legalize(op.getNameAttr());
973 addForceable(op, legalName);
976 ps <<
"reg " << PPExtString(legalName);
977 emitTypeWithColon(op.getResult().getType());
978 ps <<
"," << PP::space;
979 emitExpression(op.getClockVal());
981 emitLocationAndNewLine(op);
984void Emitter::emitStatement(RegResetOp op) {
985 auto legalName = legalize(op.getNameAttr());
986 addForceable(op, legalName);
988 if (FIRVersion(3, 0, 0) <= version) {
990 ps <<
"regreset " << legalName;
991 emitTypeWithColon(op.getResult().getType());
992 ps <<
"," << PP::space;
993 emitExpression(op.getClockVal());
994 ps <<
"," << PP::space;
995 emitExpression(op.getResetSignal());
996 ps <<
"," << PP::space;
997 emitExpression(op.getResetValue());
1001 ps <<
"reg " << legalName;
1002 emitTypeWithColon(op.getResult().getType());
1003 ps <<
"," << PP::space;
1004 emitExpression(op.getClockVal());
1005 ps << PP::space <<
"with :";
1007 ps << PP::neverbreak;
1010 ps <<
"reset => (" << PP::ibox0;
1011 emitExpression(op.getResetSignal());
1012 ps <<
"," << PP::space;
1013 emitExpression(op.getResetValue());
1014 ps <<
")" << PP::end;
1017 emitLocationAndNewLine(op);
1020void Emitter::emitStatement(NodeOp op) {
1021 auto legalName = legalize(op.getNameAttr());
1022 addForceable(op, legalName);
1024 emitAssignLike([&]() { ps <<
"node " << PPExtString(legalName); },
1025 [&]() { emitExpression(op.getInput()); });
1026 emitLocationAndNewLine(op);
1029void Emitter::emitStatement(StopOp op) {
1032 ps <<
"stop(" << PP::ibox0;
1033 emitExpression(op.getClock());
1034 ps <<
"," << PP::space;
1035 emitExpression(op.getCond());
1036 ps <<
"," << PP::space;
1038 ps <<
")" << PP::end;
1039 if (!op.getName().empty()) {
1040 ps << PP::space <<
": " << PPExtString(legalize(op.getNameAttr()));
1043 emitLocationAndNewLine(op);
1046void Emitter::emitStatement(SkipOp op) {
1049 emitLocationAndNewLine(op);
1052void Emitter::emitFormatString(Operation *op, StringRef origFormatString,
1053 OperandRange substitutionOperands,
1054 llvm::SmallVectorImpl<Value> &substitutions) {
1063 SmallString<64> formatString;
1064 for (
size_t i = 0, e = origFormatString.size(), opIdx = 0; i != e; ++i) {
1065 auto c = origFormatString[i];
1068 formatString.push_back(c);
1071 SmallString<6> width;
1072 c = origFormatString[++i];
1075 c = origFormatString[++i];
1084 formatString.append(width);
1087 substitutions.push_back(substitutionOperands[opIdx++]);
1090 formatString.push_back(c);
1095 if (origFormatString.slice(i, i + 4) ==
"{{}}") {
1096 formatString.append(
"{{");
1097 TypeSwitch<Operation *>(substitutionOperands[opIdx++].getDefiningOp())
1099 [&](
auto time) { formatString.append(
"SimulationTime"); })
1100 .Case<HierarchicalModuleNameOp>([&](
auto time) {
1101 formatString.append(
"HierarchicalModuleName");
1103 .Default([&](
auto) {
1104 emitError(op,
"unsupported fstring substitution type");
1106 formatString.append(
"}}");
1111 formatString.push_back(c);
1117void Emitter::emitStatement(PrintFOp op) {
1120 ps <<
"printf(" << PP::ibox0;
1121 emitExpression(op.getClock());
1122 ps <<
"," << PP::space;
1123 emitExpression(op.getCond());
1124 ps <<
"," << PP::space;
1126 SmallVector<Value, 4> substitutions;
1127 emitFormatString(op, op.getFormatString(), op.getSubstitutions(),
1129 for (
auto operand : substitutions) {
1130 ps <<
"," << PP::space;
1131 emitExpression(operand);
1133 ps <<
")" << PP::end;
1134 if (!op.getName().empty()) {
1135 ps << PP::space <<
": " << PPExtString(legalize(op.getNameAttr()));
1138 emitLocationAndNewLine(op);
1141void Emitter::emitStatement(FPrintFOp op) {
1142 if (failed(requireVersion({6, 0, 0}, op,
"fprintf")))
1146 ps <<
"fprintf(" << PP::ibox0;
1147 emitExpression(op.getClock());
1148 ps <<
"," << PP::space;
1149 emitExpression(op.getCond());
1150 ps <<
"," << PP::space;
1152 SmallVector<Value, 4> outputFileSubstitutions;
1153 emitFormatString(op, op.getOutputFile(), op.getOutputFileSubstitutions(),
1154 outputFileSubstitutions);
1155 if (!outputFileSubstitutions.empty()) {
1156 ps <<
"," << PP::space;
1157 interleaveComma(outputFileSubstitutions);
1160 ps <<
"," << PP::space;
1161 SmallVector<Value, 4> substitutions;
1162 emitFormatString(op, op.getFormatString(), op.getSubstitutions(),
1164 if (!substitutions.empty()) {
1165 ps <<
"," << PP::space;
1166 interleaveComma(substitutions);
1169 ps <<
")" << PP::end;
1170 if (!op.getName().empty()) {
1171 ps << PP::space <<
": " << PPExtString(legalize(op.getNameAttr()));
1174 emitLocationAndNewLine(op);
1177void Emitter::emitStatement(FFlushOp op) {
1178 if (failed(requireVersion({6, 0, 0}, op,
"fflush")))
1182 ps <<
"fflush(" << PP::ibox0;
1183 emitExpression(op.getClock());
1184 ps <<
"," << PP::space;
1185 emitExpression(op.getCond());
1186 if (op.getOutputFileAttr()) {
1187 ps <<
"," << PP::space;
1188 SmallVector<Value, 4> substitutions;
1189 emitFormatString(op, op.getOutputFileAttr(),
1190 op.getOutputFileSubstitutions(), substitutions);
1191 if (!substitutions.empty()) {
1192 ps <<
"," << PP::space;
1193 interleaveComma(substitutions);
1196 ps <<
")" << PP::end;
1198 emitLocationAndNewLine(op);
1202void Emitter::emitVerifStatement(T op, StringRef mnemonic) {
1205 ps << mnemonic <<
"(" << PP::ibox0;
1206 emitExpression(op.getClock());
1207 ps <<
"," << PP::space;
1208 emitExpression(op.getPredicate());
1209 ps <<
"," << PP::space;
1210 emitExpression(op.getEnable());
1211 ps <<
"," << PP::space;
1213 ps <<
")" << PP::end;
1214 if (!op.getName().empty()) {
1215 ps << PP::space <<
": " << PPExtString(legalize(op.getNameAttr()));
1218 emitLocationAndNewLine(op);
1221void Emitter::emitStatement(ConnectOp op) {
1223 if (FIRVersion(3, 0, 0) <= version) {
1225 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1226 ps <<
"invalidate" << PP::space;
1227 emitExpression(op.getDest());
1229 ps <<
"connect" << PP::space;
1230 emitExpression(op.getDest());
1231 ps <<
"," << PP::space;
1232 emitExpression(op.getSrc());
1236 auto emitLHS = [&]() { emitExpression(op.getDest()); };
1237 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1239 emitLHS, [&]() { ps <<
"invalid"; }, PPExtString(
"is"));
1242 emitLHS, [&]() { emitExpression(op.getSrc()); }, PPExtString(
"<="));
1245 emitLocationAndNewLine(op);
1248void Emitter::emitStatement(MatchingConnectOp op) {
1250 if (FIRVersion(3, 0, 0) <= version) {
1252 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1253 ps <<
"invalidate" << PP::space;
1254 emitExpression(op.getDest());
1256 ps <<
"connect" << PP::space;
1257 emitExpression(op.getDest());
1258 ps <<
"," << PP::space;
1259 emitExpression(op.getSrc());
1263 auto emitLHS = [&]() { emitExpression(op.getDest()); };
1264 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1266 emitLHS, [&]() { ps <<
"invalid"; }, PPExtString(
"is"));
1269 emitLHS, [&]() { emitExpression(op.getSrc()); }, PPExtString(
"<="));
1272 emitLocationAndNewLine(op);
1275void Emitter::emitStatement(PropertyAssertOp op) {
1276 if (failed(requireVersion(FIRVersion(6, 0, 0), op,
"property assert")))
1280 ps <<
"propassert" << PP::space;
1281 emitExpression(op.getCondition());
1282 ps <<
"," << PP::space;
1286 if (version < FIRVersion(7, 0, 0)) {
1287 auto expr = dyn_cast<StringConstantOp>(op.getMessage().getDefiningOp());
1290 emitOpError(op,
"unable to emit non-literal string expressions "
1291 "when targeting FIRRTL version <= 7.0.0");
1292 diag.attachNote(op.getMessage().getLoc())
1293 <<
"non-literal expression is here";
1296 emitExpression(op.getMessage());
1299 emitLocationAndNewLine(op);
1302void Emitter::emitStatement(PropAssignOp op) {
1303 if (failed(requireVersion(FIRVersion(3, 1, 0), op,
"properties")))
1307 ps <<
"propassign" << PP::space;
1308 interleaveComma(op.getOperands());
1310 emitLocationAndNewLine(op);
1313void Emitter::emitStatement(InstanceOp op) {
1315 auto legalName = legalize(op.getNameAttr());
1316 ps <<
"inst " << PPExtString(legalName) <<
" of "
1317 << PPExtString(legalize(op.getModuleNameAttr().getAttr()));
1318 emitLocationAndNewLine(op);
1322 SmallString<16> portName(legalName);
1323 portName.push_back(
'.');
1324 unsigned baseLen = portName.size();
1325 for (
unsigned i = 0, e = op.getNumResults(); i < e; ++i) {
1326 portName.append(legalize(op.getPortNameAttr(i)));
1327 addValueName(op.getResult(i), portName);
1328 portName.resize(baseLen);
1332void Emitter::emitStatement(InstanceChoiceOp op) {
1334 "option groups/instance choices")))
1337 auto legalName = legalize(op.getNameAttr());
1338 ps <<
"instchoice " << PPExtString(legalName) <<
" of "
1339 << PPExtString(legalize(op.getDefaultTargetAttr().getAttr())) <<
", "
1340 << PPExtString(legalize(op.getOptionNameAttr())) <<
" :";
1343 for (
const auto &[optSym, targetSym] : op.getTargetChoices()) {
1345 ps << PPExtString(legalize(optSym.getLeafReference()));
1347 ps << PPExtString(legalize(targetSym.getAttr()));
1350 setPendingNewline();
1352 SmallString<16> portName(legalName);
1353 portName.push_back(
'.');
1354 unsigned baseLen = portName.size();
1355 for (
unsigned i = 0, e = op.getNumResults(); i < e; ++i) {
1356 portName.append(legalize(op.getPortNameAttr(i)));
1357 addValueName(op.getResult(i), portName);
1358 portName.resize(baseLen);
1362void Emitter::emitStatement(AttachOp op) {
1363 emitStatementFunctionOp(PPExtString(
"attach"), op);
1366void Emitter::emitStatement(MemOp op) {
1367 auto legalName = legalize(op.getNameAttr());
1368 SmallString<16> portName(legalName);
1369 portName.push_back(
'.');
1370 auto portNameBaseLen = portName.size();
1371 for (
auto result : llvm::zip(op.getResults(), op.getPortNames())) {
1372 portName.resize(portNameBaseLen);
1373 portName.append(legalize(cast<StringAttr>(std::get<1>(result))));
1374 addValueName(std::get<0>(result), portName);
1378 ps <<
"mem " << PPExtString(legalName) <<
" :";
1379 emitLocationAndNewLine(op);
1382 ps <<
"data-type => ";
1383 emitType(op.getDataType());
1388 ps <<
"read-latency => ";
1391 ps <<
"write-latency => ";
1395 SmallString<16> reader, writer, readwriter;
1396 for (std::pair<StringAttr, MemOp::PortKind> port : op.getPorts()) {
1397 auto add = [&](SmallString<16> &to, StringAttr name) {
1400 to.append(name.getValue());
1402 switch (port.second) {
1403 case MemOp::PortKind::Read:
1404 add(reader, legalize(port.first));
1406 case MemOp::PortKind::Write:
1407 add(writer, legalize(port.first));
1409 case MemOp::PortKind::ReadWrite:
1410 add(readwriter, legalize(port.first));
1412 case MemOp::PortKind::Debug:
1413 emitOpError(op,
"has unsupported 'debug' port");
1417 if (!reader.empty())
1418 ps <<
"reader => " << reader << PP::newline;
1419 if (!writer.empty())
1420 ps <<
"writer => " << writer << PP::newline;
1421 if (!readwriter.empty())
1422 ps <<
"readwriter => " << readwriter << PP::newline;
1424 ps <<
"read-under-write => ";
1425 emitAttribute(op.getRuwAttr());
1426 setPendingNewline();
1430void Emitter::emitStatement(SeqMemOp op) {
1433 ps <<
"smem " << PPExtString(legalize(op.getNameAttr()));
1434 emitTypeWithColon(op.getType());
1435 ps <<
"," << PP::space;
1436 emitAttribute(op.getRuwAttr());
1438 emitLocationAndNewLine(op);
1441void Emitter::emitStatement(CombMemOp op) {
1444 ps <<
"cmem " << PPExtString(legalize(op.getNameAttr()));
1445 emitTypeWithColon(op.getType());
1447 emitLocationAndNewLine(op);
1450void Emitter::emitStatement(MemoryPortOp op) {
1452 addValueName(op.getData(), legalize(op.getNameAttr()));
1455void Emitter::emitStatement(MemoryDebugPortOp op) {
1457 addValueName(op.getData(), legalize(op.getNameAttr()));
1460void Emitter::emitStatement(MemoryPortAccessOp op) {
1464 auto port = cast<MemoryPortOp>(op.getPort().getDefiningOp());
1465 emitAttribute(port.getDirection());
1467 ps <<
" mport " << PPExtString(legalize(port.getNameAttr())) <<
" = ";
1470 auto *mem = port.getMemory().getDefiningOp();
1471 if (
auto seqMem = dyn_cast<SeqMemOp>(mem))
1472 ps << legalize(seqMem.getNameAttr());
1474 ps << legalize(cast<CombMemOp>(mem).getNameAttr());
1478 emitExpression(op.getIndex());
1482 emitExpression(op.getClock());
1484 emitLocationAndNewLine(op);
1487void Emitter::emitStatement(DomainDefineOp op) {
1491 if (isa_and_nonnull<DomainCreateAnonOp>(op.getSrc().getDefiningOp()))
1495 emitAssignLike([&]() { emitExpression(op.getDest()); },
1496 [&]() { emitExpression(op.getSrc()); }, PPExtString(
"="),
1497 PPExtString(
"domain_define"));
1498 emitLocationAndNewLine(op);
1501void Emitter::emitStatement(RefDefineOp op) {
1503 emitAssignLike([&]() { emitExpression(op.getDest()); },
1504 [&]() { emitExpression(op.getSrc()); }, PPExtString(
"="),
1505 PPExtString(
"define"));
1506 emitLocationAndNewLine(op);
1509void Emitter::emitStatement(RefForceOp op) {
1510 emitStatementFunctionOp(PPExtString(
"force"), op);
1513void Emitter::emitStatement(RefForceInitialOp op) {
1515 auto constantPredicate =
1516 dyn_cast_or_null<ConstantOp>(op.getPredicate().getDefiningOp());
1517 bool hasEnable = !constantPredicate || constantPredicate.getValue() == 0;
1520 emitExpression(op.getPredicate());
1521 ps <<
":" << PP::bbox2 << PP::neverbreak << PP::newline;
1523 ps <<
"force_initial(";
1525 interleaveComma({op.getDest(), op.getSrc()});
1530 emitLocationAndNewLine(op);
1533void Emitter::emitStatement(RefReleaseOp op) {
1534 emitStatementFunctionOp(PPExtString(
"release"), op);
1537void Emitter::emitStatement(RefReleaseInitialOp op) {
1539 auto constantPredicate =
1540 dyn_cast_or_null<ConstantOp>(op.getPredicate().getDefiningOp());
1541 bool hasEnable = !constantPredicate || constantPredicate.getValue() == 0;
1544 emitExpression(op.getPredicate());
1545 ps <<
":" << PP::bbox2 << PP::neverbreak << PP::newline;
1547 ps <<
"release_initial(";
1548 emitExpression(op.getDest());
1552 emitLocationAndNewLine(op);
1555void Emitter::emitStatement(LayerBlockOp op) {
1556 if (failed(requireVersion(FIRVersion(3, 3, 0), op,
"layers")))
1559 ps <<
"layerblock " << op.getLayerName().getLeafReference() <<
" :";
1560 emitLocationAndNewLine(op);
1561 auto *body = op.getBody();
1562 ps.
scopedBox(PP::bbox2, [&]() { emitStatementsInBlock(*body); });
1565void Emitter::emitStatement(InvalidValueOp op) {
1568 if (llvm::all_of(op->getUses(), [&](OpOperand &use) {
1569 return use.getOperandNumber() == 1 &&
1570 isa<ConnectOp, MatchingConnectOp>(use.getOwner());
1576 auto name = circuitNamespace.newName(
"_invalid");
1577 addValueName(op, name);
1578 ps <<
"wire " << PPExtString(name) <<
" : ";
1579 emitType(op.getType());
1580 emitLocationAndNewLine(op);
1582 if (FIRVersion(3, 0, 0) <= version)
1583 ps <<
"invalidate " << PPExtString(name);
1585 ps << PPExtString(name) <<
" is invalid";
1586 emitLocationAndNewLine(op);
1589void Emitter::emitStatement(GenericIntrinsicOp op) {
1590 if (failed(requireVersion(FIRVersion(4, 0, 0), op,
"generic intrinsics")))
1594 emitGenericIntrinsic(op);
1597 auto name = circuitNamespace.newName(
"_gen_int");
1598 addValueName(op.getResult(), name);
1599 emitAssignLike([&]() { ps <<
"node " << PPExtString(name); },
1600 [&]() { emitGenericIntrinsic(op); });
1602 emitLocationAndNewLine(op);
1605void Emitter::emitStatement(DomainCreateAnonOp op) {
1609void Emitter::emitStatement(DomainCreateOp op) {
1613 auto name = legalize(op.getNameAttr());
1614 addValueName(op.getResult(), name);
1616 ps <<
"domain " << PPExtString(name) <<
" of "
1617 << PPExtString(op.getDomainAttr().getValue());
1619 auto fieldValues = op.getFieldValues();
1620 if (fieldValues.empty())
1623 ps <<
"(" << PP::ibox0;
1624 interleaveComma(fieldValues, [&](
auto value) { emitExpression(value); });
1625 ps <<
")" << PP::end;
1628 emitLocationAndNewLine(op);
1631void Emitter::emitExpression(Value value) {
1634 if (
auto name = lookupEmittedName(value)) {
1640 auto *op = value.getDefiningOp();
1641 assert(op &&
"value must either be a block arg or the result of an op");
1642 TypeSwitch<Operation *>(op)
1645 ConstantOp, SpecialConstantOp, SubfieldOp, SubindexOp, SubaccessOp,
1646 OpenSubfieldOp, OpenSubindexOp, DomainSubfieldOp,
1648 AddPrimOp, SubPrimOp, MulPrimOp, DivPrimOp, RemPrimOp, AndPrimOp,
1649 OrPrimOp, XorPrimOp, LEQPrimOp, LTPrimOp, GEQPrimOp, GTPrimOp,
1650 EQPrimOp, NEQPrimOp, DShlPrimOp, DShlwPrimOp, DShrPrimOp,
1652 AsSIntPrimOp, AsUIntPrimOp, AsAsyncResetPrimOp, AsResetPrimOp,
1653 AsClockPrimOp, CvtPrimOp, NegPrimOp, NotPrimOp, AndRPrimOp, OrRPrimOp,
1656 BitsPrimOp, HeadPrimOp, TailPrimOp, PadPrimOp, MuxPrimOp, ShlPrimOp,
1657 ShrPrimOp, UninferredResetCastOp, ConstCastOp, StringConstantOp,
1658 FIntegerConstantOp, BoolConstantOp, DoubleConstantOp, ListCreateOp,
1659 UnresolvedPathOp, GenericIntrinsicOp, CatPrimOp, UnsafeDomainCastOp,
1660 ObjectAnyRefCastOp, DomainAnyRefCastOp, UnknownValueOp, IntegerAndOp,
1661 IntegerOrOp, IntegerNotOp, StringConcatOp, PropEqOp, ListLengthOp,
1662 ListContainsOp, OptionCreateOp, OptionGetOrElseOp, BoolAndOp,
1663 BoolOrOp, BoolXorOp,
1665 RefSendOp, RefResolveOp, RefSubOp, RWProbeOp, RefCastOp,
1667 TimeOp>([&](
auto op) {
1668 ps.
scopedBox(PP::ibox0, [&]() { emitExpression(op); });
1670 .Default([&](
auto op) {
1671 emitOpError(op,
"not supported as expression");
1672 ps <<
"<unsupported-expr-" << PPExtString(op->getName().stripDialect())
1677void Emitter::emitExpression(ConstantOp op) {
1679 emitType(op.getType(),
false);
1686void Emitter::emitExpression(SpecialConstantOp op) {
1687 auto emitInner = [&]() {
1694 .Case<ClockType>([&](
auto type) {
1699 .Case<ResetType>([&](
auto type) { emitInner(); })
1700 .Case<AsyncResetType>([&](
auto type) {
1701 ps <<
"asAsyncReset(";
1708void Emitter::emitExpression(SubfieldOp op) {
1709 BundleType type = op.getInput().getType();
1710 emitExpression(op.getInput());
1711 ps <<
"." << legalize(type.getElementNameAttr(op.getFieldIndex()));
1715void Emitter::emitExpression(SubindexOp op) {
1716 emitExpression(op.getInput());
1723void Emitter::emitExpression(SubaccessOp op) {
1724 emitExpression(op.getInput());
1726 emitExpression(op.getIndex());
1730void Emitter::emitExpression(OpenSubfieldOp op) {
1731 auto type = op.getInput().getType();
1732 emitExpression(op.getInput());
1733 ps <<
"." << legalize(type.getElementNameAttr(op.getFieldIndex()));
1737void Emitter::emitExpression(DomainSubfieldOp op) {
1738 emitExpression(op.getInput());
1739 ps <<
"." << legalize(op.getFieldName());
1742void Emitter::emitExpression(OpenSubindexOp op) {
1743 emitExpression(op.getInput());
1749void Emitter::emitExpression(ObjectAnyRefCastOp op) {
1750 emitExpression(op.getInput());
1753void Emitter::emitExpression(DomainAnyRefCastOp op) {
1754 emitExpression(op.getInput());
1757void Emitter::emitExpression(RefSendOp op) {
1759 emitExpression(op.getBase());
1763void Emitter::emitExpression(RefResolveOp op) {
1765 emitExpression(op.getRef());
1769void Emitter::emitExpression(RefSubOp op) {
1770 emitExpression(op.getInput());
1771 FIRRTLTypeSwitch<FIRRTLBaseType, void>(op.getInput().getType().getType())
1772 .Case<FVectorType>([&](
auto type) {
1778 [&](
auto type) { ps <<
"." << type.getElementName(op.getIndex()); });
1781void Emitter::emitExpression(RWProbeOp op) {
1785 auto target = symInfos->get().irn.lookup(op.getTarget());
1787 if (target.isPort()) {
1788 auto mod = cast<FModuleOp>(target.getOp());
1789 auto port = target.getPort();
1790 base = mod.getArgument(port);
1792 base = cast<hw::InnerSymbolOpInterface>(target.getOp()).getTargetResult();
1795 emitExpression(base);
1798 auto fieldID = target.getField();
1799 auto type = base.getType();
1801 FIRRTLTypeSwitch<Type, void>(type)
1802 .Case<FVectorType, OpenVectorType>([&](
auto vecTy) {
1803 auto index = vecTy.getIndexForFieldID(fieldID);
1807 auto [subtype, subfieldID] = vecTy.getSubTypeByFieldID(fieldID);
1809 fieldID = subfieldID;
1811 .Case<BundleType, OpenBundleType>([&](
auto bundleTy) {
1812 auto index = bundleTy.getIndexForFieldID(fieldID);
1813 ps <<
"." << bundleTy.getElementName(index);
1814 auto [subtype, subfieldID] = bundleTy.getSubTypeByFieldID(fieldID);
1816 fieldID = subfieldID;
1822void Emitter::emitExpression(RefCastOp op) { emitExpression(op.getInput()); }
1824void Emitter::emitExpression(UninferredResetCastOp op) {
1825 emitExpression(op.getInput());
1828void Emitter::emitExpression(FIntegerConstantOp op) {
1829 if (failed(requireVersion(FIRVersion(3, 1, 0), op,
"Integers")))
1836void Emitter::emitExpression(BoolConstantOp op) {
1837 if (failed(requireVersion({6, 0, 0}, op,
"Bools")))
1839 ps <<
"Bool(" << (op.getValue() ?
"true" :
"false") <<
")";
1842void Emitter::emitExpression(DoubleConstantOp op) {
1843 if (failed(requireVersion({6, 0, 0}, op,
"Doubles")))
1850 SmallString<16> str;
1851 op.getValueAttr().getValue().toString(str);
1856void Emitter::emitExpression(StringConstantOp op) {
1857 if (failed(requireVersion(FIRVersion(3, 1, 0), op,
"Strings")))
1864void Emitter::emitExpression(ListCreateOp op) {
1865 if (failed(requireVersion(FIRVersion(4, 0, 0), op,
"Lists")))
1867 return emitLiteralExpression(op.getType(), op.getElements());
1870void Emitter::emitExpression(OptionCreateOp op) {
1873 emitLiteralExpression(op.getType(), op->getOperands());
1876void Emitter::emitExpression(UnresolvedPathOp op) {
1877 if (failed(requireVersion({6, 0, 0}, op,
"Paths")))
1884void Emitter::emitExpression(GenericIntrinsicOp op) {
1885 if (failed(requireVersion(FIRVersion(4, 0, 0), op,
"generic intrinsics")))
1887 emitGenericIntrinsic(op);
1890void Emitter::emitExpression(ConstCastOp op) { emitExpression(op.getInput()); }
1892void Emitter::emitPrimExpr(StringRef mnemonic, Operation *op,
1893 ArrayRef<uint32_t>
attrs) {
1894 ps << mnemonic <<
"(" << PP::ibox0;
1895 interleaveComma(op->getOperands());
1896 if (!op->getOperands().empty() && !
attrs.empty())
1897 ps <<
"," << PP::space;
1899 ps <<
")" << PP::end;
1902void Emitter::emitExpression(CatPrimOp op) {
1903 size_t numOperands = op.getNumOperands();
1904 switch (numOperands) {
1907 emitType(op.getType(),
false);
1911 auto operand = op->getOperand(0);
1913 if (isa<UIntType>(operand.getType()))
1914 return emitExpression(operand);
1917 ps <<
"cat(" << PP::ibox0;
1918 emitExpression(op->getOperand(0));
1919 ps <<
"," << PP::space <<
"SInt<0>(0))" << PP::end;
1925 for (
size_t i = 0; i < numOperands - 1; ++i) {
1926 ps <<
"cat(" << PP::ibox0;
1927 emitExpression(op->getOperand(i));
1928 ps <<
"," << PP::space;
1931 emitExpression(op->getOperand(numOperands - 1));
1932 for (
size_t i = 0; i < numOperands - 1; ++i)
1933 ps <<
")" << PP::end;
1938void Emitter::emitExpression(UnsafeDomainCastOp op) {
1939 if (failed(requireVersion(
nextFIRVersion, op,
"unsafe_domain_cast")))
1941 ps <<
"unsafe_domain_cast(" << PP::ibox0;
1942 interleaveComma(op.getOperands(),
1943 [&](Value operand) { emitExpression(operand); });
1944 ps <<
")" << PP::end;
1947void Emitter::emitExpression(UnknownValueOp op) {
1949 requireVersion(
nextFIRVersion, op,
"unknown property expressions")))
1952 emitType(op.getType());
1956void Emitter::emitAttribute(MemDirAttr attr) {
1958 case MemDirAttr::Infer:
1961 case MemDirAttr::Read:
1964 case MemDirAttr::Write:
1967 case MemDirAttr::ReadWrite:
1973void Emitter::emitAttribute(RUWBehaviorAttr attr) {
1974 switch (attr.getValue()) {
1975 case RUWBehavior::Undefined:
1978 case RUWBehavior::Old:
1981 case RUWBehavior::New:
1988void Emitter::emitType(Type type,
bool includeConst) {
1989 if (includeConst &&
isConst(type))
1991 auto emitWidth = [&](std::optional<int32_t> width) {
1999 FIRRTLTypeSwitch<Type>(type)
2000 .Case<ClockType>([&](
auto) { ps <<
"Clock"; })
2001 .Case<ResetType>([&](
auto) { ps <<
"Reset"; })
2002 .Case<AsyncResetType>([&](
auto) { ps <<
"AsyncReset"; })
2003 .Case<UIntType>([&](
auto type) {
2005 emitWidth(type.getWidth());
2007 .Case<SIntType>([&](
auto type) {
2009 emitWidth(type.getWidth());
2011 .Case<AnalogType>([&](
auto type) {
2013 emitWidth(type.getWidth());
2015 .Case<OpenBundleType, BundleType>([&](
auto type) {
2017 if (!type.getElements().empty())
2019 bool anyEmitted =
false;
2021 for (
auto &element : type.getElements()) {
2023 ps <<
"," << PP::space;
2027 ps << legalize(element.name);
2028 emitTypeWithColon(element.type);
2037 .Case<OpenVectorType, FVectorType, CMemoryType>([&](
auto type) {
2038 emitType(type.getElementType());
2043 .Case<RefType>([&](RefType type) {
2044 if (type.getForceable())
2047 ps.
cbox(2, IndentStyle::Block);
2049 emitType(type.getType());
2050 if (
auto layer = type.getLayer()) {
2053 emitSymbol(type.getLayer());
2055 ps << BreakToken(0, -2) <<
">";
2058 .Case<ClassType>([&](ClassType type) {
2059 ps <<
"Inst<" << PPExtString(legalize(type.getNameAttr().getAttr()))
2062 .Case<AnyRefType>([&](AnyRefType type) { ps <<
"AnyRef"; })
2063 .Case<StringType>([&](StringType type) { ps <<
"String"; })
2064 .Case<FIntegerType>([&](FIntegerType type) { ps <<
"Integer"; })
2065 .Case<BoolType>([&](BoolType type) { ps <<
"Bool"; })
2066 .Case<DoubleType>([&](DoubleType type) { ps <<
"Double"; })
2067 .Case<PathType>([&](PathType type) { ps <<
"Path"; })
2068 .Case<ListType>([&](ListType type) {
2070 emitType(type.getElementType());
2073 .Case<OptionType>([&](OptionType type) {
2075 emitType(type.getElementType());
2078 .Case<RegistryType>([&](RegistryType type) {
2080 emitType(type.getElementType());
2083 .Case<DomainType>([&](DomainType type) {
2084 ps <<
"Domain of " << PPExtString(type.getName().getValue());
2086 .Default([&](
auto type) {
2087 llvm_unreachable(
"all types should be implemented");
2091void Emitter::emitDomains(Attribute attr, ArrayRef<PortInfo> ports) {
2094 auto domains = cast<ArrayAttr>(attr);
2095 if (domains.empty())
2099 interleaveComma(domains, [&](Attribute attr) {
2100 ps.
addAsString(ports[cast<IntegerAttr>(attr).getUInt()].name.getValue());
2108void Emitter::emitLocation(Location loc) {
2110 ps << PP::neverbreak;
2112 dyn_cast_or_null<FileLineColLoc, LocationAttr>(LocationAttr(loc))) {
2113 ps <<
" @[" << fileLoc.getFilename().getValue();
2114 if (
auto line = fileLoc.getLine()) {
2117 if (
auto col = fileLoc.getColumn()) {
2134 std::optional<size_t> targetLineLength,
2137 return module.emitError("--firrtl-version ")
2138 << version << " is below the minimum supported "
2139 << "version " << minimumFIRVersion;
2140 Emitter emitter(os, version,
2141 targetLineLength.value_or(defaultTargetLineLength));
2142 for (
auto &op : *module.getBody()) {
2143 if (
auto circuitOp = dyn_cast<CircuitOp>(op))
2144 emitter.emitCircuit(circuitOp);
2146 return emitter.finalize();
2151 "target-line-length",
2152 llvm::cl::desc(
"Target line length for emitted .fir; 0 disables line "
2154 llvm::cl::value_desc(
"number of chars"),
2155 llvm::cl::init(defaultTargetLineLength));
2158 llvm::cl::desc(
"FIRRTL version to target (e.g. \"3.0.0\"). "
2159 "Defaults to the latest supported version."),
2160 llvm::cl::value_desc(
"major.minor.patch"), llvm::cl::init(
""));
2161 static mlir::TranslateFromMLIRRegistration toFIR(
2162 "export-firrtl",
"emit FIRRTL dialect operations to .fir output",
2163 [](ModuleOp module, llvm::raw_ostream &os) -> mlir::LogicalResult {
2165 if (!firrtlVersionStr.empty()) {
2168 return module.emitError("invalid --firrtl-version: '")
2170 << "', expected format 'major.minor.patch'";
2173 return exportFIRFile(module, os, targetLineLength, version);
2175 [](mlir::DialectRegistry ®istry) {
2176 registry.insert<chirrtl::CHIRRTLDialect>();
2177 registry.insert<firrtl::FIRRTLDialect>();
assert(baseType &&"element must be base type")
#define HANDLE(OPTYPE, OPKIND)
static bool isEmittedInline(Operation *op)
Check if an operation is inlined into the emission of their users.
static std::vector< mlir::Value > toVector(mlir::ValueRange range)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
void space()
Add a breakable space.
void cbox(int32_t offset=0, IndentStyle style=IndentStyle::Visual)
Start a consistent group with specified offset.
void zerobreak()
Add a break that is zero-wide if not broken.
auto scopedBox(T &&t, Callable &&c, Token close=EndToken())
Open a box, invoke the lambda, and close it after.
TokenStream & addAsString(T &&t)
General-purpose "format this" helper, for types not supported by operator<< yet.
TokenStream & writeQuotedEscaped(StringRef str, bool useHexEscapes=false, StringRef left="\"", StringRef right="\"")
BaseTy type_cast(Type type)
mlir::LogicalResult exportFIRFile(mlir::ModuleOp module, llvm::raw_ostream &os, std::optional< size_t > targetLineLength, FIRVersion version)
constexpr FIRVersion nextFIRVersion(7, 0, 0)
The next version of FIRRTL that is not yet released.
constexpr FIRVersion exportFIRVersion
The version of FIRRTL that the exporter produces.
void registerToFIRFileTranslation()
bool isConst(Type type)
Returns true if this is a 'const' type whose value is guaranteed to be unchanging at circuit executio...
constexpr FIRVersion missingSpecFIRVersion
A marker for parser features that are currently missing from the spec.
bool isExpression(Operation *op)
Return true if the specified operation is a firrtl expression.
constexpr FIRVersion minimumFIRVersion(2, 0, 0)
The current minimum version of FIRRTL that the parser supports.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
The FIRRTL specification version.
static std::optional< FIRVersion > fromString(StringRef str)
Parse a version string of the form "major.minor.patch".