CIRCT 23.0.0git
Loading...
Searching...
No Matches
FIRRTLIntrinsics.cpp
Go to the documentation of this file.
1//===- FIRRTLIntrinsics.cpp - Lower Intrinsics ------------------*- C++ -*-===//
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
14#include "circt/Support/JSON.h"
15#include "mlir/Transforms/DialectConversion.h"
16#include "llvm/Support/JSON.h"
17
18using namespace circt;
19using namespace firrtl;
20
21// vtable anchor
23
24//===----------------------------------------------------------------------===//
25// GenericIntrinsic
26//===----------------------------------------------------------------------===//
27
28// Checks for a number of operands between n and n+c (allows for c optional
29// inputs)
30ParseResult GenericIntrinsic::hasNInputs(unsigned n, unsigned c) {
31 auto numOps = op.getNumOperands();
32 unsigned m = n + c;
33 if (numOps < n || numOps > m) {
34 auto err = emitError() << " has " << numOps << " inputs instead of ";
35 if (c == 0)
36 err << n;
37 else
38 err << " between " << n << " and " << m;
39 return failure();
40 }
41 return success();
42}
43
44// Accessor method for the number of inputs
45unsigned GenericIntrinsic::getNumInputs() { return op.getNumOperands(); }
46
47ParseResult GenericIntrinsic::hasNOutputElements(unsigned n) {
48 auto b = getOutputBundle();
49 if (!b)
50 return emitError() << " missing output bundle";
51 if (b.getType().getNumElements() != n)
52 return emitError() << " has " << b.getType().getNumElements()
53 << " output elements instead of " << n;
54 return success();
55}
56
57ParseResult GenericIntrinsic::hasNParam(unsigned n, unsigned c) {
58 unsigned num = 0;
59 if (op.getParameters())
60 num = op.getParameters().size();
61 if (num < n || num > n + c) {
62 auto d = emitError() << " has " << num << " parameters instead of ";
63 if (c == 0)
64 d << n;
65 else
66 d << " between " << n << " and " << (n + c);
67 return failure();
68 }
69 return success();
70}
71
72ParseResult GenericIntrinsic::namedParam(StringRef paramName, bool optional) {
73 for (auto a : op.getParameters()) {
74 auto param = cast<ParamDeclAttr>(a);
75 if (param.getName().getValue() == paramName) {
76 if (isa<StringAttr>(param.getValue()))
77 return success();
78
79 return emitError() << " has parameter '" << param.getName()
80 << "' which should be a string but is not";
81 }
82 }
83 if (optional)
84 return success();
85 return emitError() << " is missing parameter " << paramName;
86}
87
88ParseResult GenericIntrinsic::namedIntParam(StringRef paramName,
89 bool optional) {
90 for (auto a : op.getParameters()) {
91 auto param = cast<ParamDeclAttr>(a);
92 if (param.getName().getValue() == paramName) {
93 if (isa<IntegerAttr>(param.getValue()))
94 return success();
95
96 return emitError() << " has parameter '" << param.getName()
97 << "' which should be an integer but is not";
98 }
99 }
100 if (optional)
101 return success();
102 return emitError() << " is missing parameter " << paramName;
103}
104
105//===----------------------------------------------------------------------===//
106// IntrinsicOpConversion
107//===----------------------------------------------------------------------===//
108
109/// Conversion pattern adaptor dispatching via generic intrinsic name.
110namespace {
111class IntrinsicOpConversion final
112 : public OpConversionPattern<GenericIntrinsicOp> {
113public:
114 using ConversionMapTy = IntrinsicLowerings::ConversionMapTy;
115
116 IntrinsicOpConversion(TypeConverter &typeConverter, MLIRContext *context,
117 const ConversionMapTy &conversions,
118 size_t &numConversions,
119 bool allowUnknownIntrinsics = false)
120 : OpConversionPattern(typeConverter, context), conversions(conversions),
121 numConversions(numConversions),
122 allowUnknownIntrinsics(allowUnknownIntrinsics) {}
123
124 LogicalResult
125 matchAndRewrite(GenericIntrinsicOp op, OpAdaptor adaptor,
126 ConversionPatternRewriter &rewriter) const override {
127
128 auto it = conversions.find(op.getIntrinsicAttr());
129 if (it == conversions.end()) {
130 if (!allowUnknownIntrinsics)
131 return op.emitError("unknown intrinsic ") << op.getIntrinsicAttr();
132 return failure();
133 }
134
135 auto &conv = *it->second;
136 auto result = conv.checkAndConvert(GenericIntrinsic(op), adaptor, rewriter);
137 if (succeeded(result))
138 ++numConversions;
139 return result;
140 }
141
142private:
143 const ConversionMapTy &conversions;
144 size_t &numConversions;
145 const bool allowUnknownIntrinsics;
146};
147} // namespace
148
149//===----------------------------------------------------------------------===//
150// IntrinsicLowerings
151//===----------------------------------------------------------------------===//
152
153FailureOr<size_t> IntrinsicLowerings::lower(FModuleOp mod,
154 bool allowUnknownIntrinsics) {
155
156 ConversionTarget target(*context);
157
158 target.markUnknownOpDynamicallyLegal([](Operation *op) { return true; });
159 if (allowUnknownIntrinsics)
160 target.addDynamicallyLegalOp<GenericIntrinsicOp>(
161 [this](GenericIntrinsicOp op) {
162 return !conversions.contains(op.getIntrinsicAttr());
163 });
164 else
165 target.addIllegalOp<GenericIntrinsicOp>();
166
167 // Automatically insert wires + connect for compatible FIRRTL base types.
168 // For now, this is not customizable/extendable.
169 TypeConverter typeConverter;
170 typeConverter.addConversion([](Type type) { return type; });
171 auto firrtlBaseTypeMaterialization =
172 [](OpBuilder &builder, FIRRTLBaseType resultType, ValueRange inputs,
173 Location loc) -> Value {
174 if (inputs.size() != 1)
175 return {};
176 auto inputType = type_dyn_cast<FIRRTLBaseType>(inputs.front().getType());
177 if (!inputType)
178 return {};
179
180 if (!areTypesEquivalent(resultType, inputType) ||
181 !isTypeLarger(resultType, inputType))
182 return {};
183
184 auto w = WireOp::create(builder, loc, resultType).getResult();
185 emitConnect(builder, loc, w, inputs.front());
186 return w;
187 };
188 // New result doesn't match? Add wire + connect.
189 typeConverter.addSourceMaterialization(firrtlBaseTypeMaterialization);
190 // New operand doesn't match? Add wire + connect.
191 typeConverter.addTargetMaterialization(firrtlBaseTypeMaterialization);
192
193 RewritePatternSet patterns(context);
194 size_t count = 0;
195 patterns.add<IntrinsicOpConversion>(typeConverter, context, conversions,
196 count, allowUnknownIntrinsics);
197
198 if (failed(mlir::applyPartialConversion(mod, target, std::move(patterns))))
199 return failure();
200
201 return count;
202}
203
204//===----------------------------------------------------------------------===//
205// IntrinsicLoweringInterfaceCollection
206//===----------------------------------------------------------------------===//
207
209 IntrinsicLowerings &lowering) const {
210 for (const IntrinsicLoweringDialectInterface &interface : *this)
211 interface.populateIntrinsicLowerings(lowering);
212}
213
214//===----------------------------------------------------------------------===//
215// FIRRTL intrinsic lowering converters
216//===----------------------------------------------------------------------===//
217
218namespace {
219
220class CirctSizeofConverter : public IntrinsicOpConverter<SizeOfIntrinsicOp> {
221public:
222 using IntrinsicOpConverter::IntrinsicOpConverter;
223
224 bool check(GenericIntrinsic gi) override {
225 return gi.hasNInputs(1) || gi.sizedOutput<UIntType>(32) || gi.hasNParam(0);
226 }
227};
228
229class CirctIsXConverter : public IntrinsicOpConverter<IsXIntrinsicOp> {
230public:
231 using IntrinsicOpConverter::IntrinsicOpConverter;
232
233 bool check(GenericIntrinsic gi) override {
234 return gi.hasNInputs(1) || gi.sizedOutput<UIntType>(1) || gi.hasNParam(0);
235 }
236};
237
238class CirctPlusArgTestConverter : public IntrinsicConverter {
239public:
240 using IntrinsicConverter::IntrinsicConverter;
241
242 bool check(GenericIntrinsic gi) override {
243 return gi.hasNInputs(0) || gi.sizedOutput<UIntType>(1) ||
244 gi.namedParam("FORMAT") || gi.hasNParam(1);
245 }
246
247 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
248 PatternRewriter &rewriter) override {
249 rewriter.replaceOpWithNewOp<PlusArgsTestIntrinsicOp>(
250 gi.op, gi.getParamValue<StringAttr>("FORMAT"));
251 }
252};
253
254class CirctPlusArgValueConverter : public IntrinsicConverter {
255public:
256 using IntrinsicConverter::IntrinsicConverter;
257
258 bool check(GenericIntrinsic gi) override {
259 return gi.hasNOutputElements(2) ||
260 gi.sizedOutputElement<UIntType>(0, "found", 1) ||
261 gi.hasOutputElement(1, "result") || gi.namedParam("FORMAT") ||
262 gi.hasNParam(1);
263 }
264
265 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
266 PatternRewriter &rewriter) override {
267 auto bty = gi.getOutputBundle().getType();
268 auto newop = PlusArgsValueIntrinsicOp::create(
269 rewriter, gi.op.getLoc(), bty.getElementTypePreservingConst(0),
270 bty.getElementTypePreservingConst(1),
271 gi.getParamValue<StringAttr>("FORMAT"));
272 rewriter.replaceOpWithNewOp<BundleCreateOp>(
273 gi.op, bty, ValueRange({newop.getFound(), newop.getResult()}));
274 }
275};
276
277class CirctClockGateConverter
278 : public IntrinsicOpConverter<ClockGateIntrinsicOp> {
279public:
280 using IntrinsicOpConverter::IntrinsicOpConverter;
281
282 bool check(GenericIntrinsic gi) override {
283 if (gi.op.getNumOperands() == 3) {
284 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
285 gi.sizedInput<UIntType>(2, 1) || gi.typedOutput<ClockType>() ||
286 gi.hasNParam(0);
287 }
288 if (gi.op.getNumOperands() == 2) {
289 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
290 gi.typedOutput<ClockType>() || gi.hasNParam(0);
291 }
292 gi.emitError() << " has " << gi.op.getNumOperands()
293 << " ports instead of 3 or 4";
294 return true;
295 }
296};
297
298class CirctClockInverterConverter
299 : public IntrinsicOpConverter<ClockInverterIntrinsicOp> {
300public:
301 using IntrinsicOpConverter::IntrinsicOpConverter;
302
303 bool check(GenericIntrinsic gi) override {
304 return gi.hasNInputs(1) || gi.typedInput<ClockType>(0) ||
305 gi.typedOutput<ClockType>() || gi.hasNParam(0);
306 }
307};
308
309class CirctClockDividerConverter : public IntrinsicConverter {
310public:
311 using IntrinsicConverter::IntrinsicConverter;
312
313 bool check(GenericIntrinsic gi) override {
314 return gi.hasNInputs(1) || gi.typedInput<ClockType>(0) ||
315 gi.typedOutput<ClockType>() || gi.namedIntParam("POW_2") ||
316 gi.hasNParam(1);
317 }
318
319 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
320 PatternRewriter &rewriter) override {
321 auto pow2 =
322 gi.getParamValue<IntegerAttr>("POW_2").getValue().getZExtValue();
323
324 auto pow2Attr = rewriter.getI64IntegerAttr(pow2);
325
326 rewriter.replaceOpWithNewOp<ClockDividerIntrinsicOp>(
327 gi.op, adaptor.getOperands()[0], pow2Attr);
328 }
329};
330
331template <typename OpTy>
332class CirctLTLBinaryConverter : public IntrinsicOpConverter<OpTy> {
333public:
335
336 bool check(GenericIntrinsic gi) override {
337 return gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
338 gi.sizedInput<UIntType>(1, 1) || gi.sizedOutput<UIntType>(1) ||
339 gi.hasNParam(0);
340 }
341};
342
343template <typename OpTy>
344class CirctLTLUnaryConverter : public IntrinsicOpConverter<OpTy> {
345public:
347
348 bool check(GenericIntrinsic gi) override {
349 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
350 gi.sizedOutput<UIntType>(1) || gi.hasNParam(0);
351 }
352};
353
354class CirctLTLDelayConverter : public IntrinsicConverter {
355public:
356 using IntrinsicConverter::IntrinsicConverter;
357
358 bool check(GenericIntrinsic gi) override {
359 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
360 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("delay") ||
361 gi.namedIntParam("length", true) || gi.hasNParam(1, 1);
362 }
363
364 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
365 PatternRewriter &rewriter) override {
366 auto getI64Attr = [&](IntegerAttr val) {
367 if (!val)
368 return IntegerAttr();
369 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
370 };
371 auto delay = getI64Attr(gi.getParamValue<IntegerAttr>("delay"));
372 auto length = getI64Attr(gi.getParamValue<IntegerAttr>("length"));
373 rewriter.replaceOpWithNewOp<LTLDelayIntrinsicOp>(
374 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], delay, length);
375 }
376};
377
378class CirctLTLPastConverter : public IntrinsicConverter {
379public:
380 using IntrinsicConverter::IntrinsicConverter;
381
382 bool check(GenericIntrinsic gi) override {
383 if (gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
384 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("delay") ||
385 gi.hasNParam(1))
386 return true;
387 if (gi.typedInput<ClockType>(1))
388 return true;
389 return false;
390 }
391
392 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
393 PatternRewriter &rewriter) override {
394 auto delay = rewriter.getI64IntegerAttr(
395 gi.getParamValue<IntegerAttr>("delay").getValue().getZExtValue());
396 auto operands = adaptor.getOperands();
397 Value clock = operands[1];
398 rewriter.replaceOpWithNewOp<LTLPastIntrinsicOp>(
399 gi.op, gi.op.getResultTypes(), operands[0], delay, clock);
400 }
401};
402
403class CirctLTLClockConverter
404 : public IntrinsicOpConverter<LTLClockIntrinsicOp> {
405public:
406 using IntrinsicOpConverter::IntrinsicOpConverter;
407
408 bool check(GenericIntrinsic gi) override {
409 return gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
410 gi.typedInput<ClockType>(1) || gi.sizedOutput<UIntType>(1) ||
411 gi.hasNParam(0);
412 }
413};
414
415class CirctLTLRepeatConverter : public IntrinsicConverter {
416public:
417 using IntrinsicConverter::IntrinsicConverter;
418
419 bool check(GenericIntrinsic gi) override {
420 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
421 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
422 gi.namedIntParam("more", true) || gi.hasNParam(1, 1);
423 }
424
425 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
426 PatternRewriter &rewriter) override {
427 auto getI64Attr = [&](IntegerAttr val) {
428 if (!val)
429 return IntegerAttr();
430 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
431 };
432 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
433 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
434 rewriter.replaceOpWithNewOp<LTLRepeatIntrinsicOp>(
435 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
436 }
437};
438
439class CirctLTLGoToRepeatConverter : public IntrinsicConverter {
440public:
441 using IntrinsicConverter::IntrinsicConverter;
442
443 bool check(GenericIntrinsic gi) override {
444 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
445 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
446 gi.namedIntParam("more") || gi.hasNParam(1, 1);
447 }
448
449 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
450 PatternRewriter &rewriter) override {
451 auto getI64Attr = [&](IntegerAttr val) {
452 if (!val)
453 return IntegerAttr();
454 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
455 };
456 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
457 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
458 rewriter.replaceOpWithNewOp<LTLGoToRepeatIntrinsicOp>(
459 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
460 }
461};
462
463class CirctLTLNonConsecutiveRepeatConverter : public IntrinsicConverter {
464public:
465 using IntrinsicConverter::IntrinsicConverter;
466
467 bool check(GenericIntrinsic gi) override {
468 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
469 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
470 gi.namedIntParam("more") || gi.hasNParam(1, 1);
471 }
472
473 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
474 PatternRewriter &rewriter) override {
475 auto getI64Attr = [&](IntegerAttr val) {
476 if (!val)
477 return IntegerAttr();
478 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
479 };
480 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
481 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
482 rewriter.replaceOpWithNewOp<LTLNonConsecutiveRepeatIntrinsicOp>(
483 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
484 }
485};
486
487template <class Op>
488class CirctVerifConverter : public IntrinsicConverter {
489public:
490 using IntrinsicConverter::IntrinsicConverter;
491
492 bool check(GenericIntrinsic gi) override {
493 return gi.hasNInputs(1, 2) || gi.sizedInput<UIntType>(0, 1) ||
494 gi.namedParam("label", true) || gi.hasNParam(0, 1) ||
495 gi.hasNoOutput();
496 }
497
498 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
499 PatternRewriter &rewriter) override {
500 auto label = gi.getParamValue<StringAttr>("label");
501 auto operands = adaptor.getOperands();
502
503 // Check if an enable was provided
504 Value enable;
505 if (gi.getNumInputs() == 2)
506 enable = operands[1];
507
508 rewriter.replaceOpWithNewOp<Op>(gi.op, operands[0], enable, label);
509 }
510};
511
512class CirctMux2CellConverter : public IntrinsicConverter {
513 using IntrinsicConverter::IntrinsicConverter;
514
515 bool check(GenericIntrinsic gi) override {
516 return gi.hasNInputs(3) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
517 gi.hasOutput();
518 }
519
520 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
521 PatternRewriter &rewriter) override {
522 auto operands = adaptor.getOperands();
523 rewriter.replaceOpWithNewOp<Mux2CellIntrinsicOp>(gi.op, operands[0],
524 operands[1], operands[2]);
525 }
526};
527
528class CirctMux4CellConverter : public IntrinsicConverter {
529 using IntrinsicConverter::IntrinsicConverter;
530
531 bool check(GenericIntrinsic gi) override {
532 return gi.hasNInputs(5) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
533 gi.hasOutput();
534 }
535
536 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
537 PatternRewriter &rewriter) override {
538 auto operands = adaptor.getOperands();
539 rewriter.replaceOpWithNewOp<Mux4CellIntrinsicOp>(
540 gi.op, operands[0], operands[1], operands[2], operands[3], operands[4]);
541 }
542};
543
544class CirctHasBeenResetConverter
545 : public IntrinsicOpConverter<HasBeenResetIntrinsicOp> {
546public:
547 using IntrinsicOpConverter::IntrinsicOpConverter;
548
549 bool check(GenericIntrinsic gi) override {
550 return gi.hasNInputs(2) || gi.typedInput<ClockType>(0) ||
551 gi.hasResetInput(1) || gi.sizedOutput<UIntType>(1) ||
552 gi.hasNParam(0);
553 }
554};
555
556class CirctProbeConverter : public IntrinsicOpConverter<FPGAProbeIntrinsicOp> {
557public:
558 using IntrinsicOpConverter::IntrinsicOpConverter;
559
560 bool check(GenericIntrinsic gi) override {
561 return gi.hasNInputs(2) || gi.typedInput<ClockType>(1) || gi.hasNParam(0) ||
562 gi.hasNoOutput();
563 }
564};
565
566template <class OpTy, bool ifElseFatal = false>
567class CirctAssertConverter : public IntrinsicConverter {
568public:
569 using IntrinsicConverter::IntrinsicConverter;
570
571 LogicalResult checkAndConvert(GenericIntrinsic gi,
572 GenericIntrinsicOpAdaptor adaptor,
573 PatternRewriter &rewriter) override {
574 // Check structure of the intrinsic.
575 if (gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
576 gi.sizedInput<UIntType>(2, 1) ||
577 gi.namedParam("format", /*optional=*/true) ||
578 gi.namedParam("label", /*optional=*/true) ||
579 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
580 gi.hasNoOutput())
581 return failure();
582
583 auto format = gi.getParamValue<StringAttr>("format");
584 auto label = gi.getParamValue<StringAttr>("label");
585 auto guards = gi.getParamValue<StringAttr>("guards");
586
587 auto clock = adaptor.getOperands()[0];
588 auto predicate = adaptor.getOperands()[1];
589 auto enable = adaptor.getOperands()[2];
590
591 auto substitutions = adaptor.getOperands().drop_front(3);
592 auto name = label ? label.strref() : "";
593
594 // Parse the format string to handle special substitutions like
595 // {{SimulationTime}} and {{HierarchicalModuleName}}
596 StringAttr message;
597 SmallVector<Value> allOperands;
598 if (format) {
599 SmallVector<Value> substitutionVec(substitutions.begin(),
600 substitutions.end());
601 if (failed(parseFormatString(rewriter, gi.op->getLoc(), format.getValue(),
602 substitutionVec, message, allOperands)))
603 return failure();
604 } else {
605 // Message is not optional, so provide empty string if not present.
606 message = rewriter.getStringAttr("");
607 allOperands.append(substitutions.begin(), substitutions.end());
608 }
609
610 auto op = rewriter.template replaceOpWithNewOp<OpTy>(
611 gi.op, clock, predicate, enable, message, allOperands, name,
612 /*isConcurrent=*/true);
613 if (guards) {
614 SmallVector<StringRef> guardStrings;
615 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
616 /*KeepEmpty=*/false);
617 rewriter.startOpModification(op);
618 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
619 rewriter.finalizeOpModification(op);
620 }
621
622 if constexpr (ifElseFatal) {
623 rewriter.startOpModification(op);
624 op->setAttr("format", rewriter.getStringAttr("ifElseFatal"));
625 rewriter.finalizeOpModification(op);
626 }
627
628 return success();
629 }
630};
631
632class CirctCoverConverter : public IntrinsicConverter {
633public:
634 using IntrinsicConverter::IntrinsicConverter;
635
636 bool check(GenericIntrinsic gi) override {
637 return gi.hasNInputs(3) || gi.hasNoOutput() ||
638 gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
639 gi.sizedInput<UIntType>(2, 1) ||
640 gi.namedParam("label", /*optional=*/true) ||
641 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 2);
642 }
643
644 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
645 PatternRewriter &rewriter) override {
646 auto label = gi.getParamValue<StringAttr>("label");
647 auto guards = gi.getParamValue<StringAttr>("guards");
648
649 auto clock = adaptor.getOperands()[0];
650 auto predicate = adaptor.getOperands()[1];
651 auto enable = adaptor.getOperands()[2];
652
653 auto name = label ? label.strref() : "";
654 // Empty message string for cover, only 'name' / label.
655 auto message = rewriter.getStringAttr("");
656 auto op = rewriter.replaceOpWithNewOp<CoverOp>(
657 gi.op, clock, predicate, enable, message, ValueRange{}, name,
658 /*isConcurrent=*/true);
659 if (guards) {
660 SmallVector<StringRef> guardStrings;
661 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
662 /*KeepEmpty=*/false);
663 rewriter.startOpModification(op);
664 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
665 rewriter.finalizeOpModification(op);
666 }
667 }
668};
669
670class CirctUnclockedAssumeConverter : public IntrinsicConverter {
671public:
672 using IntrinsicConverter::IntrinsicConverter;
673
674 bool check(GenericIntrinsic gi) override {
675 return gi.sizedInput<UIntType>(0, 1) || gi.sizedInput<UIntType>(1, 1) ||
676 gi.namedParam("format", /*optional=*/true) ||
677 gi.namedParam("label", /*optional=*/true) ||
678 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
679 gi.hasNoOutput();
680 }
681
682 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
683 PatternRewriter &rewriter) override {
684 auto format = gi.getParamValue<StringAttr>("format");
685 auto label = gi.getParamValue<StringAttr>("label");
686 auto guards = gi.getParamValue<StringAttr>("guards");
687
688 auto predicate = adaptor.getOperands()[0];
689 auto enable = adaptor.getOperands()[1];
690
691 auto substitutions = adaptor.getOperands().drop_front(2);
692 auto name = label ? label.strref() : "";
693 // Message is not optional, so provide empty string if not present.
694 auto message = format ? format : rewriter.getStringAttr("");
695 auto op = rewriter.template replaceOpWithNewOp<UnclockedAssumeIntrinsicOp>(
696 gi.op, predicate, enable, message, substitutions, name);
697 if (guards) {
698 SmallVector<StringRef> guardStrings;
699 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
700 /*KeepEmpty=*/false);
701 rewriter.startOpModification(op);
702 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
703 rewriter.finalizeOpModification(op);
704 }
705 }
706};
707
708class CirctDPICallConverter : public IntrinsicConverter {
709 static bool getIsClocked(GenericIntrinsic gi) {
710 return !gi.getParamValue<IntegerAttr>("isClocked").getValue().isZero();
711 }
712
713public:
714 using IntrinsicConverter::IntrinsicConverter;
715
716 bool check(GenericIntrinsic gi) override {
717 if (gi.hasNParam(2, 2) || gi.namedIntParam("isClocked") ||
718 gi.namedParam("functionName") ||
719 gi.namedParam("inputNames", /*optional=*/true) ||
720 gi.namedParam("outputName", /*optional=*/true))
721 return true;
722 auto isClocked = getIsClocked(gi);
723 // If clocked, the first operand must be a clock.
724 if (isClocked && gi.typedInput<ClockType>(0))
725 return true;
726 // Enable must be UInt<1>.
727 if (gi.sizedInput<UIntType>(isClocked, 1))
728 return true;
729
730 return false;
731 }
732
733 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
734 PatternRewriter &rewriter) override {
735 auto isClocked = getIsClocked(gi);
736 auto functionName = gi.getParamValue<StringAttr>("functionName");
737 ArrayAttr inputNamesStrArray;
738 StringAttr outputStr = gi.getParamValue<StringAttr>("outputName");
739 if (auto inputNames = gi.getParamValue<StringAttr>("inputNames")) {
740 SmallVector<StringRef> inputNamesTemporary;
741 inputNames.strref().split(inputNamesTemporary, ';', /*MaxSplit=*/-1,
742 /*KeepEmpty=*/false);
743 inputNamesStrArray = rewriter.getStrArrayAttr(inputNamesTemporary);
744 }
745 // Clock and enable are optional.
746 Value clock = isClocked ? adaptor.getOperands()[0] : Value();
747 Value enable = adaptor.getOperands()[static_cast<size_t>(isClocked)];
748
749 auto inputs =
750 adaptor.getOperands().drop_front(static_cast<size_t>(isClocked) + 1);
751
752 rewriter.replaceOpWithNewOp<DPICallIntrinsicOp>(
753 gi.op, gi.op.getResultTypes(), functionName, inputNamesStrArray,
754 outputStr, clock, enable, inputs);
755 }
756};
757
758//===----------------------------------------------------------------------===//
759// View intrinsic converter and helpers
760//===----------------------------------------------------------------------===//
761
762template <typename A>
763A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc,
764 Twine path = Twine()) {
765 return tryGetAsBase<A>(dict, root, key, loc, "View 'info'",
766 "'info' attribute", path);
767}
768
769/// Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract
770/// and slightly restructure information needed for a view.
771std::optional<DictionaryAttr>
772parseAugmentedType(MLIRContext *context, Location loc,
773 DictionaryAttr augmentedType, DictionaryAttr root,
774 StringAttr name, StringAttr defName,
775 std::optional<StringAttr> description, Twine path = {}) {
776 auto classAttr =
777 tryGetAs<StringAttr>(augmentedType, root, "class", loc, path);
778 if (!classAttr)
779 return std::nullopt;
780 StringRef classBase = classAttr.getValue();
781 if (!classBase.consume_front("sifive.enterprise.grandcentral.Augmented")) {
782 mlir::emitError(loc,
783 "the 'class' was expected to start with "
784 "'sifive.enterprise.grandCentral.Augmented*', but was '" +
785 classAttr.getValue() + "' (Did you misspell it?)")
786 .attachNote()
787 << "see attribute: " << augmentedType;
788 return std::nullopt;
789 }
790
791 // An AugmentedBundleType looks like:
792 // "defName": String
793 // "elements": Seq[AugmentedField]
794 if (classBase == "BundleType") {
795 defName = tryGetAs<StringAttr>(augmentedType, root, "defName", loc, path);
796 if (!defName)
797 return std::nullopt;
798
799 // Each element is an AugmentedField with members:
800 // "name": String
801 // "description": Option[String]
802 // "tpe": AugmentedType
803 SmallVector<Attribute> elements;
804 auto elementsAttr =
805 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
806 if (!elementsAttr)
807 return std::nullopt;
808 for (size_t i = 0, e = elementsAttr.size(); i != e; ++i) {
809 auto field = dyn_cast_or_null<DictionaryAttr>(elementsAttr[i]);
810 if (!field) {
811 mlir::emitError(
812 loc,
813 "View 'info' attribute with path '.elements[" + Twine(i) +
814 "]' contained an unexpected type (expected a DictionaryAttr).")
815 .attachNote()
816 << "The received element was: " << elementsAttr[i];
817 return std::nullopt;
818 }
819 auto ePath = (path + ".elements[" + Twine(i) + "]").str();
820 auto name = tryGetAs<StringAttr>(field, root, "name", loc, ePath);
821 if (!name)
822 return std::nullopt;
823 auto tpe = tryGetAs<DictionaryAttr>(field, root, "tpe", loc, ePath);
824 if (!tpe)
825 return std::nullopt;
826 std::optional<StringAttr> description;
827 if (auto maybeDescription = field.get("description"))
828 description = cast<StringAttr>(maybeDescription);
829 auto eltAttr =
830 parseAugmentedType(context, loc, tpe, root, name, defName,
831 description, path + "_" + name.getValue());
832 if (!eltAttr)
833 return std::nullopt;
834
835 // Collect information necessary to build a module with this view later.
836 // This includes the optional description and name.
837 NamedAttrList attrs;
838 if (auto maybeDescription = field.get("description"))
839 attrs.append("description", cast<StringAttr>(maybeDescription));
840 attrs.append("name", name);
841 auto tpeClass = tpe.getAs<StringAttr>("class");
842 if (!tpeClass) {
843 mlir::emitError(loc, "missing 'class' key in") << tpe;
844 return std::nullopt;
845 }
846 attrs.append("tpe", tpeClass);
847 elements.push_back(*eltAttr);
848 }
849 // Add an attribute that stores information necessary to construct the
850 // interface for the view. This needs the name of the interface (defName)
851 // and the names of the components inside it.
852 NamedAttrList attrs;
853 attrs.append("class", classAttr);
854 attrs.append("defName", defName);
855 if (description)
856 attrs.append("description", *description);
857 attrs.append("elements", ArrayAttr::get(context, elements));
858 attrs.append("name", name);
859 return DictionaryAttr::getWithSorted(context, attrs);
860 }
861
862 // An AugmentedGroundType has no contents.
863 if (classBase == "GroundType") {
864 NamedAttrList elementIface;
865
866 // Populate the attribute for the interface element.
867 elementIface.append("class", classAttr);
868 if (description)
869 elementIface.append("description", *description);
870 elementIface.append("name", name);
871
872 return DictionaryAttr::getWithSorted(context, elementIface);
873 }
874
875 // An AugmentedVectorType looks like:
876 // "elements": Seq[AugmentedType]
877 if (classBase == "VectorType") {
878 auto elementsAttr =
879 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
880 if (!elementsAttr)
881 return std::nullopt;
882 SmallVector<Attribute> elements;
883 for (auto [i, elt] : llvm::enumerate(elementsAttr)) {
884 auto eltAttr = parseAugmentedType(
885 context, loc, cast<DictionaryAttr>(elt), root, name,
886 StringAttr::get(context, ""), std::nullopt, path + "_" + Twine(i));
887 if (!eltAttr)
888 return std::nullopt;
889 elements.push_back(*eltAttr);
890 }
891 NamedAttrList attrs;
892 attrs.append("class", classAttr);
893 if (description)
894 attrs.append("description", *description);
895 attrs.append("elements", ArrayAttr::get(context, elements));
896 attrs.append("name", name);
897 return DictionaryAttr::getWithSorted(context, attrs);
898 }
899
900 // Anything else is unexpected or a user error if they manually wrote
901 // the JSON/attribute. Print an error and error out.
902 mlir::emitError(loc, "found unknown AugmentedType '" + classAttr.getValue() +
903 "' (Did you misspell it?)")
904 .attachNote()
905 << "see attribute: " << augmentedType;
906 return std::nullopt;
907}
908
909class ViewConverter : public IntrinsicConverter {
910public:
911 LogicalResult checkAndConvert(GenericIntrinsic gi,
912 GenericIntrinsicOpAdaptor adaptor,
913 PatternRewriter &rewriter) override {
914 // Check structure of the intrinsic.
915 if (gi.hasNoOutput() || gi.namedParam("info") || gi.namedParam("name") ||
916 gi.namedParam("yaml", true))
917 return failure();
918
919 // Check operands.
920 for (auto idx : llvm::seq(gi.getNumInputs()))
921 if (gi.checkInputType(idx, "must be ground type", [](auto ty) {
922 auto base = type_dyn_cast<FIRRTLBaseType>(ty);
923 return base && base.isGround();
924 }))
925 return failure();
926
927 // Parse "info" string parameter as JSON.
928 auto view =
929 llvm::json::parse(gi.getParamValue<StringAttr>("info").getValue());
930 if (auto err = view.takeError()) {
931 handleAllErrors(std::move(err), [&](const llvm::json::ParseError &a) {
932 gi.emitError() << ": error parsing view JSON: " << a.message();
933 });
934 return failure();
935 }
936
937 // Convert JSON to MLIR attribute.
938 llvm::json::Path::Root root;
939 auto value = convertJSONToAttribute(gi.op.getContext(), view.get(), root);
940 assert(value && "JSON to attribute failed but should not ever fail");
941
942 // Check attribute is a dictionary, for AugmentedBundleTypeAttr
943 // construction.
944 auto dict = dyn_cast<DictionaryAttr>(value);
945 if (!dict)
946 return gi.emitError() << ": 'info' parameter must be a dictionary";
947
948 auto nameAttr = gi.getParamValue<StringAttr>("name");
949 auto result = parseAugmentedType(
950 gi.op.getContext(), gi.op.getLoc(), dict, dict, nameAttr,
951 /* defName= */ {}, /* description= */ std::nullopt);
952
953 if (!result)
954 return failure();
955
956 // Build AugmentedBundleTypeAttr, unchecked.
957 auto augmentedType =
958 AugmentedBundleTypeAttr::get(gi.op.getContext(), *result);
959 if (augmentedType.getClass() != augmentedBundleTypeAnnoClass)
960 return gi.emitError() << ": 'info' must be augmented bundle";
961
962 // Scan for ground-type (leaves) and count.
963 SmallVector<DictionaryAttr> worklist;
964 worklist.push_back(augmentedType.getUnderlying());
965 size_t numLeaves = 0;
966 auto augGroundAttr =
967 StringAttr::get(gi.op.getContext(), augmentedGroundTypeAnnoClass);
968 [[maybe_unused]] auto augBundleAttr =
969 StringAttr::get(gi.op.getContext(), augmentedBundleTypeAnnoClass);
970 [[maybe_unused]] auto augVectorAttr =
971 StringAttr::get(gi.op.getContext(), augmentedVectorTypeAnnoClass);
972 while (!worklist.empty()) {
973 auto dict = worklist.pop_back_val();
974 auto clazz = dict.getAs<StringAttr>("class");
975 if (clazz == augGroundAttr) {
976 ++numLeaves;
977 continue;
978 }
979 assert(clazz == augBundleAttr || clazz == augVectorAttr);
980 llvm::append_range(
981 worklist,
982 dict.getAs<ArrayAttr>("elements").getAsRange<DictionaryAttr>());
983 }
984
985 if (numLeaves != gi.getNumInputs())
986 return gi.emitError()
987 << " has " << gi.getNumInputs() << " operands but view 'info' has "
988 << numLeaves << " leaf elements";
989
990 // Check complete, convert!
991 auto yaml = gi.getParamValue<StringAttr>("yaml");
992 rewriter.replaceOpWithNewOp<ViewIntrinsicOp>(
993 gi.op, nameAttr.getValue(), yaml, augmentedType, adaptor.getOperands());
994 return success();
995 }
996};
997
998} // namespace
999
1000//===----------------------------------------------------------------------===//
1001// FIRRTL intrinsic lowering dialect interface
1002//===----------------------------------------------------------------------===//
1003
1004#include "FIRRTLIntrinsics.cpp.inc"
1005
1007 IntrinsicLowerings &lowering) const {
1008 populateLowerings(lowering);
1009}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static std::optional< DictionaryAttr > parseAugmentedType(ApplyState &state, DictionaryAttr augmentedType, DictionaryAttr root, StringAttr name, StringAttr defName, std::optional< IntegerAttr > id, std::optional< StringAttr > description, Twine clazz, StringAttr companionAttr, Twine path={})
Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract any annotations it may con...
static LogicalResult convert(arc::ExecuteOp op, arc::ExecuteOp::Adaptor adaptor, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
Base class for Intrinsic Converters.
Lowering helper which collects all intrinsic converters.
FailureOr< size_t > lower(FModuleOp mod, bool allowUnknownIntrinsics=false)
Lowers all intrinsics in a module. Returns number converted or failure.
llvm::DenseMap< StringAttr, std::unique_ptr< IntrinsicConverter > > ConversionMapTy
MLIRContext * context
Reference to the MLIR context.
ConversionMapTy conversions
Mapping from intrinsic names to converters.
A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc, Twine clazz, Twine path=Twine())
Implements the same behavior as DictionaryAttr::getAs<A> to return the value of a specific type assoc...
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Attribute convertJSONToAttribute(MLIRContext *context, llvm::json::Value &value, llvm::json::Path p)
Convert arbitrary JSON to an MLIR Attribute.
Definition seq.py:1
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const override
Helper class for checking and extracting information from the generic instrinsic op.
ParseResult sizedInput(unsigned n, int32_t size)
mlir::TypedValue< BundleType > getOutputBundle()
T getParamValue(StringRef name)
Get parameter value by name, if present, as requested type.
ParseResult hasResetInput(unsigned n)
ParseResult typedInput(unsigned n)
ParseResult hasNOutputElements(unsigned n)
ParseResult namedIntParam(StringRef paramName, bool optional=false)
ParseResult namedParam(StringRef paramName, bool optional=false)
ParseResult sizedOutput(int32_t size)
ParseResult sizedOutputElement(unsigned n, StringRef name, int32_t size)
ParseResult hasNParam(unsigned n, unsigned c=0)
ParseResult hasOutputElement(unsigned n, StringRef name)
ParseResult hasNInputs(unsigned n, unsigned c=0)
A dialect interface to provide lowering conversions.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const