CIRCT 23.0.0git
Loading...
Searching...
No Matches
HWOps.cpp
Go to the documentation of this file.
1//===- HWOps.cpp - Implement the HW operations ----------------------------===//
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 HW ops.
10//
11//===----------------------------------------------------------------------===//
12
23#include "mlir/IR/Builders.h"
24#include "mlir/IR/Matchers.h"
25#include "mlir/IR/PatternMatch.h"
26#include "mlir/Interfaces/FunctionImplementation.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringSet.h"
30
31using namespace circt;
32using namespace hw;
33using mlir::TypedAttr;
34
35/// Flip a port direction.
37 switch (direction) {
38 case ModulePort::Direction::Input:
39 return ModulePort::Direction::Output;
40 case ModulePort::Direction::Output:
41 return ModulePort::Direction::Input;
42 case ModulePort::Direction::InOut:
43 return ModulePort::Direction::InOut;
44 }
45 llvm_unreachable("unknown PortDirection");
46}
47
48bool hw::isValidIndexBitWidth(Value index, Value array) {
49 hw::ArrayType arrayType =
50 dyn_cast<hw::ArrayType>(hw::getCanonicalType(array.getType()));
51 assert(arrayType && "expected array type");
52 unsigned indexWidth = index.getType().getIntOrFloatBitWidth();
53 auto requiredWidth = llvm::Log2_64_Ceil(arrayType.getNumElements());
54 return requiredWidth == 0 ? (indexWidth == 0 || indexWidth == 1)
55 : indexWidth == requiredWidth;
56}
57
58/// Return true if the specified operation is a combinational logic op.
59bool hw::isCombinational(Operation *op) {
60 struct IsCombClassifier : public TypeOpVisitor<IsCombClassifier, bool> {
61 bool visitInvalidTypeOp(Operation *op) { return false; }
62 bool visitUnhandledTypeOp(Operation *op) { return true; }
63 };
64
65 return (op->getDialect() && op->getDialect()->getNamespace() == "comb") ||
66 IsCombClassifier().dispatchTypeOpVisitor(op);
67}
68
69static Value foldStructExtract(Operation *inputOp, uint32_t fieldIndex) {
70 // A struct extract of a struct create -> corresponding struct create operand.
71 if (auto structCreate = dyn_cast_or_null<StructCreateOp>(inputOp)) {
72 return structCreate.getOperand(fieldIndex);
73 }
74
75 // Extracting injected field -> corresponding field
76 if (auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
77 if (structInject.getFieldIndex() != fieldIndex)
78 return {};
79 return structInject.getNewValue();
80 }
81 return {};
82}
83
84static ArrayAttr arrayOrEmpty(mlir::MLIRContext *context,
85 ArrayRef<Attribute> attrs) {
86 if (attrs.empty())
87 return ArrayAttr::get(context, {});
88 bool empty = true;
89 for (auto a : attrs)
90 if (a && !cast<DictionaryAttr>(a).empty()) {
91 empty = false;
92 break;
93 }
94 if (empty)
95 return ArrayAttr::get(context, {});
96 return ArrayAttr::get(context, attrs);
97}
98
99/// Get a special name to use when printing the entry block arguments of the
100/// region contained by an operation in this dialect.
101static void getAsmBlockArgumentNamesImpl(mlir::Region &region,
102 OpAsmSetValueNameFn setNameFn) {
103 if (region.empty())
104 return;
105 // Assign port names to the bbargs.
106 auto module = cast<HWModuleOp>(region.getParentOp());
107
108 auto *block = &region.front();
109 for (size_t i = 0, e = block->getNumArguments(); i != e; ++i) {
110 auto name = module.getInputName(i);
111 // Let mlir deterministically convert names to valid identifiers
112 setNameFn(block->getArgument(i), name);
113 }
114}
115
116enum class Delimiter {
117 None,
118 Paren, // () enclosed list
119 OptionalLessGreater, // <> enclosed list or absent
120};
121
122/// Check parameter specified by `value` to see if it is valid according to the
123/// module's parameters. If not, emit an error to the diagnostic provided as an
124/// argument to the lambda 'instanceError' and return failure, otherwise return
125/// success.
126///
127/// If `disallowParamRefs` is true, then parameter references are not allowed.
128LogicalResult hw::checkParameterInContext(
129 Attribute value, ArrayAttr moduleParameters,
130 const instance_like_impl::EmitErrorFn &instanceError,
131 bool disallowParamRefs) {
132 // Literals are always ok. Their types are already known to match
133 // expectations.
134 if (isa<IntegerAttr>(value) || isa<FloatAttr>(value) ||
135 isa<StringAttr>(value) || isa<ParamVerbatimAttr>(value))
136 return success();
137
138 // Check both subexpressions of an expression.
139 if (auto expr = dyn_cast<ParamExprAttr>(value)) {
140 for (auto op : expr.getOperands())
141 if (failed(checkParameterInContext(op, moduleParameters, instanceError,
142 disallowParamRefs)))
143 return failure();
144 return success();
145 }
146
147 // Parameter references need more analysis to make sure they are valid within
148 // this module.
149 if (auto parameterRef = dyn_cast<ParamDeclRefAttr>(value)) {
150 auto nameAttr = parameterRef.getName();
151
152 // Don't allow references to parameters from the default values of a
153 // parameter list.
154 if (disallowParamRefs) {
155 instanceError([&](auto &diag) {
156 diag << "parameter " << nameAttr
157 << " cannot be used as a default value for a parameter";
158 return false;
159 });
160 return failure();
161 }
162
163 // Find the corresponding attribute in the module.
164 for (auto param : moduleParameters) {
165 auto paramAttr = cast<ParamDeclAttr>(param);
166 if (paramAttr.getName() != nameAttr)
167 continue;
168
169 // If the types match then the reference is ok.
170 if (paramAttr.getType() == parameterRef.getType())
171 return success();
172
173 instanceError([&](auto &diag) {
174 diag << "parameter " << nameAttr << " used with type "
175 << parameterRef.getType() << "; should have type "
176 << paramAttr.getType();
177 return true;
178 });
179 return failure();
180 }
181
182 instanceError([&](auto &diag) {
183 diag << "use of unknown parameter " << nameAttr;
184 return true;
185 });
186 return failure();
187 }
188
189 instanceError([&](auto &diag) {
190 diag << "invalid parameter value " << value;
191 return false;
192 });
193 return failure();
194}
195
196/// Check parameter specified by `value` to see if it is valid within the scope
197/// of the specified module `module`. If not, emit an error at the location of
198/// `usingOp` and return failure, otherwise return success. If `usingOp` is
199/// null, then no diagnostic is generated.
200///
201/// If `disallowParamRefs` is true, then parameter references are not allowed.
202LogicalResult hw::checkParameterInContext(Attribute value, Operation *module,
203 Operation *usingOp,
204 bool disallowParamRefs) {
206 [&](const std::function<bool(InFlightDiagnostic &)> &fn) {
207 if (usingOp) {
208 auto diag = usingOp->emitOpError();
209 if (fn(diag))
210 diag.attachNote(module->getLoc()) << "module declared here";
211 }
212 };
213
214 return checkParameterInContext(value,
215 module->getAttrOfType<ArrayAttr>("parameters"),
216 emitError, disallowParamRefs);
217}
218
219/// Return true if the specified attribute tree is made up of nodes that are
220/// valid in a parameter expression.
221bool hw::isValidParameterExpression(Attribute attr, Operation *module) {
222 return succeeded(checkParameterInContext(attr, module, nullptr, false));
223}
224
226 const ModulePortInfo &info,
227 Region &bodyRegion)
228 : info(info) {
229 inputArgs.resize(info.sizeInputs());
230 for (auto [i, barg] : llvm::enumerate(bodyRegion.getArguments())) {
231 inputIdx[info.at(i).name.str()] = i;
232 inputArgs[i] = barg;
233 }
234
236 for (auto [i, outputInfo] : llvm::enumerate(info.getOutputs())) {
237 outputIdx[outputInfo.name.str()] = i;
238 }
239}
240
241void HWModulePortAccessor::setOutput(unsigned i, Value v) {
242 assert(outputOperands.size() > i && "invalid output index");
243 assert(outputOperands[i] == Value() && "output already set");
244 outputOperands[i] = v;
245}
246
248 assert(inputArgs.size() > i && "invalid input index");
249 return inputArgs[i];
250}
251Value HWModulePortAccessor::getInput(StringRef name) {
252 return getInput(inputIdx.find(name.str())->second);
253}
254void HWModulePortAccessor::setOutput(StringRef name, Value v) {
255 setOutput(outputIdx.find(name.str())->second, v);
256}
257
258//===----------------------------------------------------------------------===//
259// Declarative Canonicalization Patterns
260//===----------------------------------------------------------------------===//
261
262namespace {
263#include "circt/Dialect/HW/HWCanonicalization.cpp.inc"
264} // namespace
265
266//===----------------------------------------------------------------------===//
267// ConstantOp
268//===----------------------------------------------------------------------===//
269
270void ConstantOp::print(OpAsmPrinter &p) {
271 p << " ";
272 p.printAttribute(getValueAttr());
273 p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{"value"});
274}
275
276ParseResult ConstantOp::parse(OpAsmParser &parser, OperationState &result) {
277 IntegerAttr valueAttr;
278
279 if (parser.parseAttribute(valueAttr, "value", result.attributes) ||
280 parser.parseOptionalAttrDict(result.attributes))
281 return failure();
282
283 result.addTypes(valueAttr.getType());
284 return success();
285}
286
287LogicalResult ConstantOp::verify() {
288 // If the result type has a bitwidth, then the attribute must match its width.
289 if (getValue().getBitWidth() != cast<IntegerType>(getType()).getWidth())
290 return emitError(
291 "hw.constant attribute bitwidth doesn't match return type");
292
293 return success();
294}
295
296/// Build a ConstantOp from an APInt, infering the result type from the
297/// width of the APInt.
298void ConstantOp::build(OpBuilder &builder, OperationState &result,
299 const APInt &value) {
300
301 auto type = IntegerType::get(builder.getContext(), value.getBitWidth());
302 auto attr = builder.getIntegerAttr(type, value);
303 return build(builder, result, type, attr);
304}
305
306/// Build a ConstantOp from an APInt, infering the result type from the
307/// width of the APInt.
308void ConstantOp::build(OpBuilder &builder, OperationState &result,
309 IntegerAttr value) {
310 return build(builder, result, value.getType(), value);
311}
312
313/// This builder allows construction of small signed integers like 0, 1, -1
314/// matching a specified MLIR IntegerType. This shouldn't be used for general
315/// constant folding because it only works with values that can be expressed in
316/// an int64_t. Use APInt's instead.
317void ConstantOp::build(OpBuilder &builder, OperationState &result, Type type,
318 int64_t value) {
319 auto numBits = cast<IntegerType>(type).getWidth();
320 build(builder, result,
321 APInt(numBits, (uint64_t)value, /*isSigned=*/true,
322 /*implicitTrunc=*/true));
323}
324
325void ConstantOp::getAsmResultNames(
326 function_ref<void(Value, StringRef)> setNameFn) {
327 auto intTy = getType();
328 auto intCst = getValue();
329
330 // Sugar i1 constants with 'true' and 'false'.
331 if (cast<IntegerType>(intTy).getWidth() == 1)
332 return setNameFn(getResult(), intCst.isZero() ? "false" : "true");
333
334 // Otherwise, build a complex name with the value and type.
335 SmallVector<char, 32> specialNameBuffer;
336 llvm::raw_svector_ostream specialName(specialNameBuffer);
337 specialName << 'c' << intCst << '_' << intTy;
338 setNameFn(getResult(), specialName.str());
339}
340
341OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) {
342 assert(adaptor.getOperands().empty() && "constant has no operands");
343 return getValueAttr();
344}
345
346//===----------------------------------------------------------------------===//
347// WireOp
348//===----------------------------------------------------------------------===//
349
350/// Check whether an operation has any additional attributes set beyond its
351/// standard list of attributes returned by `getAttributeNames`.
352template <class Op>
353static bool hasAdditionalAttributes(Op op,
354 ArrayRef<StringRef> ignoredAttrs = {}) {
355 auto names = op.getAttributeNames();
356 llvm::SmallDenseSet<StringRef> nameSet;
357 nameSet.reserve(names.size() + ignoredAttrs.size());
358 nameSet.insert(names.begin(), names.end());
359 nameSet.insert(ignoredAttrs.begin(), ignoredAttrs.end());
360 return llvm::any_of(op->getAttrs(), [&](auto namedAttr) {
361 return !nameSet.contains(namedAttr.getName());
362 });
363}
364
365void WireOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
366 // If the wire has an optional 'name' attribute, use it.
367 auto nameAttr = (*this)->getAttrOfType<StringAttr>("name");
368 if (nameAttr && !nameAttr.getValue().empty())
369 setNameFn(getResult(), nameAttr.getValue());
370}
371
372std::optional<size_t> WireOp::getTargetResultIndex() { return 0; }
373
374OpFoldResult WireOp::fold(FoldAdaptor adaptor) {
375 // If the wire has no additional attributes, no name, and no symbol, just
376 // forward its input.
377 if (!hasAdditionalAttributes(*this, {"sv.namehint"}) && !getNameAttr() &&
378 !getInnerSymAttr())
379 return getInput();
380 return {};
381}
382
383LogicalResult WireOp::canonicalize(WireOp wire, PatternRewriter &rewriter) {
384 // Block if the wire has any attributes.
385 if (hasAdditionalAttributes(wire, {"sv.namehint"}))
386 return failure();
387
388 // If the wire has a symbol, then we can't delete it.
389 if (wire.getInnerSymAttr())
390 return failure();
391
392 // If the wire has a name or an `sv.namehint` attribute, propagate it as an
393 // `sv.namehint` to the expression.
394 if (auto *inputOp = wire.getInput().getDefiningOp())
395 if (auto name = chooseName(wire, inputOp))
396 rewriter.modifyOpInPlace(inputOp,
397 [&] { inputOp->setAttr("sv.namehint", name); });
398
399 rewriter.replaceOp(wire, wire.getInput());
400 return success();
401}
402
403//===----------------------------------------------------------------------===//
404// AggregateConstantOp
405//===----------------------------------------------------------------------===//
406
407static LogicalResult checkAttributes(Operation *op, Attribute attr, Type type) {
408 // If this is a type alias, get the underlying type.
409 if (auto typeAlias = dyn_cast<TypeAliasType>(type))
410 type = typeAlias.getCanonicalType();
411
412 if (auto structType = dyn_cast<StructType>(type)) {
413 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
414 if (!arrayAttr)
415 return op->emitOpError("expected array attribute for constant of type ")
416 << type;
417 if (structType.getElements().size() != arrayAttr.size())
418 return op->emitOpError("array attribute (")
419 << arrayAttr.size() << ") has wrong size for struct constant ("
420 << structType.getElements().size() << ")";
421
422 for (auto [attr, fieldInfo] :
423 llvm::zip(arrayAttr.getValue(), structType.getElements())) {
424 if (failed(checkAttributes(op, attr, fieldInfo.type)))
425 return failure();
426 }
427 } else if (auto arrayType = dyn_cast<ArrayType>(type)) {
428 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
429 if (!arrayAttr)
430 return op->emitOpError("expected array attribute for constant of type ")
431 << type;
432 if (arrayType.getNumElements() != arrayAttr.size())
433 return op->emitOpError("array attribute (")
434 << arrayAttr.size() << ") has wrong size for array constant ("
435 << arrayType.getNumElements() << ")";
436
437 auto elementType = arrayType.getElementType();
438 for (auto attr : arrayAttr.getValue()) {
439 if (failed(checkAttributes(op, attr, elementType)))
440 return failure();
441 }
442 } else if (auto arrayType = dyn_cast<UnpackedArrayType>(type)) {
443 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
444 if (!arrayAttr)
445 return op->emitOpError("expected array attribute for constant of type ")
446 << type;
447 auto elementType = arrayType.getElementType();
448 if (arrayType.getNumElements() != arrayAttr.size())
449 return op->emitOpError("array attribute (")
450 << arrayAttr.size()
451 << ") has wrong size for unpacked array constant ("
452 << arrayType.getNumElements() << ")";
453
454 for (auto attr : arrayAttr.getValue()) {
455 if (failed(checkAttributes(op, attr, elementType)))
456 return failure();
457 }
458 } else if (auto enumType = dyn_cast<EnumType>(type)) {
459 auto stringAttr = dyn_cast<StringAttr>(attr);
460 if (!stringAttr)
461 return op->emitOpError("expected string attribute for constant of type ")
462 << type;
463 } else if (auto intType = dyn_cast<IntegerType>(type)) {
464 // Check the attribute kind is correct.
465 auto intAttr = dyn_cast<IntegerAttr>(attr);
466 if (!intAttr)
467 return op->emitOpError("expected integer attribute for constant of type ")
468 << type;
469 // Check the bitwidth is correct.
470 if (intAttr.getValue().getBitWidth() != intType.getWidth())
471 return op->emitOpError("hw.constant attribute bitwidth "
472 "doesn't match return type");
473 } else if (auto typedAttr = dyn_cast<TypedAttr>(attr)) {
474 if (typedAttr.getType() != type)
475 return op->emitOpError("typed attr doesn't match the return type ")
476 << type;
477 } else {
478 return op->emitOpError("unknown element type ") << type;
479 }
480 return success();
481}
482
483LogicalResult AggregateConstantOp::verify() {
484 return checkAttributes(*this, getFieldsAttr(), getType());
485}
486
487OpFoldResult AggregateConstantOp::fold(FoldAdaptor) { return getFieldsAttr(); }
488
489//===----------------------------------------------------------------------===//
490// ParamValueOp
491//===----------------------------------------------------------------------===//
492
493static ParseResult parseParamValue(OpAsmParser &p, Attribute &value,
494 Type &resultType) {
495 if (p.parseType(resultType) || p.parseEqual() ||
496 p.parseAttribute(value, resultType))
497 return failure();
498 return success();
499}
500
501static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value,
502 Type resultType) {
503 p << resultType << " = ";
504 p.printAttributeWithoutType(value);
505}
506
507LogicalResult ParamValueOp::verify() {
508 // Check that the attribute expression is valid in this module.
510 getValue(), (*this)->getParentOfType<hw::HWModuleOp>(), *this);
511}
512
513OpFoldResult ParamValueOp::fold(FoldAdaptor adaptor) {
514 assert(adaptor.getOperands().empty() && "hw.param.value has no operands");
515 return getValueAttr();
516}
517
518//===----------------------------------------------------------------------===//
519// HWModuleOp
520//===----------------------------------------------------------------------===/
521
522/// Return true if isAnyModule or instance.
523bool hw::isAnyModuleOrInstance(Operation *moduleOrInstance) {
524 return isa<HWModuleLike, InstanceOp>(moduleOrInstance);
525}
526
527/// Return the signature for a module as a function type from the module itself
528/// or from an hw::InstanceOp.
529FunctionType hw::getModuleType(Operation *moduleOrInstance) {
530 return TypeSwitch<Operation *, FunctionType>(moduleOrInstance)
531 .Case<InstanceOp>([](auto instance) {
532 SmallVector<Type> inputs(instance->getOperandTypes());
533 SmallVector<Type> results(instance->getResultTypes());
534 return FunctionType::get(instance->getContext(), inputs, results);
535 })
536 .Case<HWModuleLike>(
537 [](auto mod) { return mod.getHWModuleType().getFuncType(); })
538 .Default([](Operation *op) {
539 return cast<FunctionType>(
540 cast<mlir::FunctionOpInterface>(op).getFunctionType());
541 });
542}
543
544/// Return the name to use for the Verilog module that we're referencing
545/// here. This is typically the symbol, but can be overridden with the
546/// verilogName attribute.
547StringAttr hw::getVerilogModuleNameAttr(Operation *module) {
548 auto nameAttr = module->getAttrOfType<StringAttr>("verilogName");
549 if (nameAttr)
550 return nameAttr;
551
552 return module->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
553}
554
555template <typename ModuleTy>
556static void
557buildModule(OpBuilder &builder, OperationState &result, StringAttr name,
558 const ModulePortInfo &ports, ArrayAttr parameters,
559 ArrayRef<NamedAttribute> attributes, StringAttr comment) {
560 using namespace mlir::function_interface_impl;
561
562 // Add an attribute for the name.
563 result.addAttribute(SymbolTable::getSymbolAttrName(), name);
564
565 SmallVector<Attribute> perPortAttrs;
566 SmallVector<ModulePort> portTypes;
567
568 for (auto elt : ports) {
569 portTypes.push_back(elt);
570 llvm::SmallVector<NamedAttribute> portAttrs;
571 if (elt.attrs)
572 llvm::copy(elt.attrs, std::back_inserter(portAttrs));
573 perPortAttrs.push_back(builder.getDictionaryAttr(portAttrs));
574 }
575
576 // Allow clients to pass in null for the parameters list.
577 if (!parameters)
578 parameters = builder.getArrayAttr({});
579
580 // Record the argument and result types as an attribute.
581 auto type = ModuleType::get(builder.getContext(), portTypes);
582 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name),
583 TypeAttr::get(type));
584 result.addAttribute("per_port_attrs",
585 arrayOrEmpty(builder.getContext(), perPortAttrs));
586 result.addAttribute("parameters", parameters);
587 if (!comment)
588 comment = builder.getStringAttr("");
589 result.addAttribute("comment", comment);
590 result.addAttributes(attributes);
591 result.addRegion();
592}
593
594/// Internal implementation of argument/result insertion and removal on modules.
596 MLIRContext *context, ArrayRef<std::pair<unsigned, PortInfo>> insertArgs,
597 ArrayRef<unsigned> removeArgs, ArrayRef<Attribute> oldArgNames,
598 ArrayRef<Type> oldArgTypes, ArrayRef<Attribute> oldArgAttrs,
599 ArrayRef<Location> oldArgLocs, SmallVector<Attribute> &newArgNames,
600 SmallVector<Type> &newArgTypes, SmallVector<Attribute> &newArgAttrs,
601 SmallVector<Location> &newArgLocs, Block *body = nullptr) {
602
603#ifndef NDEBUG
604 // Check that the `insertArgs` and `removeArgs` indices are in ascending
605 // order.
606 assert(llvm::is_sorted(insertArgs,
607 [](auto &a, auto &b) { return a.first < b.first; }) &&
608 "insertArgs must be in ascending order");
609 assert(llvm::is_sorted(removeArgs, [](auto &a, auto &b) { return a < b; }) &&
610 "removeArgs must be in ascending order");
611#endif
612
613 auto oldArgCount = oldArgTypes.size();
614 auto newArgCount = oldArgCount + insertArgs.size() - removeArgs.size();
615 assert((int)newArgCount >= 0);
616
617 newArgNames.reserve(newArgCount);
618 newArgTypes.reserve(newArgCount);
619 newArgAttrs.reserve(newArgCount);
620 newArgLocs.reserve(newArgCount);
621
622 auto exportPortAttrName = StringAttr::get(context, "hw.exportPort");
623 auto emptyDictAttr = DictionaryAttr::get(context, {});
624 auto unknownLoc = UnknownLoc::get(context);
625
626 BitVector erasedIndices;
627 if (body)
628 erasedIndices.resize(oldArgCount + insertArgs.size());
629
630 for (unsigned argIdx = 0, idx = 0; argIdx <= oldArgCount; ++argIdx, ++idx) {
631 // Insert new ports at this position.
632 while (!insertArgs.empty() && insertArgs[0].first == argIdx) {
633 auto port = insertArgs[0].second;
634 if (port.dir == ModulePort::Direction::InOut &&
635 !isa<InOutType>(port.type))
636 port.type = InOutType::get(port.type);
637 auto sym = port.getSym();
638 Attribute attr =
639 (sym && !sym.empty())
640 ? DictionaryAttr::get(context, {{exportPortAttrName, sym}})
641 : emptyDictAttr;
642 newArgNames.push_back(port.name);
643 newArgTypes.push_back(port.type);
644 newArgAttrs.push_back(attr);
645 insertArgs = insertArgs.drop_front();
646 LocationAttr loc = port.loc ? port.loc : unknownLoc;
647 newArgLocs.push_back(loc);
648 if (body)
649 body->insertArgument(idx++, port.type, loc);
650 }
651 if (argIdx == oldArgCount)
652 break;
653
654 // Migrate the old port at this position.
655 bool removed = false;
656 while (!removeArgs.empty() && removeArgs[0] == argIdx) {
657 removeArgs = removeArgs.drop_front();
658 removed = true;
659 }
660
661 if (removed) {
662 if (body)
663 erasedIndices.set(idx);
664 } else {
665 newArgNames.push_back(oldArgNames[argIdx]);
666 newArgTypes.push_back(oldArgTypes[argIdx]);
667 newArgAttrs.push_back(oldArgAttrs.empty() ? emptyDictAttr
668 : oldArgAttrs[argIdx]);
669 newArgLocs.push_back(oldArgLocs[argIdx]);
670 }
671 }
672
673 if (body)
674 body->eraseArguments(erasedIndices);
675
676 assert(newArgNames.size() == newArgCount);
677 assert(newArgTypes.size() == newArgCount);
678 assert(newArgAttrs.size() == newArgCount);
679 assert(newArgLocs.size() == newArgCount);
680}
681
682/// Insert and remove ports of a module. The insertion and removal indices must
683/// be in ascending order. The indices refer to the port positions before any
684/// insertion or removal occurs. Ports inserted at the same index will appear in
685/// the module in the same order as they were listed in the `insert*` array.
686///
687/// The operation must be any of the module-like operations.
688///
689/// This is marked deprecated as it's only used from HandshakeToHW and
690/// PortConverter and is likely broken and not currently tested. Users of this
691/// are still written dealing with input and output ports separately, which is
692/// an old and broken style.
693[[deprecated]] static void
694modifyModulePorts(Operation *op,
695 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
696 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
697 ArrayRef<unsigned> removeInputs,
698 ArrayRef<unsigned> removeOutputs, Block *body = nullptr) {
699 auto moduleOp = cast<HWModuleLike>(op);
700 auto *context = moduleOp.getContext();
701
702 // Dig up the old argument and result data.
703 auto oldArgNames = moduleOp.getInputNames();
704 auto oldArgTypes = moduleOp.getInputTypes();
705 auto oldArgAttrs = moduleOp.getAllInputAttrs();
706 auto oldArgLocs = moduleOp.getInputLocs();
707
708 auto oldResultNames = moduleOp.getOutputNames();
709 auto oldResultTypes = moduleOp.getOutputTypes();
710 auto oldResultAttrs = moduleOp.getAllOutputAttrs();
711 auto oldResultLocs = moduleOp.getOutputLocs();
712
713 // Modify the ports.
714 SmallVector<Attribute> newArgNames, newResultNames;
715 SmallVector<Type> newArgTypes, newResultTypes;
716 SmallVector<Attribute> newArgAttrs, newResultAttrs;
717 SmallVector<Location> newArgLocs, newResultLocs;
718
719 modifyModuleArgs(context, insertInputs, removeInputs, oldArgNames,
720 oldArgTypes, oldArgAttrs, oldArgLocs, newArgNames,
721 newArgTypes, newArgAttrs, newArgLocs, body);
722
723 modifyModuleArgs(context, insertOutputs, removeOutputs, oldResultNames,
724 oldResultTypes, oldResultAttrs, oldResultLocs,
725 newResultNames, newResultTypes, newResultAttrs,
726 newResultLocs);
727
728 // Update the module operation types and attributes.
729 auto fnty = FunctionType::get(context, newArgTypes, newResultTypes);
730 auto modty = detail::fnToMod(fnty, newArgNames, newResultNames);
731 moduleOp.setHWModuleType(modty);
732 moduleOp.setAllInputAttrs(newArgAttrs);
733 moduleOp.setAllOutputAttrs(newResultAttrs);
734
735 newArgLocs.append(newResultLocs.begin(), newResultLocs.end());
736 moduleOp.setAllPortLocs(newArgLocs);
737}
738
739void HWModuleOp::build(OpBuilder &builder, OperationState &result,
740 StringAttr name, const ModulePortInfo &ports,
741 ArrayAttr parameters,
742 ArrayRef<NamedAttribute> attributes, StringAttr comment,
743 bool shouldEnsureTerminator) {
744 buildModule<HWModuleOp>(builder, result, name, ports, parameters, attributes,
745 comment);
746
747 // Create a region and a block for the body.
748 auto *bodyRegion = result.regions[0].get();
749 Block *body = new Block();
750 bodyRegion->push_back(body);
751
752 // Add arguments to the body block.
753 auto unknownLoc = builder.getUnknownLoc();
754 for (auto port : ports.getInputs()) {
755 auto loc = port.loc ? Location(port.loc) : unknownLoc;
756 auto type = port.type;
757 if (port.isInOut() && !isa<InOutType>(type))
758 type = InOutType::get(type);
759 body->addArgument(type, loc);
760 }
761
762 // Add result ports attribute.
763 auto unknownLocAttr = cast<LocationAttr>(unknownLoc);
764 SmallVector<Attribute> resultLocs;
765 for (auto port : ports.getOutputs())
766 resultLocs.push_back(port.loc ? port.loc : unknownLocAttr);
767 result.addAttribute("result_locs", builder.getArrayAttr(resultLocs));
768
769 if (shouldEnsureTerminator)
770 HWModuleOp::ensureTerminator(*bodyRegion, builder, result.location);
771}
772
773void HWModuleOp::build(OpBuilder &builder, OperationState &result,
774 StringAttr name, ArrayRef<PortInfo> ports,
775 ArrayAttr parameters,
776 ArrayRef<NamedAttribute> attributes,
777 StringAttr comment) {
778 build(builder, result, name, ModulePortInfo(ports), parameters, attributes,
779 comment);
780}
781
782void HWModuleOp::build(OpBuilder &builder, OperationState &odsState,
783 StringAttr name, const ModulePortInfo &ports,
784 HWModuleBuilder modBuilder, ArrayAttr parameters,
785 ArrayRef<NamedAttribute> attributes,
786 StringAttr comment) {
787 build(builder, odsState, name, ports, parameters, attributes, comment,
788 /*shouldEnsureTerminator=*/false);
789 auto *bodyRegion = odsState.regions[0].get();
790 OpBuilder::InsertionGuard guard(builder);
791 auto accessor = HWModulePortAccessor(odsState.location, ports, *bodyRegion);
792 builder.setInsertionPointToEnd(&bodyRegion->front());
793 modBuilder(builder, accessor);
794 // Create output operands.
795 llvm::SmallVector<Value> outputOperands = accessor.getOutputOperands();
796 hw::OutputOp::create(builder, odsState.location, outputOperands);
797}
798
799void HWModuleOp::modifyPorts(
800 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
801 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
802 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
803 modifyModulePorts(*this, insertInputs, insertOutputs, eraseInputs,
804 eraseOutputs);
805}
806
807/// Return the name to use for the Verilog module that we're referencing
808/// here. This is typically the symbol, but can be overridden with the
809/// verilogName attribute.
810StringAttr HWModuleExternOp::getVerilogModuleNameAttr() {
811 if (auto vName = getVerilogNameAttr())
812 return vName;
813
814 return (*this)->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
815}
816
817StringAttr HWModuleGeneratedOp::getVerilogModuleNameAttr() {
818 if (auto vName = getVerilogNameAttr()) {
819 return vName;
820 }
821 return (*this)->getAttrOfType<StringAttr>(
822 ::mlir::SymbolTable::getSymbolAttrName());
823}
824
825void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
826 StringAttr name, const ModulePortInfo &ports,
827 StringRef verilogName, ArrayAttr parameters,
828 ArrayRef<NamedAttribute> attributes) {
829 buildModule<HWModuleExternOp>(builder, result, name, ports, parameters,
830 attributes, {});
831
832 // Add the port locations.
833 LocationAttr unknownLoc = builder.getUnknownLoc();
834 SmallVector<Attribute> portLocs;
835 for (auto elt : ports)
836 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
837 result.addAttribute("port_locs", builder.getArrayAttr(portLocs));
838
839 if (!verilogName.empty())
840 result.addAttribute("verilogName", builder.getStringAttr(verilogName));
841}
842
843void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
844 StringAttr name, ArrayRef<PortInfo> ports,
845 StringRef verilogName, ArrayAttr parameters,
846 ArrayRef<NamedAttribute> attributes) {
847 build(builder, result, name, ModulePortInfo(ports), verilogName, parameters,
848 attributes);
849}
850
851void HWModuleExternOp::modifyPorts(
852 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
853 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
854 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
855 modifyModulePorts(*this, insertInputs, insertOutputs, eraseInputs,
856 eraseOutputs);
857}
858
859void HWModuleExternOp::appendOutputs(
860 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
861
862void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
863 FlatSymbolRefAttr genKind, StringAttr name,
864 const ModulePortInfo &ports,
865 StringRef verilogName, ArrayAttr parameters,
866 ArrayRef<NamedAttribute> attributes) {
867 buildModule<HWModuleGeneratedOp>(builder, result, name, ports, parameters,
868 attributes, {});
869 // Add the port locations.
870 LocationAttr unknownLoc = builder.getUnknownLoc();
871 SmallVector<Attribute> portLocs;
872 for (auto elt : ports)
873 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
874 result.addAttribute("port_locs", builder.getArrayAttr(portLocs));
875
876 result.addAttribute("generatorKind", genKind);
877 if (!verilogName.empty())
878 result.addAttribute("verilogName", builder.getStringAttr(verilogName));
879}
880
881void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
882 FlatSymbolRefAttr genKind, StringAttr name,
883 ArrayRef<PortInfo> ports, StringRef verilogName,
884 ArrayAttr parameters,
885 ArrayRef<NamedAttribute> attributes) {
886 build(builder, result, genKind, name, ModulePortInfo(ports), verilogName,
887 parameters, attributes);
888}
889
890void HWModuleGeneratedOp::modifyPorts(
891 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
892 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
893 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
894 modifyModulePorts(*this, insertInputs, insertOutputs, eraseInputs,
895 eraseOutputs);
896}
897
898void HWModuleGeneratedOp::appendOutputs(
899 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
900
901static bool hasAttribute(StringRef name, ArrayRef<NamedAttribute> attrs) {
902 for (auto &argAttr : attrs)
903 if (argAttr.getName() == name)
904 return true;
905 return false;
906}
907
908template <typename ModuleTy>
909static ParseResult parseHWModuleOp(OpAsmParser &parser,
910 OperationState &result) {
911
912 using namespace mlir::function_interface_impl;
913 auto builder = parser.getBuilder();
914 auto loc = parser.getCurrentLocation();
915
916 // Parse the visibility attribute.
917 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
918
919 // Parse the name as a symbol.
920 StringAttr nameAttr;
921 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
922 result.attributes))
923 return failure();
924
925 // Parse the generator information.
926 FlatSymbolRefAttr kindAttr;
927 if constexpr (std::is_same_v<ModuleTy, HWModuleGeneratedOp>) {
928 if (parser.parseComma() ||
929 parser.parseAttribute(kindAttr, "generatorKind", result.attributes)) {
930 return failure();
931 }
932 }
933
934 // Parse the parameters.
935 ArrayAttr parameters;
936 if (parseOptionalParameterList(parser, parameters))
937 return failure();
938
939 SmallVector<module_like_impl::PortParse> ports;
940 TypeAttr modType;
941 if (failed(module_like_impl::parseModuleSignature(parser, ports, modType)))
942 return failure();
943
944 // Parse the attribute dict.
945 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
946 return failure();
947
948 if (hasAttribute("parameters", result.attributes)) {
949 parser.emitError(loc, "explicit `parameters` attributes not allowed");
950 return failure();
951 }
952
953 result.addAttribute("parameters", parameters);
954 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name), modType);
955
956 // Convert the specified array of dictionary attrs (which may have null
957 // entries) to an ArrayAttr of dictionaries.
958 SmallVector<Attribute> attrs;
959 for (auto &port : ports)
960 attrs.push_back(port.attrs ? port.attrs : builder.getDictionaryAttr({}));
961 // Add the attributes to the ports.
962 auto nonEmptyAttrsFn = [](Attribute attr) {
963 return attr && !cast<DictionaryAttr>(attr).empty();
964 };
965 if (llvm::any_of(attrs, nonEmptyAttrsFn))
966 result.addAttribute(ModuleTy::getPerPortAttrsAttrName(result.name),
967 builder.getArrayAttr(attrs));
968
969 // Add the port locations.
970 auto unknownLoc = builder.getUnknownLoc();
971 auto nonEmptyLocsFn = [unknownLoc](Attribute attr) {
972 return attr && cast<Location>(attr) != unknownLoc;
973 };
974 SmallVector<Attribute> locs;
975 StringAttr portLocsAttrName;
976 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>) {
977 // Plain modules only store the output port locations, as the input port
978 // locations will be stored in the basic block arguments.
979 portLocsAttrName = ModuleTy::getResultLocsAttrName(result.name);
980 for (auto &port : ports)
981 if (port.direction == ModulePort::Direction::Output)
982 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
983 } else {
984 // All other modules store all port locations in a single array.
985 portLocsAttrName = ModuleTy::getPortLocsAttrName(result.name);
986 for (auto &port : ports)
987 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
988 }
989 if (llvm::any_of(locs, nonEmptyLocsFn))
990 result.addAttribute(portLocsAttrName, builder.getArrayAttr(locs));
991
992 // Add the entry block arguments.
993 SmallVector<OpAsmParser::Argument, 4> entryArgs;
994 for (auto &port : ports)
995 if (port.direction != ModulePort::Direction::Output)
996 entryArgs.push_back(port);
997
998 // Parse the optional function body.
999 auto *body = result.addRegion();
1000 if (std::is_same_v<ModuleTy, HWModuleOp>) {
1001 if (parser.parseRegion(*body, entryArgs))
1002 return failure();
1003
1004 HWModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1005 }
1006 return success();
1007}
1008
1009ParseResult HWModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1010 return parseHWModuleOp<HWModuleOp>(parser, result);
1011}
1012
1013ParseResult HWModuleExternOp::parse(OpAsmParser &parser,
1014 OperationState &result) {
1015 return parseHWModuleOp<HWModuleExternOp>(parser, result);
1016}
1017
1018ParseResult HWModuleGeneratedOp::parse(OpAsmParser &parser,
1019 OperationState &result) {
1020 return parseHWModuleOp<HWModuleGeneratedOp>(parser, result);
1021}
1022
1023FunctionType getHWModuleOpType(Operation *op) {
1024 if (auto mod = dyn_cast<HWModuleLike>(op))
1025 return mod.getHWModuleType().getFuncType();
1026 return cast<FunctionType>(
1027 cast<mlir::FunctionOpInterface>(op).getFunctionType());
1028}
1029
1030template <typename ModuleTy>
1031static void printModuleOp(OpAsmPrinter &p, ModuleTy mod) {
1032 p << ' ';
1033 // Print the visibility of the module.
1034 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
1035 if (auto visibility = mod.getOperation()->template getAttrOfType<StringAttr>(
1036 visibilityAttrName))
1037 p << visibility.getValue() << ' ';
1038
1039 // Print the operation and the function name.
1040 p.printSymbolName(SymbolTable::getSymbolName(mod.getOperation()).getValue());
1041 if (auto gen = dyn_cast<HWModuleGeneratedOp>(mod.getOperation())) {
1042 p << ", ";
1043 p.printSymbolName(gen.getGeneratorKind());
1044 }
1045
1046 // Print the parameter list if present.
1047 printOptionalParameterList(p, mod.getOperation(), mod.getParameters());
1048
1050
1051 SmallVector<StringRef, 3> omittedAttrs;
1052 if (isa<HWModuleGeneratedOp>(mod.getOperation()))
1053 omittedAttrs.push_back("generatorKind");
1054 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>)
1055 omittedAttrs.push_back(mod.getResultLocsAttrName());
1056 else
1057 omittedAttrs.push_back(mod.getPortLocsAttrName());
1058 omittedAttrs.push_back(mod.getModuleTypeAttrName());
1059 omittedAttrs.push_back(mod.getPerPortAttrsAttrName());
1060 omittedAttrs.push_back(mod.getParametersAttrName());
1061 omittedAttrs.push_back(visibilityAttrName);
1062 if (auto cmt =
1063 mod.getOperation()->template getAttrOfType<StringAttr>("comment"))
1064 if (cmt.getValue().empty())
1065 omittedAttrs.push_back("comment");
1066
1067 mlir::function_interface_impl::printFunctionAttributes(p, mod.getOperation(),
1068 omittedAttrs);
1069}
1070
1071void HWModuleExternOp::print(OpAsmPrinter &p) { printModuleOp(p, *this); }
1072void HWModuleGeneratedOp::print(OpAsmPrinter &p) { printModuleOp(p, *this); }
1073
1074void HWModuleOp::print(OpAsmPrinter &p) {
1075 printModuleOp(p, *this);
1076
1077 // Print the body if this is not an external function.
1078 Region &body = getBody();
1079 if (!body.empty()) {
1080 p << " ";
1081 p.printRegion(body, /*printEntryBlockArgs=*/false,
1082 /*printBlockTerminators=*/true);
1083 }
1084}
1085
1086static LogicalResult verifyModuleCommon(HWModuleLike module) {
1087 assert(isa<HWModuleLike>(module) &&
1088 "verifier hook should only be called on modules");
1089
1090 SmallPtrSet<Attribute, 4> paramNames;
1091
1092 // Check parameter default values are sensible.
1093 for (auto param : module->getAttrOfType<ArrayAttr>("parameters")) {
1094 auto paramAttr = cast<ParamDeclAttr>(param);
1095
1096 // Check that we don't have any redundant parameter names. These are
1097 // resolved by string name: reuse of the same name would cause ambiguities.
1098 if (!paramNames.insert(paramAttr.getName()).second)
1099 return module->emitOpError("parameter ")
1100 << paramAttr << " has the same name as a previous parameter";
1101
1102 // Default values are allowed to be missing, check them if present.
1103 auto value = paramAttr.getValue();
1104 if (!value)
1105 continue;
1106
1107 auto typedValue = dyn_cast<TypedAttr>(value);
1108 if (!typedValue)
1109 return module->emitOpError("parameter ")
1110 << paramAttr << " should have a typed value; has value " << value;
1111
1112 if (typedValue.getType() != paramAttr.getType())
1113 return module->emitOpError("parameter ")
1114 << paramAttr << " should have type " << paramAttr.getType()
1115 << "; has type " << typedValue.getType();
1116
1117 // Verify that this is a valid parameter value, disallowing parameter
1118 // references. We could allow parameters to refer to each other in the
1119 // future with lexical ordering if there is a need.
1120 if (failed(checkParameterInContext(value, module, module,
1121 /*disallowParamRefs=*/true)))
1122 return failure();
1123 }
1124 return success();
1125}
1126
1127LogicalResult HWModuleOp::verify() {
1128 if (failed(verifyModuleCommon(*this)))
1129 return failure();
1130
1131 auto type = getModuleType();
1132 auto *body = getBodyBlock();
1133
1134 // Verify the number of block arguments.
1135 auto numInputs = type.getNumInputs();
1136 if (body->getNumArguments() != numInputs)
1137 return emitOpError("entry block must have ")
1138 << numInputs << " arguments to match module signature";
1139
1140 return success();
1141}
1142
1143LogicalResult HWModuleExternOp::verify() { return verifyModuleCommon(*this); }
1144
1145std::pair<StringAttr, BlockArgument>
1146HWModuleOp::insertInput(unsigned index, StringAttr name, Type ty) {
1147 // Find a unique name for the wire.
1148 Namespace ns;
1149 auto ports = getPortList();
1150 for (auto port : ports)
1151 ns.newName(port.name.getValue());
1152 auto nameAttr = StringAttr::get(getContext(), ns.newName(name.getValue()));
1153
1154 Block *body = getBodyBlock();
1155
1156 // Create a new port for the host clock.
1157 PortInfo port;
1158 port.name = nameAttr;
1160 port.type = ty;
1161 modifyModulePorts(getOperation(), {std::make_pair(index, port)}, {}, {}, {},
1162 body);
1163
1164 // Add a new argument.
1165 return {nameAttr, body->getArgument(index)};
1166}
1167
1168void HWModuleOp::insertOutputs(unsigned index,
1169 ArrayRef<std::pair<StringAttr, Value>> outputs) {
1170
1171 auto output = cast<OutputOp>(getBodyBlock()->getTerminator());
1172 assert(index <= output->getNumOperands() && "invalid output index");
1173
1174 // Rewrite the port list of the module.
1175 SmallVector<std::pair<unsigned, PortInfo>> indexedNewPorts;
1176 for (auto &[name, value] : outputs) {
1177 PortInfo port;
1178 port.name = name;
1180 port.type = value.getType();
1181 indexedNewPorts.emplace_back(index, port);
1182 }
1183 modifyModulePorts(getOperation(), {}, indexedNewPorts, {}, {},
1184 getBodyBlock());
1185
1186 // Rewrite the output op.
1187 for (auto &[name, value] : outputs)
1188 output->insertOperands(index++, value);
1189}
1190
1191void HWModuleOp::appendOutputs(ArrayRef<std::pair<StringAttr, Value>> outputs) {
1192 return insertOutputs(getNumOutputPorts(), outputs);
1193}
1194
1195void HWModuleOp::getAsmBlockArgumentNames(mlir::Region &region,
1196 mlir::OpAsmSetValueNameFn setNameFn) {
1197 getAsmBlockArgumentNamesImpl(region, setNameFn);
1198}
1199
1200void HWModuleExternOp::getAsmBlockArgumentNames(
1201 mlir::Region &region, mlir::OpAsmSetValueNameFn setNameFn) {
1202 getAsmBlockArgumentNamesImpl(region, setNameFn);
1203}
1204
1205template <typename ModTy>
1206static SmallVector<Location> getAllPortLocs(ModTy module) {
1207 auto locs = module.getPortLocs();
1208 if (locs) {
1209 SmallVector<Location> retval;
1210 retval.reserve(locs->size());
1211 for (auto l : *locs)
1212 retval.push_back(cast<Location>(l));
1213 // Either we have a length of 0 or the correct length
1214 assert(!locs->size() || locs->size() == module.getNumPorts());
1215 return retval;
1216 }
1217 return SmallVector<Location>(module.getNumPorts(),
1218 UnknownLoc::get(module.getContext()));
1219}
1220
1221SmallVector<Location> HWModuleOp::getAllPortLocs() {
1222 SmallVector<Location> portLocs;
1223 portLocs.reserve(getNumPorts());
1224 auto resultLocs = getResultLocsAttr();
1225 unsigned inputCount = 0;
1226 auto modType = getModuleType();
1227 auto unknownLoc = UnknownLoc::get(getContext());
1228 auto *body = getBodyBlock();
1229 for (unsigned i = 0, e = getNumPorts(); i < e; ++i) {
1230 if (modType.isOutput(i)) {
1231 auto loc = resultLocs
1232 ? cast<Location>(
1233 resultLocs.getValue()[portLocs.size() - inputCount])
1234 : unknownLoc;
1235 portLocs.push_back(loc);
1236 } else {
1237 auto loc = body ? body->getArgument(inputCount).getLoc() : unknownLoc;
1238 portLocs.push_back(loc);
1239 ++inputCount;
1240 }
1241 }
1242 return portLocs;
1243}
1244
1245SmallVector<Location> HWModuleExternOp::getAllPortLocs() {
1246 return ::getAllPortLocs(*this);
1247}
1248
1249SmallVector<Location> HWModuleGeneratedOp::getAllPortLocs() {
1250 return ::getAllPortLocs(*this);
1251}
1252
1253void HWModuleOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1254 SmallVector<Attribute> resultLocs;
1255 unsigned inputCount = 0;
1256 auto modType = getModuleType();
1257 auto *body = getBodyBlock();
1258 for (unsigned i = 0, e = getNumPorts(); i < e; ++i) {
1259 if (modType.isOutput(i))
1260 resultLocs.push_back(locs[i]);
1261 else
1262 body->getArgument(inputCount++).setLoc(cast<Location>(locs[i]));
1263 }
1264 setResultLocsAttr(ArrayAttr::get(getContext(), resultLocs));
1265}
1266
1267void HWModuleExternOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1268 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1269}
1270
1271void HWModuleGeneratedOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1272 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1273}
1274
1275template <typename ModTy>
1276static void setAllPortNames(ArrayRef<Attribute> names, ModTy module) {
1277 auto numInputs = module.getNumInputPorts();
1278 SmallVector<Attribute> argNames(names.begin(), names.begin() + numInputs);
1279 SmallVector<Attribute> resNames(names.begin() + numInputs, names.end());
1280 auto oldType = module.getModuleType();
1281 SmallVector<ModulePort> newPorts(oldType.getPorts().begin(),
1282 oldType.getPorts().end());
1283 for (size_t i = 0UL, e = newPorts.size(); i != e; ++i)
1284 newPorts[i].name = cast<StringAttr>(names[i]);
1285 auto newType = ModuleType::get(module.getContext(), newPorts);
1286 module.setModuleType(newType);
1287}
1288
1289void HWModuleOp::setAllPortNames(ArrayRef<Attribute> names) {
1290 ::setAllPortNames(names, *this);
1291}
1292
1293void HWModuleExternOp::setAllPortNames(ArrayRef<Attribute> names) {
1294 ::setAllPortNames(names, *this);
1295}
1296
1297void HWModuleGeneratedOp::setAllPortNames(ArrayRef<Attribute> names) {
1298 ::setAllPortNames(names, *this);
1299}
1300
1301ArrayRef<Attribute> HWModuleOp::getAllPortAttrs() {
1302 auto attrs = getPerPortAttrs();
1303 if (attrs && !attrs->empty())
1304 return attrs->getValue();
1305 return {};
1306}
1307
1308ArrayRef<Attribute> HWModuleExternOp::getAllPortAttrs() {
1309 auto attrs = getPerPortAttrs();
1310 if (attrs && !attrs->empty())
1311 return attrs->getValue();
1312 return {};
1313}
1314
1315ArrayRef<Attribute> HWModuleGeneratedOp::getAllPortAttrs() {
1316 auto attrs = getPerPortAttrs();
1317 if (attrs && !attrs->empty())
1318 return attrs->getValue();
1319 return {};
1320}
1321
1322void HWModuleOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1323 setPerPortAttrsAttr(arrayOrEmpty(getContext(), attrs));
1324}
1325
1326void HWModuleExternOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1327 setPerPortAttrsAttr(arrayOrEmpty(getContext(), attrs));
1328}
1329
1330void HWModuleGeneratedOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1331 setPerPortAttrsAttr(arrayOrEmpty(getContext(), attrs));
1332}
1333
1334void HWModuleOp::removeAllPortAttrs() {
1335 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1336}
1337
1338void HWModuleExternOp::removeAllPortAttrs() {
1339 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1340}
1341
1342void HWModuleGeneratedOp::removeAllPortAttrs() {
1343 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1344}
1345
1346// This probably does really unexpected stuff when you change the number of
1347
1348template <typename ModTy>
1349static void setHWModuleType(ModTy &mod, ModuleType type) {
1350 auto argAttrs = mod.getAllInputAttrs();
1351 auto resAttrs = mod.getAllOutputAttrs();
1352 mod.setModuleTypeAttr(TypeAttr::get(type));
1353 unsigned newNumArgs = type.getNumInputs();
1354 unsigned newNumResults = type.getNumOutputs();
1355
1356 auto emptyDict = DictionaryAttr::get(mod.getContext());
1357 argAttrs.resize(newNumArgs, emptyDict);
1358 resAttrs.resize(newNumResults, emptyDict);
1359
1360 SmallVector<Attribute> attrs;
1361 attrs.append(argAttrs.begin(), argAttrs.end());
1362 attrs.append(resAttrs.begin(), resAttrs.end());
1363
1364 if (attrs.empty())
1365 return mod.removeAllPortAttrs();
1366 mod.setAllPortAttrs(attrs);
1367}
1368
1369void HWModuleOp::setHWModuleType(ModuleType type) {
1370 return ::setHWModuleType(*this, type);
1371}
1372
1373void HWModuleExternOp::setHWModuleType(ModuleType type) {
1374 return ::setHWModuleType(*this, type);
1375}
1376
1377void HWModuleGeneratedOp::setHWModuleType(ModuleType type) {
1378 return ::setHWModuleType(*this, type);
1379}
1380
1381/// Lookup the generator for the symbol. This returns null on
1382/// invalid IR.
1383Operation *HWModuleGeneratedOp::getGeneratorKindOp() {
1384 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
1385 return topLevelModuleOp.lookupSymbol(getGeneratorKind());
1386}
1387
1388LogicalResult
1389HWModuleGeneratedOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1390 auto *referencedKind =
1391 symbolTable.lookupNearestSymbolFrom(*this, getGeneratorKindAttr());
1392
1393 if (referencedKind == nullptr)
1394 return emitError("Cannot find generator definition '")
1395 << getGeneratorKind() << "'";
1396
1397 if (!isa<HWGeneratorSchemaOp>(referencedKind))
1398 return emitError("Symbol resolved to '")
1399 << referencedKind->getName()
1400 << "' which is not a HWGeneratorSchemaOp";
1401
1402 auto referencedKindOp = dyn_cast<HWGeneratorSchemaOp>(referencedKind);
1403 auto paramRef = referencedKindOp.getRequiredAttrs();
1404 auto dict = (*this)->getAttrDictionary();
1405 for (auto str : paramRef) {
1406 auto strAttr = dyn_cast<StringAttr>(str);
1407 if (!strAttr)
1408 return emitError("Unknown attribute type, expected a string");
1409 if (!dict.get(strAttr.getValue()))
1410 return emitError("Missing attribute '") << strAttr.getValue() << "'";
1411 }
1412
1413 return success();
1414}
1415
1416LogicalResult HWModuleGeneratedOp::verify() {
1417 return verifyModuleCommon(*this);
1418}
1419
1420void HWModuleGeneratedOp::getAsmBlockArgumentNames(
1421 mlir::Region &region, mlir::OpAsmSetValueNameFn setNameFn) {
1422 getAsmBlockArgumentNamesImpl(region, setNameFn);
1423}
1424
1425LogicalResult HWModuleOp::verifyBody() { return success(); }
1426
1427template <typename ModuleTy>
1428static SmallVector<PortInfo> getPortList(ModuleTy &mod) {
1429 auto modTy = mod.getHWModuleType();
1430 auto emptyDict = DictionaryAttr::get(mod.getContext());
1431 SmallVector<PortInfo> retval;
1432 auto locs = mod.getAllPortLocs();
1433 for (unsigned i = 0, e = modTy.getNumPorts(); i < e; ++i) {
1434 LocationAttr loc = locs[i];
1435 DictionaryAttr attrs =
1436 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(i));
1437 if (!attrs)
1438 attrs = emptyDict;
1439 retval.push_back({modTy.getPorts()[i],
1440 modTy.isOutput(i) ? modTy.getOutputIdForPortId(i)
1441 : modTy.getInputIdForPortId(i),
1442 attrs, loc});
1443 }
1444 return retval;
1445}
1446
1447template <typename ModuleTy>
1448static PortInfo getPort(ModuleTy &mod, size_t idx) {
1449 auto modTy = mod.getHWModuleType();
1450 auto emptyDict = DictionaryAttr::get(mod.getContext());
1451 LocationAttr loc = mod.getPortLoc(idx);
1452 DictionaryAttr attrs =
1453 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(idx));
1454 if (!attrs)
1455 attrs = emptyDict;
1456 return {modTy.getPorts()[idx],
1457 modTy.isOutput(idx) ? modTy.getOutputIdForPortId(idx)
1458 : modTy.getInputIdForPortId(idx),
1459 attrs, loc};
1460}
1461
1462//===----------------------------------------------------------------------===//
1463// InstanceOp
1464//===----------------------------------------------------------------------===//
1465
1466/// Create a instance that refers to a known module.
1467void InstanceOp::build(OpBuilder &builder, OperationState &result,
1468 Operation *module, StringAttr name,
1469 ArrayRef<Value> inputs, ArrayAttr parameters,
1470 InnerSymAttr innerSym) {
1471 if (!parameters)
1472 parameters = builder.getArrayAttr({});
1473
1474 auto mod = cast<hw::HWModuleLike>(module);
1475 auto argNames = builder.getArrayAttr(mod.getInputNames());
1476 auto resultNames = builder.getArrayAttr(mod.getOutputNames());
1477
1478 // Try to resolve the parameterized module type. If failed, use the module's
1479 // parmeterized type. If the client doesn't fix this error, the verifier will
1480 // fail.
1481 ModuleType modType = mod.getHWModuleType();
1482 FailureOr<ModuleType> resolvedModType = modType.resolveParametricTypes(
1483 parameters, result.location, /*emitErrors=*/false);
1484 if (succeeded(resolvedModType))
1485 modType = *resolvedModType;
1486 FunctionType funcType = resolvedModType->getFuncType();
1487 build(builder, result, funcType.getResults(), name,
1488 FlatSymbolRefAttr::get(SymbolTable::getSymbolName(module)), inputs,
1489 argNames, resultNames, parameters, innerSym, /*doNotPrint=*/{});
1490}
1491
1492std::optional<size_t> InstanceOp::getTargetResultIndex() {
1493 // Inner symbols on instance operations target the op not any result.
1494 return std::nullopt;
1495}
1496
1497LogicalResult InstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1499 *this, getModuleNameAttr(), getInputs(), getResultTypes(), getArgNames(),
1500 getResultNames(), getParameters(), symbolTable);
1501}
1502
1503LogicalResult InstanceOp::verify() {
1504 auto module = (*this)->getParentOfType<HWModuleOp>();
1505 if (!module)
1506 return success();
1507
1508 auto moduleParameters = module->getAttrOfType<ArrayAttr>("parameters");
1510 [&](const std::function<bool(InFlightDiagnostic &)> &fn) {
1511 auto diag = emitOpError();
1512 if (fn(diag))
1513 diag.attachNote(module->getLoc()) << "module declared here";
1514 };
1516 getParameters(), moduleParameters, emitError);
1517}
1518
1519ParseResult InstanceOp::parse(OpAsmParser &parser, OperationState &result) {
1520 StringAttr instanceNameAttr;
1521 InnerSymAttr innerSym;
1522 FlatSymbolRefAttr moduleNameAttr;
1523 SmallVector<OpAsmParser::UnresolvedOperand, 4> inputsOperands;
1524 SmallVector<Type, 1> inputsTypes, allResultTypes;
1525 ArrayAttr argNames, resultNames, parameters;
1526 auto noneType = parser.getBuilder().getType<NoneType>();
1527
1528 if (parser.parseAttribute(instanceNameAttr, noneType, "instanceName",
1529 result.attributes))
1530 return failure();
1531
1532 if (succeeded(parser.parseOptionalKeyword("sym"))) {
1533 // Parsing an optional symbol name doesn't fail, so no need to check the
1534 // result.
1535 if (parser.parseCustomAttributeWithFallback(innerSym))
1536 return failure();
1537 result.addAttribute(InnerSymbolTable::getInnerSymbolAttrName(), innerSym);
1538 }
1539
1540 llvm::SMLoc parametersLoc, inputsOperandsLoc;
1541 if (parser.parseAttribute(moduleNameAttr, noneType, "moduleName",
1542 result.attributes) ||
1543 parser.getCurrentLocation(&parametersLoc) ||
1544 parseOptionalParameterList(parser, parameters) ||
1545 parseInputPortList(parser, inputsOperands, inputsTypes, argNames) ||
1546 parser.resolveOperands(inputsOperands, inputsTypes, inputsOperandsLoc,
1547 result.operands) ||
1548 parser.parseArrow() ||
1549 parseOutputPortList(parser, allResultTypes, resultNames) ||
1550 parser.parseOptionalAttrDict(result.attributes)) {
1551 return failure();
1552 }
1553
1554 result.addAttribute("argNames", argNames);
1555 result.addAttribute("resultNames", resultNames);
1556 result.addAttribute("parameters", parameters);
1557 result.addTypes(allResultTypes);
1558 return success();
1559}
1560
1561void InstanceOp::print(OpAsmPrinter &p) {
1562 p << ' ';
1563 p.printAttributeWithoutType(getInstanceNameAttr());
1564 if (auto attr = getInnerSymAttr()) {
1565 p << " sym ";
1566 attr.print(p);
1567 }
1568 p << ' ';
1569 p.printAttributeWithoutType(getModuleNameAttr());
1570 printOptionalParameterList(p, *this, getParameters());
1571 printInputPortList(p, *this, getInputs(), getInputs().getTypes(),
1572 getArgNames());
1573 p << " -> ";
1574 printOutputPortList(p, *this, getResultTypes(), getResultNames());
1575
1576 p.printOptionalAttrDict(
1577 (*this)->getAttrs(),
1578 /*elidedAttrs=*/{"instanceName",
1579 InnerSymbolTable::getInnerSymbolAttrName(), "moduleName",
1580 "argNames", "resultNames", "parameters"});
1581}
1582
1583//===----------------------------------------------------------------------===//
1584// HWOutputOp
1585//===----------------------------------------------------------------------===//
1586
1587/// Verify that the num of operands and types fit the declared results.
1588LogicalResult OutputOp::verify() {
1589 // Check that the we (hw.output) have the same number of operands as our
1590 // region has results.
1591 ModuleType modType;
1592 if (auto mod = dyn_cast<HWModuleOp>((*this)->getParentOp()))
1593 modType = mod.getHWModuleType();
1594 else {
1595 emitOpError("must have a module parent");
1596 return failure();
1597 }
1598 auto modResults = modType.getOutputTypes();
1599 OperandRange outputValues = getOperands();
1600 if (modResults.size() != outputValues.size()) {
1601 emitOpError("must have same number of operands as region results.");
1602 return failure();
1603 }
1604
1605 // Check that the types of our operands and the region's results match.
1606 for (size_t i = 0, e = modResults.size(); i < e; ++i) {
1607 if (modResults[i] != outputValues[i].getType()) {
1608 emitOpError("output types must match module. In "
1609 "operand ")
1610 << i << ", expected " << modResults[i] << ", but got "
1611 << outputValues[i].getType() << ".";
1612 return failure();
1613 }
1614 }
1615
1616 return success();
1617}
1618
1619//===----------------------------------------------------------------------===//
1620// Other Operations
1621//===----------------------------------------------------------------------===//
1622
1623static ParseResult parseSliceTypes(OpAsmParser &p, Type &srcType,
1624 Type &idxType) {
1625 Type type;
1626 if (p.parseType(type))
1627 return p.emitError(p.getCurrentLocation(), "Expected type");
1628 auto arrType = type_dyn_cast<ArrayType>(type);
1629 if (!arrType)
1630 return p.emitError(p.getCurrentLocation(), "Expected !hw.array type");
1631 srcType = type;
1632 unsigned idxWidth = llvm::Log2_64_Ceil(arrType.getNumElements());
1633 idxType = IntegerType::get(p.getBuilder().getContext(), idxWidth);
1634 return success();
1635}
1636
1637static void printSliceTypes(OpAsmPrinter &p, Operation *, Type srcType,
1638 Type idxType) {
1639 p.printType(srcType);
1640}
1641
1642ParseResult ArrayCreateOp::parse(OpAsmParser &parser, OperationState &result) {
1643 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
1644 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
1645 Type elemType;
1646
1647 if (parser.parseOperandList(operands) ||
1648 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
1649 parser.parseType(elemType))
1650 return failure();
1651
1652 if (operands.size() == 0)
1653 return parser.emitError(inputOperandsLoc,
1654 "Cannot construct an array of length 0");
1655
1656 // Check for optional result type: " -> <type>"
1657 Type resultType;
1658 if (parser.parseOptionalArrow().succeeded()) {
1659 if (parser.parseType(resultType))
1660 return failure();
1661 result.addTypes(resultType);
1662 } else {
1663 result.addTypes({ArrayType::get(elemType, operands.size())});
1664 }
1665
1666 for (auto operand : operands)
1667 if (parser.resolveOperand(operand, elemType, result.operands))
1668 return failure();
1669 return success();
1670}
1671
1672void ArrayCreateOp::print(OpAsmPrinter &p) {
1673 p << " ";
1674 p.printOperands(getInputs());
1675 p.printOptionalAttrDict((*this)->getAttrs());
1676 p << " : " << getInputs()[0].getType();
1677
1678 // Print optional result type if it's not the default constructed type
1679 Type expectedType =
1680 ArrayType::get(getInputs()[0].getType(), getInputs().size());
1681 if (getType() != expectedType)
1682 p << " -> " << getType();
1683}
1684
1685void ArrayCreateOp::build(OpBuilder &b, OperationState &state,
1686 ValueRange values) {
1687 assert(values.size() > 0 && "Cannot build array of zero elements");
1688 Type elemType = values[0].getType();
1689 assert(llvm::all_of(
1690 values,
1691 [elemType](Value v) -> bool { return v.getType() == elemType; }) &&
1692 "All values must have same type.");
1693 build(b, state, ArrayType::get(elemType, values.size()), values);
1694}
1695
1696LogicalResult ArrayCreateOp::verify() {
1697 unsigned returnSize = hw::type_cast<ArrayType>(getType()).getNumElements();
1698 if (getInputs().size() != returnSize)
1699 return failure();
1700 return success();
1701}
1702
1703OpFoldResult ArrayCreateOp::fold(FoldAdaptor adaptor) {
1704 if (llvm::any_of(adaptor.getInputs(), [](Attribute attr) {
1705 return !isa_and_nonnull<IntegerAttr>(attr);
1706 }))
1707 return {};
1708 return ArrayAttr::get(getContext(), adaptor.getInputs());
1709}
1710
1711// Check whether an integer value is an offset from a base.
1712bool hw::isOffset(Value base, Value index, uint64_t offset) {
1713 if (auto constBase = base.getDefiningOp<hw::ConstantOp>()) {
1714 if (auto constIndex = index.getDefiningOp<hw::ConstantOp>()) {
1715 // If both values are a constant, check if index == base + offset.
1716 // To account for overflow, the addition is performed with an extra bit
1717 // and the offset is asserted to fit in the bit width of the base.
1718 auto baseValue = constBase.getValue();
1719 auto indexValue = constIndex.getValue();
1720
1721 unsigned bits = baseValue.getBitWidth();
1722 assert(bits == indexValue.getBitWidth() && "mismatched widths");
1723
1724 if (bits < 64 && offset >= (1ull << bits))
1725 return false;
1726
1727 APInt baseExt = baseValue.zextOrTrunc(bits + 1);
1728 APInt indexExt = indexValue.zextOrTrunc(bits + 1);
1729 return baseExt + offset == indexExt;
1730 }
1731 }
1732 return false;
1733}
1734
1735// Canonicalize a create of consecutive elements to a slice.
1736static LogicalResult foldCreateToSlice(ArrayCreateOp op,
1737 PatternRewriter &rewriter) {
1738 // Do not canonicalize create of get into a slice.
1739 auto arrayTy = hw::type_cast<ArrayType>(op.getType());
1740 if (arrayTy.getNumElements() <= 1)
1741 return failure();
1742 auto elemTy = arrayTy.getElementType();
1743
1744 // Check if create arguments are consecutive elements of the same array.
1745 // Attempt to break a create of gets into a sequence of consecutive intervals.
1746 struct Chunk {
1747 Value input;
1748 Value index;
1749 size_t size;
1750 };
1751 SmallVector<Chunk> chunks;
1752 for (Value value : llvm::reverse(op.getInputs())) {
1753 auto get = value.getDefiningOp<ArrayGetOp>();
1754 if (!get)
1755 return failure();
1756
1757 Value input = get.getInput();
1758 Value index = get.getIndex();
1759 if (!chunks.empty()) {
1760 auto &c = *chunks.rbegin();
1761 if (c.input == get.getInput() && isOffset(c.index, index, c.size)) {
1762 c.size++;
1763 continue;
1764 }
1765 }
1766
1767 chunks.push_back(Chunk{input, index, 1});
1768 }
1769
1770 // If there is a single slice, eliminate the create.
1771 if (chunks.size() == 1) {
1772 auto &chunk = chunks[0];
1773 rewriter.replaceOp(op, rewriter.createOrFold<ArraySliceOp>(
1774 op.getLoc(), arrayTy, chunk.input, chunk.index));
1775 return success();
1776 }
1777
1778 // If the number of chunks is significantly less than the number of
1779 // elements, replace the create with a concat of the identified slices.
1780 if (chunks.size() * 2 < arrayTy.getNumElements()) {
1781 SmallVector<Value> slices;
1782 for (auto &chunk : llvm::reverse(chunks)) {
1783 auto sliceTy = ArrayType::get(elemTy, chunk.size);
1784 slices.push_back(rewriter.createOrFold<ArraySliceOp>(
1785 op.getLoc(), sliceTy, chunk.input, chunk.index));
1786 }
1787 rewriter.replaceOpWithNewOp<ArrayConcatOp>(op, arrayTy, slices);
1788 return success();
1789 }
1790
1791 return failure();
1792}
1793
1794LogicalResult ArrayCreateOp::canonicalize(ArrayCreateOp op,
1795 PatternRewriter &rewriter) {
1796 if (succeeded(foldCreateToSlice(op, rewriter)))
1797 return success();
1798 return failure();
1799}
1800
1801Value ArrayCreateOp::getUniformElement() {
1802 if (!getInputs().empty() && llvm::all_equal(getInputs()))
1803 return getInputs()[0];
1804 return {};
1805}
1806
1807static std::optional<uint64_t> getUIntFromValue(Value value) {
1808 auto idxOp = dyn_cast_or_null<ConstantOp>(value.getDefiningOp());
1809 if (!idxOp)
1810 return std::nullopt;
1811 APInt idxAttr = idxOp.getValue();
1812 if (idxAttr.getBitWidth() > 64)
1813 return std::nullopt;
1814 return idxAttr.getLimitedValue();
1815}
1816
1817LogicalResult ArraySliceOp::verify() {
1818 unsigned inputSize =
1819 type_cast<ArrayType>(getInput().getType()).getNumElements();
1820 if (llvm::Log2_64_Ceil(inputSize) !=
1821 getLowIndex().getType().getIntOrFloatBitWidth())
1822 return emitOpError(
1823 "ArraySlice: index width must match clog2 of array size");
1824 return success();
1825}
1826
1827OpFoldResult ArraySliceOp::fold(FoldAdaptor adaptor) {
1828 // If we are slicing the entire input, then return it.
1829 if (getType() == getInput().getType())
1830 return getInput();
1831 return {};
1832}
1833
1834LogicalResult ArraySliceOp::canonicalize(ArraySliceOp op,
1835 PatternRewriter &rewriter) {
1836 auto sliceTy = hw::type_cast<ArrayType>(op.getType());
1837 auto elemTy = sliceTy.getElementType();
1838 uint64_t sliceSize = sliceTy.getNumElements();
1839 if (sliceSize == 0)
1840 return failure();
1841
1842 if (sliceSize == 1) {
1843 // slice(a, n) -> create(a[n])
1844 auto get = ArrayGetOp::create(rewriter, op.getLoc(), op.getInput(),
1845 op.getLowIndex());
1846 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(),
1847 get.getResult());
1848 return success();
1849 }
1850
1851 auto offsetOpt = getUIntFromValue(op.getLowIndex());
1852 if (!offsetOpt)
1853 return failure();
1854
1855 auto *inputOp = op.getInput().getDefiningOp();
1856 if (auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
1857 // slice(slice(a, n), m) -> slice(a, n + m)
1858 if (inputSlice == op)
1859 return failure();
1860
1861 auto inputIndex = inputSlice.getLowIndex();
1862 auto inputOffsetOpt = getUIntFromValue(inputIndex);
1863 if (!inputOffsetOpt)
1864 return failure();
1865
1866 uint64_t offset = *offsetOpt + *inputOffsetOpt;
1867 auto lowIndex =
1868 ConstantOp::create(rewriter, op.getLoc(), inputIndex.getType(), offset);
1869 rewriter.replaceOpWithNewOp<ArraySliceOp>(op, op.getType(),
1870 inputSlice.getInput(), lowIndex);
1871 return success();
1872 }
1873
1874 if (auto inputCreate = dyn_cast_or_null<ArrayCreateOp>(inputOp)) {
1875 // slice(create(a0, a1, ..., an), m) -> create(am, ...)
1876 auto inputs = inputCreate.getInputs();
1877
1878 uint64_t begin = inputs.size() - *offsetOpt - sliceSize;
1879 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(),
1880 inputs.slice(begin, sliceSize));
1881 return success();
1882 }
1883
1884 if (auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
1885 // slice(concat(a1, a2, ...)) -> concat(a2, slice(a3, ..), ...)
1886 SmallVector<Value> chunks;
1887 uint64_t sliceStart = *offsetOpt;
1888 for (auto input : llvm::reverse(inputConcat.getInputs())) {
1889 // Check whether the input intersects with the slice.
1890 uint64_t inputSize =
1891 hw::type_cast<ArrayType>(input.getType()).getNumElements();
1892 if (inputSize == 0 || inputSize <= sliceStart) {
1893 sliceStart -= inputSize;
1894 continue;
1895 }
1896
1897 // Find the indices to slice from this input by intersection.
1898 uint64_t cutEnd = std::min(inputSize, sliceStart + sliceSize);
1899 uint64_t cutSize = cutEnd - sliceStart;
1900 assert(cutSize != 0 && "slice cannot be empty");
1901
1902 if (cutSize == inputSize) {
1903 // The whole input fits in the slice, add it.
1904 assert(sliceStart == 0 && "invalid cut size");
1905 chunks.push_back(input);
1906 } else {
1907 // Slice the required bits from the input.
1908 unsigned width = inputSize == 1 ? 1 : llvm::Log2_64_Ceil(inputSize);
1909 auto lowIndex = ConstantOp::create(
1910 rewriter, op.getLoc(), rewriter.getIntegerType(width), sliceStart);
1911 chunks.push_back(ArraySliceOp::create(
1912 rewriter, op.getLoc(), hw::ArrayType::get(elemTy, cutSize), input,
1913 lowIndex));
1914 }
1915
1916 sliceStart = 0;
1917 sliceSize -= cutSize;
1918 if (sliceSize == 0)
1919 break;
1920 }
1921
1922 assert(chunks.size() > 0 && "missing sliced items");
1923 if (chunks.size() == 1)
1924 rewriter.replaceOp(op, chunks[0]);
1925 else
1926 rewriter.replaceOpWithNewOp<ArrayConcatOp>(
1927 op, llvm::to_vector(llvm::reverse(chunks)));
1928 return success();
1929 }
1930 return failure();
1931}
1932
1933//===----------------------------------------------------------------------===//
1934// ArrayConcatOp
1935//===----------------------------------------------------------------------===//
1936
1937static ParseResult parseArrayConcatTypes(OpAsmParser &p,
1938 SmallVectorImpl<Type> &inputTypes,
1939 Type &resultType) {
1940 Type elemType;
1941 uint64_t resultSize = 0;
1942
1943 auto parseElement = [&]() -> ParseResult {
1944 Type ty;
1945 if (p.parseType(ty))
1946 return failure();
1947 auto arrTy = type_dyn_cast<ArrayType>(ty);
1948 if (!arrTy)
1949 return p.emitError(p.getCurrentLocation(), "Expected !hw.array type");
1950 if (elemType && elemType != arrTy.getElementType())
1951 return p.emitError(p.getCurrentLocation(), "Expected array element type ")
1952 << elemType;
1953
1954 elemType = arrTy.getElementType();
1955 inputTypes.push_back(ty);
1956 resultSize += arrTy.getNumElements();
1957 return success();
1958 };
1959
1960 if (p.parseCommaSeparatedList(parseElement))
1961 return failure();
1962
1963 resultType = ArrayType::get(elemType, resultSize);
1964 return success();
1965}
1966
1967static void printArrayConcatTypes(OpAsmPrinter &p, Operation *,
1968 TypeRange inputTypes, Type resultType) {
1969 llvm::interleaveComma(inputTypes, p, [&p](Type t) { p << t; });
1970}
1971
1972void ArrayConcatOp::build(OpBuilder &b, OperationState &state,
1973 ValueRange values) {
1974 assert(!values.empty() && "Cannot build array of zero elements");
1975 ArrayType arrayTy = cast<ArrayType>(values[0].getType());
1976 Type elemTy = arrayTy.getElementType();
1977 assert(llvm::all_of(values,
1978 [elemTy](Value v) -> bool {
1979 return isa<ArrayType>(v.getType()) &&
1980 cast<ArrayType>(v.getType()).getElementType() ==
1981 elemTy;
1982 }) &&
1983 "All values must be of ArrayType with the same element type.");
1984
1985 uint64_t resultSize = 0;
1986 for (Value val : values)
1987 resultSize += cast<ArrayType>(val.getType()).getNumElements();
1988 build(b, state, ArrayType::get(elemTy, resultSize), values);
1989}
1990
1991OpFoldResult ArrayConcatOp::fold(FoldAdaptor adaptor) {
1992 if (getInputs().size() == 1)
1993 return getInputs()[0];
1994
1995 auto inputs = adaptor.getInputs();
1996 SmallVector<Attribute> array;
1997 for (size_t i = 0, e = getNumOperands(); i < e; ++i) {
1998 if (!inputs[i])
1999 return {};
2000 llvm::copy(cast<ArrayAttr>(inputs[i]), std::back_inserter(array));
2001 }
2002 return ArrayAttr::get(getContext(), array);
2003}
2004
2005// Flatten a concatenation of array creates into a single create.
2006static bool flattenConcatOp(ArrayConcatOp op, PatternRewriter &rewriter) {
2007 for (auto input : op.getInputs())
2008 if (!input.getDefiningOp<ArrayCreateOp>())
2009 return false;
2010
2011 SmallVector<Value> items;
2012 for (auto input : op.getInputs()) {
2013 auto create = cast<ArrayCreateOp>(input.getDefiningOp());
2014 for (auto item : create.getInputs())
2015 items.push_back(item);
2016 }
2017
2018 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, items);
2019 return true;
2020}
2021
2022// Merge consecutive slice expressions in a concatenation.
2023static bool mergeConcatSlices(ArrayConcatOp op, PatternRewriter &rewriter) {
2024 struct Slice {
2025 Value input;
2026 Value index;
2027 size_t size;
2028 Value op;
2029 SmallVector<Location> locs;
2030 };
2031
2032 SmallVector<Value> items;
2033 std::optional<Slice> last;
2034 bool changed = false;
2035
2036 auto concatenate = [&] {
2037 // If there is only one op in the slice, place it to the items list.
2038 if (!last)
2039 return;
2040 if (last->op) {
2041 items.push_back(last->op);
2042 last.reset();
2043 return;
2044 }
2045
2046 // Otherwise, create a new slice of with the given size and place it.
2047 // In this case, the concat op is replaced, using the new argument.
2048 changed = true;
2049 auto loc = FusedLoc::get(op.getContext(), last->locs);
2050 auto origTy = hw::type_cast<ArrayType>(last->input.getType());
2051 auto arrayTy = ArrayType::get(origTy.getElementType(), last->size);
2052 items.push_back(rewriter.createOrFold<ArraySliceOp>(
2053 loc, arrayTy, last->input, last->index));
2054
2055 last.reset();
2056 };
2057
2058 auto append = [&](Value op, Value input, Value index, size_t size) {
2059 // If this slice is an extension of the previous one, extend the size
2060 // saved. In this case, a new slice of is created and the concatenation
2061 // operator is rewritten. Otherwise, flush the last slice.
2062 if (last) {
2063 if (last->input == input && isOffset(last->index, index, last->size)) {
2064 last->size += size;
2065 last->op = {};
2066 last->locs.push_back(op.getLoc());
2067 return;
2068 }
2069 concatenate();
2070 }
2071 last.emplace(Slice{input, index, size, op, {op.getLoc()}});
2072 };
2073
2074 for (auto item : llvm::reverse(op.getInputs())) {
2075 if (auto slice = item.getDefiningOp<ArraySliceOp>()) {
2076 auto size = hw::type_cast<ArrayType>(slice.getType()).getNumElements();
2077 append(item, slice.getInput(), slice.getLowIndex(), size);
2078 continue;
2079 }
2080
2081 if (auto create = item.getDefiningOp<ArrayCreateOp>()) {
2082 if (create.getInputs().size() == 1) {
2083 if (auto get = create.getInputs()[0].getDefiningOp<ArrayGetOp>()) {
2084 append(item, get.getInput(), get.getIndex(), 1);
2085 continue;
2086 }
2087 }
2088 }
2089
2090 concatenate();
2091 items.push_back(item);
2092 }
2093 concatenate();
2094
2095 if (!changed)
2096 return false;
2097
2098 if (items.size() == 1) {
2099 rewriter.replaceOp(op, items[0]);
2100 } else {
2101 std::reverse(items.begin(), items.end());
2102 rewriter.replaceOpWithNewOp<ArrayConcatOp>(op, items);
2103 }
2104 return true;
2105}
2106
2107LogicalResult ArrayConcatOp::canonicalize(ArrayConcatOp op,
2108 PatternRewriter &rewriter) {
2109 // concat(create(a1, ...), create(a3, ...), ...) -> create(a1, ..., a3, ...)
2110 if (flattenConcatOp(op, rewriter))
2111 return success();
2112
2113 // concat(slice(a, n, m), slice(a, n + m, p)) -> concat(slice(a, n, m + p))
2114 if (mergeConcatSlices(op, rewriter))
2115 return success();
2116
2117 return failure();
2118}
2119
2120//===----------------------------------------------------------------------===//
2121// EnumConstantOp
2122//===----------------------------------------------------------------------===//
2123
2124ParseResult EnumConstantOp::parse(OpAsmParser &parser, OperationState &result) {
2125 // Parse a Type instead of an EnumType since the type might be a type alias.
2126 // The validity of the canonical type is checked during construction of the
2127 // EnumFieldAttr.
2128 Type type;
2129 StringRef field;
2130
2131 auto loc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
2132 if (parser.parseKeyword(&field) || parser.parseColonType(type))
2133 return failure();
2134
2135 auto fieldAttr = EnumFieldAttr::get(
2136 loc, StringAttr::get(parser.getContext(), field), type);
2137
2138 if (!fieldAttr)
2139 return failure();
2140
2141 result.addAttribute("field", fieldAttr);
2142 result.addTypes(type);
2143
2144 return success();
2145}
2146
2147void EnumConstantOp::print(OpAsmPrinter &p) {
2148 p << " " << getField().getField().getValue() << " : "
2149 << getField().getType().getValue();
2150}
2151
2152void EnumConstantOp::getAsmResultNames(
2153 function_ref<void(Value, StringRef)> setNameFn) {
2154 setNameFn(getResult(), getField().getField().str());
2155}
2156
2157void EnumConstantOp::build(OpBuilder &builder, OperationState &odsState,
2158 EnumFieldAttr field) {
2159 return build(builder, odsState, field.getType().getValue(), field);
2160}
2161
2162OpFoldResult EnumConstantOp::fold(FoldAdaptor adaptor) {
2163 assert(adaptor.getOperands().empty() && "constant has no operands");
2164 return getFieldAttr();
2165}
2166
2167LogicalResult EnumConstantOp::verify() {
2168 auto fieldAttr = getFieldAttr();
2169 auto fieldType = fieldAttr.getType().getValue();
2170 // This check ensures that we are using the exact same type, without looking
2171 // through type aliases.
2172 if (fieldType != getType())
2173 emitOpError("return type ")
2174 << getType() << " does not match attribute type " << fieldAttr;
2175 return success();
2176}
2177
2178//===----------------------------------------------------------------------===//
2179// EnumCmpOp
2180//===----------------------------------------------------------------------===//
2181
2182LogicalResult EnumCmpOp::verify() {
2183 // Compare the canonical types.
2184 auto lhsType = type_cast<EnumType>(getLhs().getType());
2185 auto rhsType = type_cast<EnumType>(getRhs().getType());
2186 if (rhsType != lhsType)
2187 emitOpError("types do not match");
2188 return success();
2189}
2190
2191//===----------------------------------------------------------------------===//
2192// StructCreateOp
2193//===----------------------------------------------------------------------===//
2194
2195ParseResult StructCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2196 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2197 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
2198 Type declOrAliasType;
2199
2200 if (parser.parseLParen() || parser.parseOperandList(operands) ||
2201 parser.parseRParen() || parser.parseOptionalAttrDict(result.attributes) ||
2202 parser.parseColonType(declOrAliasType))
2203 return failure();
2204
2205 auto declType = type_dyn_cast<StructType>(declOrAliasType);
2206 if (!declType)
2207 return parser.emitError(parser.getNameLoc(),
2208 "expected !hw.struct type or alias");
2209
2210 llvm::SmallVector<Type, 4> structInnerTypes;
2211 declType.getInnerTypes(structInnerTypes);
2212 result.addTypes(declOrAliasType);
2213
2214 if (parser.resolveOperands(operands, structInnerTypes, inputOperandsLoc,
2215 result.operands))
2216 return failure();
2217 return success();
2218}
2219
2220void StructCreateOp::print(OpAsmPrinter &printer) {
2221 printer << " (";
2222 printer.printOperands(getInput());
2223 printer << ")";
2224 printer.printOptionalAttrDict((*this)->getAttrs());
2225 printer << " : " << getType();
2226}
2227
2228LogicalResult StructCreateOp::verify() {
2229 auto elements = hw::type_cast<StructType>(getType()).getElements();
2230
2231 if (elements.size() != getInput().size())
2232 return emitOpError("structure field count mismatch");
2233
2234 for (const auto &[field, value] : llvm::zip(elements, getInput()))
2235 if (field.type != value.getType())
2236 return emitOpError("structure field `")
2237 << field.name << "` type does not match";
2238
2239 return success();
2240}
2241
2242OpFoldResult StructCreateOp::fold(FoldAdaptor adaptor) {
2243 // struct_create(struct_explode(x)) => x
2244 if (!getInput().empty())
2245 if (auto explodeOp = getInput()[0].getDefiningOp<StructExplodeOp>();
2246 explodeOp && getInput() == explodeOp.getResults() &&
2247 getResult().getType() == explodeOp.getInput().getType())
2248 return explodeOp.getInput();
2249
2250 auto inputs = adaptor.getInput();
2251 if (llvm::any_of(inputs, [](Attribute attr) {
2252 return !isa_and_nonnull<IntegerAttr>(attr);
2253 }))
2254 return {};
2255 return ArrayAttr::get(getContext(), inputs);
2256}
2257
2258//===----------------------------------------------------------------------===//
2259// StructExplodeOp
2260//===----------------------------------------------------------------------===//
2261
2262ParseResult StructExplodeOp::parse(OpAsmParser &parser,
2263 OperationState &result) {
2264 OpAsmParser::UnresolvedOperand operand;
2265 Type declType;
2266
2267 if (parser.parseOperand(operand) ||
2268 parser.parseOptionalAttrDict(result.attributes) ||
2269 parser.parseColonType(declType))
2270 return failure();
2271 auto structType = type_dyn_cast<StructType>(declType);
2272 if (!structType)
2273 return parser.emitError(parser.getNameLoc(),
2274 "invalid kind of type specified");
2275
2276 llvm::SmallVector<Type, 4> structInnerTypes;
2277 structType.getInnerTypes(structInnerTypes);
2278 result.addTypes(structInnerTypes);
2279
2280 if (parser.resolveOperand(operand, declType, result.operands))
2281 return failure();
2282 return success();
2283}
2284
2285void StructExplodeOp::print(OpAsmPrinter &printer) {
2286 printer << " ";
2287 printer.printOperand(getInput());
2288 printer.printOptionalAttrDict((*this)->getAttrs());
2289 printer << " : " << getInput().getType();
2290}
2291
2292LogicalResult StructExplodeOp::fold(FoldAdaptor adaptor,
2293 SmallVectorImpl<OpFoldResult> &results) {
2294 auto input = adaptor.getInput();
2295 if (!input)
2296 return failure();
2297 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(results));
2298 return success();
2299}
2300
2301LogicalResult StructExplodeOp::canonicalize(StructExplodeOp op,
2302 PatternRewriter &rewriter) {
2303 auto *inputOp = op.getInput().getDefiningOp();
2304 auto elements = type_cast<StructType>(op.getInput().getType()).getElements();
2305 auto result = failure();
2306 auto opResults = op.getResults();
2307 for (uint32_t index = 0; index < elements.size(); index++) {
2308 if (auto foldResult = foldStructExtract(inputOp, index)) {
2309 rewriter.replaceAllUsesWith(opResults[index], foldResult);
2310 result = success();
2311 }
2312 }
2313 return result;
2314}
2315
2316void StructExplodeOp::getAsmResultNames(
2317 function_ref<void(Value, StringRef)> setNameFn) {
2318 auto structType = type_cast<StructType>(getInput().getType());
2319 for (auto [res, field] : llvm::zip(getResults(), structType.getElements()))
2320 setNameFn(res, field.name.str());
2321}
2322
2323void StructExplodeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2324 Value input) {
2325 StructType inputType = dyn_cast<StructType>(input.getType());
2326 assert(inputType);
2327 SmallVector<Type, 16> fieldTypes;
2328 for (auto field : inputType.getElements())
2329 fieldTypes.push_back(field.type);
2330 build(odsBuilder, odsState, fieldTypes, input);
2331}
2332
2333//===----------------------------------------------------------------------===//
2334// StructExtractOp
2335//===----------------------------------------------------------------------===//
2336
2337/// Ensure an aggregate op's field index is within the bounds of
2338/// the aggregate type and the accessed field is of 'elementType'.
2339template <typename AggregateOp, typename AggregateType>
2340static LogicalResult verifyAggregateFieldIndexAndType(AggregateOp &op,
2341 AggregateType aggType,
2342 Type elementType) {
2343 auto index = op.getFieldIndex();
2344 if (index >= aggType.getElements().size())
2345 return op.emitOpError() << "field index " << index
2346 << " exceeds element count of aggregate type";
2347
2349 getCanonicalType(aggType.getElements()[index].type))
2350 return op.emitOpError()
2351 << "type " << aggType.getElements()[index].type
2352 << " of accessed field in aggregate at index " << index
2353 << " does not match expected type " << elementType;
2354
2355 return success();
2356}
2357
2358LogicalResult StructExtractOp::verify() {
2359 return verifyAggregateFieldIndexAndType<StructExtractOp, StructType>(
2360 *this, getInput().getType(), getType());
2361}
2362
2363/// Use the same parser for both struct_extract and union_extract since the
2364/// syntax is identical.
2365template <typename AggregateType>
2366static ParseResult parseExtractOp(OpAsmParser &parser, OperationState &result) {
2367 OpAsmParser::UnresolvedOperand operand;
2368 StringAttr fieldName;
2369 Type declType;
2370
2371 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2372 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2373 parser.parseOptionalAttrDict(result.attributes) ||
2374 parser.parseColonType(declType))
2375 return failure();
2376 auto aggType = type_dyn_cast<AggregateType>(declType);
2377 if (!aggType)
2378 return parser.emitError(parser.getNameLoc(),
2379 "invalid kind of type specified");
2380
2381 auto fieldIndex = aggType.getFieldIndex(fieldName);
2382 if (!fieldIndex) {
2383 parser.emitError(parser.getNameLoc(), "field name '" +
2384 fieldName.getValue() +
2385 "' not found in aggregate type");
2386 return failure();
2387 }
2388
2389 auto indexAttr =
2390 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2391 result.addAttribute("fieldIndex", indexAttr);
2392 Type resultType = aggType.getElements()[*fieldIndex].type;
2393 result.addTypes(resultType);
2394
2395 if (parser.resolveOperand(operand, declType, result.operands))
2396 return failure();
2397 return success();
2398}
2399
2400/// Use the same printer for both struct_extract and union_extract since the
2401/// syntax is identical.
2402template <typename AggType>
2403static void printExtractOp(OpAsmPrinter &printer, AggType op) {
2404 printer << " ";
2405 printer.printOperand(op.getInput());
2406 printer << "[\"" << op.getFieldName() << "\"]";
2407 printer.printOptionalAttrDict(op->getAttrs(), {"fieldIndex"});
2408 printer << " : " << op.getInput().getType();
2409}
2410
2411ParseResult StructExtractOp::parse(OpAsmParser &parser,
2412 OperationState &result) {
2413 return parseExtractOp<StructType>(parser, result);
2414}
2415
2416void StructExtractOp::print(OpAsmPrinter &printer) {
2417 printExtractOp(printer, *this);
2418}
2419
2420void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2421 Value input, StructType::FieldInfo field) {
2422 auto fieldIndex =
2423 type_cast<StructType>(input.getType()).getFieldIndex(field.name);
2424 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2425 build(builder, odsState, field.type, input, *fieldIndex);
2426}
2427
2428void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2429 Value input, StringAttr fieldName) {
2430 auto structType = type_cast<StructType>(input.getType());
2431 auto fieldIndex = structType.getFieldIndex(fieldName);
2432 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2433 auto resultType = structType.getElements()[*fieldIndex].type;
2434 build(builder, odsState, resultType, input, *fieldIndex);
2435}
2436
2437OpFoldResult StructExtractOp::fold(FoldAdaptor adaptor) {
2438 if (auto constOperand = adaptor.getInput()) {
2439 // Fold extract from aggregate constant
2440 auto operandAttr = llvm::cast<ArrayAttr>(constOperand);
2441 return operandAttr.getValue()[getFieldIndex()];
2442 }
2443
2444 if (auto foldResult =
2445 foldStructExtract(getInput().getDefiningOp(), getFieldIndex()))
2446 return foldResult;
2447 return {};
2448}
2449
2450LogicalResult StructExtractOp::canonicalize(StructExtractOp op,
2451 PatternRewriter &rewriter) {
2452 auto *inputOp = op.getInput().getDefiningOp();
2453
2454 // b = extract(inject(x["a"], v0)["b"]) => extract(x, "b")
2455 if (auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
2456 if (structInject.getFieldIndex() != op.getFieldIndex()) {
2457 rewriter.replaceOpWithNewOp<StructExtractOp>(
2458 op, op.getType(), structInject.getInput(), op.getFieldIndexAttr());
2459 return success();
2460 }
2461 }
2462
2463 return failure();
2464}
2465
2466void StructExtractOp::getAsmResultNames(
2467 function_ref<void(Value, StringRef)> setNameFn) {
2468 setNameFn(getResult(), getFieldName());
2469}
2470
2471//===----------------------------------------------------------------------===//
2472// StructInjectOp
2473//===----------------------------------------------------------------------===//
2474
2475void StructInjectOp::build(OpBuilder &builder, OperationState &odsState,
2476 Value input, StringAttr fieldName, Value newValue) {
2477 auto structType = type_cast<StructType>(input.getType());
2478 auto fieldIndex = structType.getFieldIndex(fieldName);
2479 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2480 build(builder, odsState, input, *fieldIndex, newValue);
2481}
2482
2483LogicalResult StructInjectOp::verify() {
2484 return verifyAggregateFieldIndexAndType<StructInjectOp, StructType>(
2485 *this, getInput().getType(), getNewValue().getType());
2486}
2487
2488ParseResult StructInjectOp::parse(OpAsmParser &parser, OperationState &result) {
2489 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2490 OpAsmParser::UnresolvedOperand operand, val;
2491 StringAttr fieldName;
2492 Type declType;
2493
2494 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2495 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2496 parser.parseComma() || parser.parseOperand(val) ||
2497 parser.parseOptionalAttrDict(result.attributes) ||
2498 parser.parseColonType(declType))
2499 return failure();
2500 auto structType = type_dyn_cast<StructType>(declType);
2501 if (!structType)
2502 return parser.emitError(inputOperandsLoc, "invalid kind of type specified");
2503
2504 auto fieldIndex = structType.getFieldIndex(fieldName);
2505 if (!fieldIndex) {
2506 parser.emitError(parser.getNameLoc(), "field name '" +
2507 fieldName.getValue() +
2508 "' not found in aggregate type");
2509 return failure();
2510 }
2511
2512 auto indexAttr =
2513 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2514 result.addAttribute("fieldIndex", indexAttr);
2515 result.addTypes(declType);
2516
2517 Type resultType = structType.getElements()[*fieldIndex].type;
2518 if (parser.resolveOperands({operand, val}, {declType, resultType},
2519 inputOperandsLoc, result.operands))
2520 return failure();
2521 return success();
2522}
2523
2524void StructInjectOp::print(OpAsmPrinter &printer) {
2525 printer << " ";
2526 printer.printOperand(getInput());
2527 printer << "[\"" << getFieldName() << "\"], ";
2528 printer.printOperand(getNewValue());
2529 printer.printOptionalAttrDict((*this)->getAttrs(), {"fieldIndex"});
2530 printer << " : " << getInput().getType();
2531}
2532
2533OpFoldResult StructInjectOp::fold(FoldAdaptor adaptor) {
2534 auto input = adaptor.getInput();
2535 auto newValue = adaptor.getNewValue();
2536 if (!input || !newValue)
2537 return {};
2538 SmallVector<Attribute> array;
2539 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(array));
2540 array[getFieldIndex()] = newValue;
2541 return ArrayAttr::get(getContext(), array);
2542}
2543
2544LogicalResult StructInjectOp::canonicalize(StructInjectOp op,
2545 PatternRewriter &rewriter) {
2546 // If this inject is only used as an input to another inject, don't try to
2547 // canonicalize it. It will be included in that other op's canonicalization
2548 // attempt. This avoids doing redundant work.
2549 if (op->hasOneUse()) {
2550 auto &use = *op->use_begin();
2551 if (isa<StructInjectOp>(use.getOwner()) && use.getOperandNumber() == 0)
2552 return failure();
2553 }
2554
2555 // Canonicalize multiple injects into a create op and eliminate overwrites.
2556 SmallPtrSet<Operation *, 4> injects;
2557 DenseMap<StringAttr, Value> fields;
2558
2559 // Chase a chain of injects. Bail out if cycles are present.
2560 StructInjectOp inject = op;
2561 Value input;
2562 do {
2563 if (!injects.insert(inject).second)
2564 break;
2565
2566 fields.try_emplace(inject.getFieldNameAttr(), inject.getNewValue());
2567 input = inject.getInput();
2568 inject = dyn_cast_or_null<StructInjectOp>(input.getDefiningOp());
2569 } while (inject);
2570 assert(input && "missing input to inject chain");
2571
2572 auto ty = hw::type_cast<StructType>(op.getType());
2573 auto elements = ty.getElements();
2574
2575 // If the inject chain sets all fields, canonicalize to create.
2576 if (fields.size() == elements.size()) {
2577 SmallVector<Value> createFields;
2578 for (const auto &field : elements) {
2579 auto it = fields.find(field.name);
2580 assert(it != fields.end() && "missing field");
2581 createFields.push_back(it->second);
2582 }
2583 rewriter.replaceOpWithNewOp<StructCreateOp>(op, ty, createFields);
2584 return success();
2585 }
2586
2587 // Nothing to canonicalize, only the original inject in the chain.
2588 if (injects.size() == fields.size())
2589 return failure();
2590
2591 // Eliminate overwrites. The hash map contains the last write to each field.
2592 for (uint32_t fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
2593 auto it = fields.find(elements[fieldIndex].name);
2594 if (it == fields.end())
2595 continue;
2596 input = StructInjectOp::create(rewriter, op.getLoc(), ty, input, fieldIndex,
2597 it->second);
2598 }
2599
2600 rewriter.replaceOp(op, input);
2601 return success();
2602}
2603
2604//===----------------------------------------------------------------------===//
2605// UnionCreateOp
2606//===----------------------------------------------------------------------===//
2607
2608LogicalResult UnionCreateOp::verify() {
2609 return verifyAggregateFieldIndexAndType<UnionCreateOp, UnionType>(
2610 *this, getType(), getInput().getType());
2611}
2612
2613void UnionCreateOp::build(OpBuilder &builder, OperationState &odsState,
2614 Type unionType, StringAttr fieldName, Value input) {
2615 auto fieldIndex = type_cast<UnionType>(unionType).getFieldIndex(fieldName);
2616 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2617 build(builder, odsState, unionType, *fieldIndex, input);
2618}
2619
2620ParseResult UnionCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2621 Type declOrAliasType;
2622 StringAttr fieldName;
2623 OpAsmParser::UnresolvedOperand input;
2624 llvm::SMLoc fieldLoc = parser.getCurrentLocation();
2625
2626 if (parser.parseAttribute(fieldName) || parser.parseComma() ||
2627 parser.parseOperand(input) ||
2628 parser.parseOptionalAttrDict(result.attributes) ||
2629 parser.parseColonType(declOrAliasType))
2630 return failure();
2631
2632 auto declType = type_dyn_cast<UnionType>(declOrAliasType);
2633 if (!declType)
2634 return parser.emitError(parser.getNameLoc(),
2635 "expected !hw.union type or alias");
2636
2637 auto fieldIndex = declType.getFieldIndex(fieldName);
2638 if (!fieldIndex) {
2639 parser.emitError(fieldLoc, "cannot find union field '")
2640 << fieldName.getValue() << '\'';
2641 return failure();
2642 }
2643
2644 auto indexAttr =
2645 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2646 result.addAttribute("fieldIndex", indexAttr);
2647 Type inputType = declType.getElements()[*fieldIndex].type;
2648
2649 if (parser.resolveOperand(input, inputType, result.operands))
2650 return failure();
2651 result.addTypes({declOrAliasType});
2652 return success();
2653}
2654
2655void UnionCreateOp::print(OpAsmPrinter &printer) {
2656 printer << " \"" << getFieldName() << "\", ";
2657 printer.printOperand(getInput());
2658 printer.printOptionalAttrDict((*this)->getAttrs(), {"fieldIndex"});
2659 printer << " : " << getType();
2660}
2661
2662//===----------------------------------------------------------------------===//
2663// UnionExtractOp
2664//===----------------------------------------------------------------------===//
2665
2666ParseResult UnionExtractOp::parse(OpAsmParser &parser, OperationState &result) {
2667 return parseExtractOp<UnionType>(parser, result);
2668}
2669
2670void UnionExtractOp::print(OpAsmPrinter &printer) {
2671 printExtractOp(printer, *this);
2672}
2673
2674LogicalResult UnionExtractOp::inferReturnTypes(
2675 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
2676 DictionaryAttr attrs, mlir::OpaqueProperties properties,
2677 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
2678 Adaptor adaptor(operands, attrs, properties, regions);
2679 auto unionElements =
2680 hw::type_cast<UnionType>((adaptor.getInput().getType())).getElements();
2681 unsigned fieldIndex = adaptor.getFieldIndexAttr().getValue().getZExtValue();
2682 if (fieldIndex >= unionElements.size()) {
2683 if (loc)
2684 mlir::emitError(*loc, "field index " + Twine(fieldIndex) +
2685 " exceeds element count of aggregate type");
2686 return failure();
2687 }
2688 results.push_back(unionElements[fieldIndex].type);
2689 return success();
2690}
2691
2692void UnionExtractOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2693 Value input, StringAttr fieldName) {
2694 auto unionType = type_cast<UnionType>(input.getType());
2695 auto fieldIndex = unionType.getFieldIndex(fieldName);
2696 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2697 auto resultType = unionType.getElements()[*fieldIndex].type;
2698 build(odsBuilder, odsState, resultType, input, *fieldIndex);
2699}
2700
2701//===----------------------------------------------------------------------===//
2702// ArrayGetOp
2703//===----------------------------------------------------------------------===//
2704
2705// An array_get of an array_create with a constant index can just be the
2706// array_create operand at the constant index. If the array_create has a
2707// single uniform value for each element, just return that value regardless of
2708// the index. If the array is constructed from a constant by a bitcast
2709// operation, we can fold into a constant.
2710OpFoldResult ArrayGetOp::fold(FoldAdaptor adaptor) {
2711 auto inputCst = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2712 auto indexCst = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2713
2714 if (inputCst) {
2715 // Constant array index.
2716 if (indexCst) {
2717 auto indexVal = indexCst.getValue();
2718 if (indexVal.getBitWidth() < 64) {
2719 auto index = indexVal.getZExtValue();
2720 return inputCst[inputCst.size() - 1 - index];
2721 }
2722 }
2723 // If all elements of the array are the same, we can return any element of
2724 // array.
2725 if (!inputCst.empty() && llvm::all_equal(inputCst))
2726 return inputCst[0];
2727 }
2728
2729 // array_get(bitcast(c), i) -> c[i*w+w-1:i*w]
2730 if (auto bitcast = getInput().getDefiningOp<hw::BitcastOp>()) {
2731 auto intTy = dyn_cast<IntegerType>(getType());
2732 if (!intTy)
2733 return {};
2734 auto bitcastInputOp = bitcast.getInput().getDefiningOp<hw::ConstantOp>();
2735 if (!bitcastInputOp)
2736 return {};
2737 if (!indexCst)
2738 return {};
2739 auto bitcastInputCst = bitcastInputOp.getValue();
2740 // Calculate the index. Make sure to zero-extend the index value before
2741 // multiplying the element width.
2742 auto startIdx = indexCst.getValue().zext(bitcastInputCst.getBitWidth()) *
2743 getType().getIntOrFloatBitWidth();
2744 // Extract [startIdx + width - 1: startIdx].
2745 return IntegerAttr::get(intTy, bitcastInputCst.lshr(startIdx).trunc(
2746 intTy.getIntOrFloatBitWidth()));
2747 }
2748
2749 // array_get(array_inject(_, index, element), index) -> element
2750 if (auto inject = getInput().getDefiningOp<ArrayInjectOp>())
2751 if (getIndex() == inject.getIndex())
2752 return inject.getElement();
2753
2754 auto inputCreate = getInput().getDefiningOp<ArrayCreateOp>();
2755 if (!inputCreate)
2756 return {};
2757
2758 if (auto uniformValue = inputCreate.getUniformElement())
2759 return uniformValue;
2760
2761 if (!indexCst || indexCst.getValue().getBitWidth() > 64)
2762 return {};
2763
2764 uint64_t index = indexCst.getValue().getLimitedValue();
2765 auto createInputs = inputCreate.getInputs();
2766 if (index >= createInputs.size())
2767 return {};
2768 return createInputs[createInputs.size() - index - 1];
2769}
2770
2771LogicalResult ArrayGetOp::canonicalize(ArrayGetOp op,
2772 PatternRewriter &rewriter) {
2773 auto idxOpt = getUIntFromValue(op.getIndex());
2774 if (!idxOpt)
2775 return failure();
2776
2777 auto *inputOp = op.getInput().getDefiningOp();
2778 if (auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
2779 // get(slice(a, n), m) -> get(a, n + m)
2780 auto offsetOp = inputSlice.getLowIndex();
2781 auto offsetOpt = getUIntFromValue(offsetOp);
2782 if (!offsetOpt)
2783 return failure();
2784
2785 uint64_t offset = *offsetOpt + *idxOpt;
2786 auto newOffset =
2787 ConstantOp::create(rewriter, op.getLoc(), offsetOp.getType(), offset);
2788 rewriter.replaceOpWithNewOp<ArrayGetOp>(op, inputSlice.getInput(),
2789 newOffset);
2790 return success();
2791 }
2792
2793 if (auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
2794 // get(concat(a0, a1, ...), m) -> get(an, m - s0 - s1 - ...)
2795 uint64_t elemIndex = *idxOpt;
2796 for (auto input : llvm::reverse(inputConcat.getInputs())) {
2797 size_t size = hw::type_cast<ArrayType>(input.getType()).getNumElements();
2798 if (elemIndex >= size) {
2799 elemIndex -= size;
2800 continue;
2801 }
2802
2803 unsigned indexWidth = size == 1 ? 1 : llvm::Log2_64_Ceil(size);
2804 auto newIdxOp =
2805 ConstantOp::create(rewriter, op.getLoc(),
2806 rewriter.getIntegerType(indexWidth), elemIndex);
2807
2808 rewriter.replaceOpWithNewOp<ArrayGetOp>(op, input, newIdxOp);
2809 return success();
2810 }
2811 return failure();
2812 }
2813
2814 // array_get const, (array_get sel, (array_create a, b, c, d)) -->
2815 // array_get sel, (array_create (array_get const a), (array_get const b),
2816 // (array_get const, c), (array_get const, d))
2817 if (auto innerGet = dyn_cast_or_null<hw::ArrayGetOp>(inputOp)) {
2818 if (!innerGet.getIndex().getDefiningOp<hw::ConstantOp>()) {
2819 if (auto create =
2820 innerGet.getInput().getDefiningOp<hw::ArrayCreateOp>()) {
2821
2822 SmallVector<Value> newValues;
2823 for (auto operand : create.getOperands())
2824 newValues.push_back(rewriter.createOrFold<hw::ArrayGetOp>(
2825 op.getLoc(), operand, op.getIndex()));
2826
2827 rewriter.replaceOpWithNewOp<hw::ArrayGetOp>(
2828 op,
2829 rewriter.createOrFold<hw::ArrayCreateOp>(op.getLoc(), newValues),
2830 innerGet.getIndex());
2831 return success();
2832 }
2833 }
2834 }
2835
2836 return failure();
2837}
2838
2839//===----------------------------------------------------------------------===//
2840// ArrayInjectOp
2841//===----------------------------------------------------------------------===//
2842
2843OpFoldResult ArrayInjectOp::fold(FoldAdaptor adaptor) {
2844 auto inputAttr = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2845 auto indexAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2846 auto elementAttr = adaptor.getElement();
2847
2848 // inject(constant[xs, y, zs], iy, a) -> constant[x, a, z]
2849 if (inputAttr && indexAttr && elementAttr) {
2850 if (auto index = indexAttr.getValue().tryZExtValue()) {
2851 if (*index < inputAttr.size()) {
2852 SmallVector<Attribute> elements(inputAttr.getValue());
2853 elements[inputAttr.size() - 1 - *index] = elementAttr;
2854 return ArrayAttr::get(getContext(), elements);
2855 }
2856 }
2857 }
2858
2859 return {};
2860}
2861
2862static LogicalResult canonicalizeArrayInjectChain(ArrayInjectOp op,
2863 PatternRewriter &rewriter) {
2864 // If this inject is only used as an input to another inject, don't try to
2865 // canonicalize it. It will be included in that other op's canonicalization
2866 // attempt. This avoids doing redundant work.
2867 if (op->hasOneUse()) {
2868 auto &use = *op->use_begin();
2869 if (isa<ArrayInjectOp>(use.getOwner()) && use.getOperandNumber() == 0)
2870 return failure();
2871 }
2872
2873 // Collect all injects to constant indices.
2874 auto arrayLength = type_cast<ArrayType>(op.getType()).getNumElements();
2875 Value input = op;
2877 while (auto inject = input.getDefiningOp<ArrayInjectOp>()) {
2878 // Determine the constant index.
2879 APInt indexAPInt;
2880 if (!matchPattern(inject.getIndex(), mlir::m_ConstantInt(&indexAPInt)))
2881 break;
2882 if (indexAPInt.getActiveBits() > 32)
2883 break;
2884 uint32_t index = indexAPInt.getZExtValue();
2885
2886 // Track the injected value. Make sure to only track indices that are in
2887 // bounds. This will allow us to later check if `elements.size()` matches
2888 // the array length.
2889 if (index < arrayLength)
2890 elements.insert({index, inject.getElement()});
2891
2892 // Step to the next inject op.
2893 input = inject.getInput();
2894 if (input == op)
2895 break; // break cycles
2896 }
2897
2898 // If we are assigning every single element, replace the op with an
2899 // `hw.array_create`.
2900 if (elements.size() == arrayLength) {
2901 SmallVector<Value, 4> operands;
2902 operands.reserve(arrayLength);
2903 for (uint32_t idx = 0; idx < arrayLength; ++idx)
2904 operands.push_back(elements.at(arrayLength - idx - 1));
2905 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(), operands);
2906 return success();
2907 }
2908
2909 return failure();
2910}
2911
2912static LogicalResult
2913canonicalizeArrayInjectIntoCreate(ArrayInjectOp op, PatternRewriter &rewriter) {
2914 auto createOp = op.getInput().getDefiningOp<ArrayCreateOp>();
2915 if (!createOp)
2916 return failure();
2917
2918 // Make sure the access is in bounds.
2919 APInt indexAPInt;
2920 if (!matchPattern(op.getIndex(), mlir::m_ConstantInt(&indexAPInt)) ||
2921 !indexAPInt.ult(createOp.getInputs().size()))
2922 return failure();
2923
2924 // Substitute the injected value.
2925 SmallVector<Value> elements = createOp.getInputs();
2926 elements[elements.size() - indexAPInt.getZExtValue() - 1] = op.getElement();
2927 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, elements);
2928 return success();
2929}
2930
2931void ArrayInjectOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
2932 MLIRContext *context) {
2933 patterns.add<ArrayInjectToSameIndex>(context);
2936}
2937
2938//===----------------------------------------------------------------------===//
2939// TypedeclOp
2940//===----------------------------------------------------------------------===//
2941
2942StringRef TypedeclOp::getPreferredName() {
2943 return getVerilogName().value_or(getName());
2944}
2945
2946Type TypedeclOp::getAliasType() {
2947 auto parentScope = cast<hw::TypeScopeOp>(getOperation()->getParentOp());
2948 return hw::TypeAliasType::get(
2949 SymbolRefAttr::get(parentScope.getSymNameAttr(),
2950 {FlatSymbolRefAttr::get(*this)}),
2951 getType());
2952}
2953
2954//===----------------------------------------------------------------------===//
2955// BitcastOp
2956//===----------------------------------------------------------------------===//
2957
2958OpFoldResult BitcastOp::fold(FoldAdaptor) {
2959 // Identity.
2960 // bitcast(%a) : A -> A ==> %a
2961 if (getOperand().getType() == getType())
2962 return getOperand();
2963
2964 return {};
2965}
2966
2967LogicalResult BitcastOp::canonicalize(BitcastOp op, PatternRewriter &rewriter) {
2968 // Composition.
2969 // %b = bitcast(%a) : A -> B
2970 // bitcast(%b) : B -> C
2971 // ===> bitcast(%a) : A -> C
2972 auto inputBitcast =
2973 dyn_cast_or_null<BitcastOp>(op.getInput().getDefiningOp());
2974 if (!inputBitcast)
2975 return failure();
2976 auto bitcast = rewriter.createOrFold<BitcastOp>(op.getLoc(), op.getType(),
2977 inputBitcast.getInput());
2978 rewriter.replaceOp(op, bitcast);
2979 return success();
2980}
2981
2982LogicalResult BitcastOp::verify() {
2983 if (getBitWidth(getInput().getType()) != getBitWidth(getResult().getType()))
2984 return this->emitOpError("Bitwidth of input must match result");
2985 return success();
2986}
2987
2988//===----------------------------------------------------------------------===//
2989// HierPathOp helpers.
2990//===----------------------------------------------------------------------===//
2991
2992bool HierPathOp::dropModule(StringAttr moduleToDrop) {
2993 SmallVector<Attribute, 4> newPath;
2994 bool updateMade = false;
2995 for (auto nameRef : getNamepath()) {
2996 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
2997 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
2998 if (ref.getModule() == moduleToDrop)
2999 updateMade = true;
3000 else
3001 newPath.push_back(ref);
3002 } else {
3003 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3004 updateMade = true;
3005 else
3006 newPath.push_back(nameRef);
3007 }
3008 }
3009 if (updateMade)
3010 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3011 return updateMade;
3012}
3013
3014bool HierPathOp::inlineModule(StringAttr moduleToDrop) {
3015 SmallVector<Attribute, 4> newPath;
3016 bool updateMade = false;
3017 StringRef inlinedInstanceName = "";
3018 for (auto nameRef : getNamepath()) {
3019 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3020 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3021 if (ref.getModule() == moduleToDrop) {
3022 inlinedInstanceName = ref.getName().getValue();
3023 updateMade = true;
3024 } else if (!inlinedInstanceName.empty()) {
3025 newPath.push_back(hw::InnerRefAttr::get(
3026 ref.getModule(),
3027 StringAttr::get(getContext(), inlinedInstanceName + "_" +
3028 ref.getName().getValue())));
3029 inlinedInstanceName = "";
3030 } else
3031 newPath.push_back(ref);
3032 } else {
3033 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3034 updateMade = true;
3035 else
3036 newPath.push_back(nameRef);
3037 }
3038 }
3039 if (updateMade)
3040 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3041 return updateMade;
3042}
3043
3044bool HierPathOp::updateModule(StringAttr oldMod, StringAttr newMod) {
3045 SmallVector<Attribute, 4> newPath;
3046 bool updateMade = false;
3047 for (auto nameRef : getNamepath()) {
3048 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3049 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3050 if (ref.getModule() == oldMod) {
3051 newPath.push_back(hw::InnerRefAttr::get(newMod, ref.getName()));
3052 updateMade = true;
3053 } else
3054 newPath.push_back(ref);
3055 } else {
3056 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == oldMod) {
3057 newPath.push_back(FlatSymbolRefAttr::get(newMod));
3058 updateMade = true;
3059 } else
3060 newPath.push_back(nameRef);
3061 }
3062 }
3063 if (updateMade)
3064 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3065 return updateMade;
3066}
3067
3068bool HierPathOp::updateModuleAndInnerRef(
3069 StringAttr oldMod, StringAttr newMod,
3070 const llvm::DenseMap<StringAttr, StringAttr> &innerSymRenameMap) {
3071 auto fromRef = FlatSymbolRefAttr::get(oldMod);
3072 if (oldMod == newMod)
3073 return false;
3074
3075 auto namepathNew = getNamepath().getValue().vec();
3076 bool updateMade = false;
3077 // Break from the loop if the module is found, since it can occur only once.
3078 for (auto &element : namepathNew) {
3079 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(element)) {
3080 if (innerRef.getModule() != oldMod)
3081 continue;
3082 auto symName = innerRef.getName();
3083 // Since the module got updated, the old innerRef symbol inside oldMod
3084 // should also be updated to the new symbol inside the newMod.
3085 auto to = innerSymRenameMap.find(symName);
3086 if (to != innerSymRenameMap.end())
3087 symName = to->second;
3088 updateMade = true;
3089 element = hw::InnerRefAttr::get(newMod, symName);
3090 break;
3091 }
3092 if (element != fromRef)
3093 continue;
3094
3095 updateMade = true;
3096 element = FlatSymbolRefAttr::get(newMod);
3097 break;
3098 }
3099 if (updateMade)
3100 setNamepathAttr(ArrayAttr::get(getContext(), namepathNew));
3101 return updateMade;
3102}
3103
3104bool HierPathOp::truncateAtModule(StringAttr atMod, bool includeMod) {
3105 SmallVector<Attribute, 4> newPath;
3106 bool updateMade = false;
3107 for (auto nameRef : getNamepath()) {
3108 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3109 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3110 if (ref.getModule() == atMod) {
3111 updateMade = true;
3112 if (includeMod)
3113 newPath.push_back(ref);
3114 } else
3115 newPath.push_back(ref);
3116 } else {
3117 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == atMod && !includeMod)
3118 updateMade = true;
3119 else
3120 newPath.push_back(nameRef);
3121 }
3122 if (updateMade)
3123 break;
3124 }
3125 if (updateMade)
3126 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3127 return updateMade;
3128}
3129
3130/// Return just the module part of the namepath at a specific index.
3131StringAttr HierPathOp::modPart(unsigned i) {
3132 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3133 .Case<FlatSymbolRefAttr>([](auto a) { return a.getAttr(); })
3134 .Case<hw::InnerRefAttr>([](auto a) { return a.getModule(); });
3135}
3136
3137/// Return the root module.
3138StringAttr HierPathOp::root() {
3139 assert(!getNamepath().empty());
3140 return modPart(0);
3141}
3142
3143/// Return true if the NLA has the module in its path.
3144bool HierPathOp::hasModule(StringAttr modName) {
3145 for (auto nameRef : getNamepath()) {
3146 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3147 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3148 if (ref.getModule() == modName)
3149 return true;
3150 } else {
3151 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == modName)
3152 return true;
3153 }
3154 }
3155 return false;
3156}
3157
3158/// Return true if the NLA has the InnerSym .
3159bool HierPathOp::hasInnerSym(StringAttr modName, StringAttr symName) const {
3160 for (auto nameRef : const_cast<HierPathOp *>(this)->getNamepath())
3161 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef))
3162 if (ref.getName() == symName && ref.getModule() == modName)
3163 return true;
3164
3165 return false;
3166}
3167
3168/// Return just the reference part of the namepath at a specific index. This
3169/// will return an empty attribute if this is the leaf and the leaf is a module.
3170StringAttr HierPathOp::refPart(unsigned i) {
3171 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3172 .Case<FlatSymbolRefAttr>([](auto a) { return StringAttr({}); })
3173 .Case<hw::InnerRefAttr>([](auto a) { return a.getName(); });
3174}
3175
3176/// Return the leaf reference. This returns an empty attribute if the leaf
3177/// reference is a module.
3178StringAttr HierPathOp::ref() {
3179 assert(!getNamepath().empty());
3180 return refPart(getNamepath().size() - 1);
3181}
3182
3183/// Return the leaf module.
3184StringAttr HierPathOp::leafMod() {
3185 assert(!getNamepath().empty());
3186 return modPart(getNamepath().size() - 1);
3187}
3188
3189/// Returns true if this NLA targets an instance of a module (as opposed to
3190/// an instance's port or something inside an instance).
3191bool HierPathOp::isModule() { return !ref(); }
3192
3193/// Returns true if this NLA targets something inside a module (as opposed
3194/// to a module or an instance of a module);
3195bool HierPathOp::isComponent() { return (bool)ref(); }
3196
3197// Verify the HierPathOp.
3198// 1. Iterate over the namepath.
3199// 2. The namepath should be a valid instance path, specified either on a
3200// module or a declaration inside a module.
3201// 3. Each element in the namepath is an InnerRefAttr except possibly the
3202// last element.
3203// 4. Make sure that the InnerRefAttr is legal, by verifying the module name
3204// and the corresponding inner_sym on the instance.
3205// 5. Make sure that the instance path is legal, by verifying the sequence of
3206// instance and the expected module occurs as the next element in the path.
3207// 6. The last element of the namepath, can be an InnerRefAttr on either a
3208// module port or a declaration inside the module.
3209// 7. The last element of the namepath can also be a module symbol.
3210LogicalResult HierPathOp::verifyInnerRefs(hw::InnerRefNamespace &ns) {
3211 ArrayAttr expectedModuleNames = {};
3212 auto checkExpectedModule = [&](Attribute name) -> LogicalResult {
3213 if (!expectedModuleNames)
3214 return success();
3215 if (llvm::any_of(expectedModuleNames,
3216 [name](Attribute attr) { return attr == name; }))
3217 return success();
3218 auto diag = emitOpError() << "instance path is incorrect. Expected ";
3219 size_t n = expectedModuleNames.size();
3220 if (n != 1) {
3221 diag << "one of ";
3222 }
3223 for (size_t i = 0; i < n; ++i) {
3224 if (i != 0)
3225 diag << ((i + 1 == n) ? " or " : ", ");
3226 diag << cast<StringAttr>(expectedModuleNames[i]);
3227 }
3228 diag << ". Instead found: " << name;
3229 return diag;
3230 };
3231
3232 if (!getNamepath() || getNamepath().empty())
3233 return emitOpError() << "the instance path cannot be empty";
3234 for (unsigned i = 0, s = getNamepath().size() - 1; i < s; ++i) {
3235 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(getNamepath()[i]);
3236 if (!innerRef)
3237 return emitOpError()
3238 << "the instance path can only contain inner sym reference"
3239 << ", only the leaf can refer to a module symbol";
3240
3241 if (failed(checkExpectedModule(innerRef.getModule())))
3242 return failure();
3243
3244 auto instOp = ns.lookupOp<igraph::InstanceOpInterface>(innerRef);
3245 if (!instOp)
3246 return emitOpError() << " module: " << innerRef.getModule()
3247 << " does not contain any instance with symbol: "
3248 << innerRef.getName();
3249 expectedModuleNames = instOp.getReferencedModuleNamesAttr();
3250 }
3251
3252 // The instance path has been verified. Now verify the last element.
3253 auto leafRef = getNamepath()[getNamepath().size() - 1];
3254 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(leafRef)) {
3255 if (!ns.lookup(innerRef)) {
3256 return emitOpError() << " operation with symbol: " << innerRef
3257 << " was not found ";
3258 }
3259 if (failed(checkExpectedModule(innerRef.getModule())))
3260 return failure();
3261 } else if (failed(checkExpectedModule(
3262 cast<FlatSymbolRefAttr>(leafRef).getAttr()))) {
3263 return failure();
3264 }
3265 return success();
3266}
3267
3268void HierPathOp::print(OpAsmPrinter &p) {
3269 p << " ";
3270
3271 // Print visibility if present.
3272 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
3273 if (auto visibility =
3274 getOperation()->getAttrOfType<StringAttr>(visibilityAttrName))
3275 p << visibility.getValue() << ' ';
3276
3277 p.printSymbolName(getSymName());
3278 p << " [";
3279 llvm::interleaveComma(getNamepath().getValue(), p, [&](Attribute attr) {
3280 if (auto ref = dyn_cast<hw::InnerRefAttr>(attr)) {
3281 p.printSymbolName(ref.getModule().getValue());
3282 p << "::";
3283 p.printSymbolName(ref.getName().getValue());
3284 } else {
3285 p.printSymbolName(cast<FlatSymbolRefAttr>(attr).getValue());
3286 }
3287 });
3288 p << "]";
3289 p.printOptionalAttrDict(
3290 (*this)->getAttrs(),
3291 {SymbolTable::getSymbolAttrName(), "namepath", visibilityAttrName});
3292}
3293
3294ParseResult HierPathOp::parse(OpAsmParser &parser, OperationState &result) {
3295 // Parse the visibility attribute.
3296 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
3297
3298 // Parse the symbol name.
3299 StringAttr symName;
3300 if (parser.parseSymbolName(symName, SymbolTable::getSymbolAttrName(),
3301 result.attributes))
3302 return failure();
3303
3304 // Parse the namepath.
3305 SmallVector<Attribute> namepath;
3306 if (parser.parseCommaSeparatedList(
3307 OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
3308 auto loc = parser.getCurrentLocation();
3309 SymbolRefAttr ref;
3310 if (parser.parseAttribute(ref))
3311 return failure();
3312
3313 // "A" is a Ref, "A::b" is a InnerRef, "A::B::c" is an error.
3314 auto pathLength = ref.getNestedReferences().size();
3315 if (pathLength == 0)
3316 namepath.push_back(
3317 FlatSymbolRefAttr::get(ref.getRootReference()));
3318 else if (pathLength == 1)
3319 namepath.push_back(hw::InnerRefAttr::get(ref.getRootReference(),
3320 ref.getLeafReference()));
3321 else
3322 return parser.emitError(loc,
3323 "only one nested reference is allowed");
3324 return success();
3325 }))
3326 return failure();
3327 result.addAttribute("namepath",
3328 ArrayAttr::get(parser.getContext(), namepath));
3329
3330 if (parser.parseOptionalAttrDict(result.attributes))
3331 return failure();
3332
3333 return success();
3334}
3335
3336//===----------------------------------------------------------------------===//
3337// TriggeredOp
3338//===----------------------------------------------------------------------===//
3339
3340void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
3341 EventControlAttr event, Value trigger,
3342 ValueRange inputs) {
3343 odsState.addOperands(trigger);
3344 odsState.addOperands(inputs);
3345 odsState.addAttribute(getEventAttrName(odsState.name), event);
3346 auto *r = odsState.addRegion();
3347 Block *b = new Block();
3348 r->push_back(b);
3349
3350 llvm::SmallVector<Location> argLocs;
3351 llvm::transform(inputs, std::back_inserter(argLocs),
3352 [&](Value v) { return v.getLoc(); });
3353 b->addArguments(inputs.getTypes(), argLocs);
3354}
3355
3356//===----------------------------------------------------------------------===//
3357// TableGen generated logic.
3358//===----------------------------------------------------------------------===//
3359
3360// Provide the autogenerated implementation guts for the Op classes.
3361#define GET_OP_CLASSES
3362#include "circt/Dialect/HW/HW.cpp.inc"
assert(baseType &&"element must be base type")
MlirType elementType
Definition CHIRRTL.cpp:29
static std::unique_ptr< Context > context
static void buildModule(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports, ArrayAttr annotations, ArrayAttr layers)
void getAsmBlockArgumentNamesImpl(Operation *op, mlir::Region &region, OpAsmSetValueNameFn setNameFn)
Get a special name to use when printing the entry block arguments of the region contained by an opera...
static LogicalResult verifyModuleCommon(HWModuleLike module)
Definition HWOps.cpp:1086
static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value, Type resultType)
Definition HWOps.cpp:501
static LogicalResult canonicalizeArrayInjectChain(ArrayInjectOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2862
static void printModuleOp(OpAsmPrinter &p, ModuleTy mod)
Definition HWOps.cpp:1031
static bool flattenConcatOp(ArrayConcatOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2006
static LogicalResult foldCreateToSlice(ArrayCreateOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:1736
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
Definition HWOps.cpp:1428
static ArrayAttr arrayOrEmpty(mlir::MLIRContext *context, ArrayRef< Attribute > attrs)
Definition HWOps.cpp:84
FunctionType getHWModuleOpType(Operation *op)
Definition HWOps.cpp:1023
static void printExtractOp(OpAsmPrinter &printer, AggType op)
Use the same printer for both struct_extract and union_extract since the syntax is identical.
Definition HWOps.cpp:2403
static void printArrayConcatTypes(OpAsmPrinter &p, Operation *, TypeRange inputTypes, Type resultType)
Definition HWOps.cpp:1967
static ParseResult parseSliceTypes(OpAsmParser &p, Type &srcType, Type &idxType)
Definition HWOps.cpp:1623
static void modifyModulePorts(Operation *op, ArrayRef< std::pair< unsigned, PortInfo > > insertInputs, ArrayRef< std::pair< unsigned, PortInfo > > insertOutputs, ArrayRef< unsigned > removeInputs, ArrayRef< unsigned > removeOutputs, Block *body=nullptr)
Insert and remove ports of a module.
Definition HWOps.cpp:694
static Value foldStructExtract(Operation *inputOp, uint32_t fieldIndex)
Definition HWOps.cpp:69
static bool hasAttribute(StringRef name, ArrayRef< NamedAttribute > attrs)
Definition HWOps.cpp:901
static void modifyModuleArgs(MLIRContext *context, ArrayRef< std::pair< unsigned, PortInfo > > insertArgs, ArrayRef< unsigned > removeArgs, ArrayRef< Attribute > oldArgNames, ArrayRef< Type > oldArgTypes, ArrayRef< Attribute > oldArgAttrs, ArrayRef< Location > oldArgLocs, SmallVector< Attribute > &newArgNames, SmallVector< Type > &newArgTypes, SmallVector< Attribute > &newArgAttrs, SmallVector< Location > &newArgLocs, Block *body=nullptr)
Internal implementation of argument/result insertion and removal on modules.
Definition HWOps.cpp:595
static bool mergeConcatSlices(ArrayConcatOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2023
static SmallVector< Location > getAllPortLocs(ModTy module)
Definition HWOps.cpp:1206
static ParseResult parseExtractOp(OpAsmParser &parser, OperationState &result)
Use the same parser for both struct_extract and union_extract since the syntax is identical.
Definition HWOps.cpp:2366
static void setAllPortNames(ArrayRef< Attribute > names, ModTy module)
Definition HWOps.cpp:1276
static void getAsmBlockArgumentNamesImpl(mlir::Region &region, OpAsmSetValueNameFn setNameFn)
Get a special name to use when printing the entry block arguments of the region contained by an opera...
Definition HWOps.cpp:101
static void setHWModuleType(ModTy &mod, ModuleType type)
Definition HWOps.cpp:1349
static ParseResult parseParamValue(OpAsmParser &p, Attribute &value, Type &resultType)
Definition HWOps.cpp:493
static LogicalResult checkAttributes(Operation *op, Attribute attr, Type type)
Definition HWOps.cpp:407
static LogicalResult canonicalizeArrayInjectIntoCreate(ArrayInjectOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2913
static std::optional< uint64_t > getUIntFromValue(Value value)
Definition HWOps.cpp:1807
static ParseResult parseHWModuleOp(OpAsmParser &parser, OperationState &result)
Definition HWOps.cpp:909
static LogicalResult verifyAggregateFieldIndexAndType(AggregateOp &op, AggregateType aggType, Type elementType)
Ensure an aggregate op's field index is within the bounds of the aggregate type and the accessed fiel...
Definition HWOps.cpp:2340
static PortInfo getPort(ModuleTy &mod, size_t idx)
Definition HWOps.cpp:1448
static void printSliceTypes(OpAsmPrinter &p, Operation *, Type srcType, Type idxType)
Definition HWOps.cpp:1637
static bool hasAdditionalAttributes(Op op, ArrayRef< StringRef > ignoredAttrs={})
Check whether an operation has any additional attributes set beyond its standard list of attributes r...
Definition HWOps.cpp:353
Delimiter
Definition HWOps.cpp:116
@ OptionalLessGreater
static ParseResult parseArrayConcatTypes(OpAsmParser &p, SmallVectorImpl< Type > &inputTypes, Type &resultType)
Definition HWOps.cpp:1937
static bool getFieldName(const FieldRef &fieldRef, SmallString< 32 > &string)
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:216
static StringAttr append(StringAttr base, const Twine &suffix)
Return a attribute with the specified suffix appended.
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
A namespace that is used to store existing names and generate new names in some scope within the IR.
Definition Namespace.h:30
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
Definition Namespace.h:87
void setOutput(unsigned i, Value v)
Definition HWOps.cpp:241
Value getInput(unsigned i)
Definition HWOps.cpp:247
llvm::SmallVector< Value > outputOperands
Definition HWOps.h:119
llvm::SmallVector< Value > inputArgs
Definition HWOps.h:118
llvm::StringMap< unsigned > outputIdx
Definition HWOps.h:117
llvm::StringMap< unsigned > inputIdx
Definition HWOps.h:117
HWModulePortAccessor(Location loc, const ModulePortInfo &info, Region &bodyRegion)
Definition HWOps.cpp:225
static StringRef getInnerSymbolAttrName()
Return the name of the attribute used for inner symbol names.
This helps visit TypeOp nodes.
Definition HWVisitors.h:25
ResultType dispatchTypeOpVisitor(Operation *op, ExtraArgs... args)
Definition HWVisitors.h:27
ResultType visitUnhandledTypeOp(Operation *op, ExtraArgs... args)
This callback is invoked on any combinational operations that are not handled by the concrete visitor...
Definition HWVisitors.h:57
ResultType visitInvalidTypeOp(Operation *op, ExtraArgs... args)
This callback is invoked on any non-expression operations.
Definition HWVisitors.h:50
create(array_value, idx)
Definition hw.py:450
create(array_value, low_index, ret_type)
Definition hw.py:466
create(data_type, value)
Definition hw.py:433
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:55
uint64_t getWidth(Type t)
Definition ESIPasses.cpp:32
size_t getNumPorts(Operation *op)
Return the number of ports in a module-like thing (modules, memories, etc)
ModuleType fnToMod(Operation *op, ArrayRef< Attribute > inputNames, ArrayRef< Attribute > outputNames)
Definition HWTypes.cpp:1052
LogicalResult verifyParameterStructure(ArrayAttr parameters, ArrayAttr moduleParameters, const EmitErrorFn &emitError)
Check that all the parameter values specified to the instance are structurally valid.
std::function< void(std::function< bool(InFlightDiagnostic &)>)> EmitErrorFn
Whenever the nested function returns true, a note referring to the referenced module is attached to t...
LogicalResult verifyInstanceOfHWModule(Operation *instance, FlatSymbolRefAttr moduleRef, OperandRange inputs, TypeRange results, ArrayAttr argNames, ArrayAttr resultNames, ArrayAttr parameters, SymbolTableCollection &symbolTable)
Combines verifyReferencedModule, verifyInputs, verifyOutputs, and verifyParameters.
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
ParseResult parseModuleSignature(OpAsmParser &parser, SmallVectorImpl< PortParse > &args, TypeAttr &modType)
New Style parsing.
void printModuleSignatureNew(OpAsmPrinter &p, Region &body, hw::ModuleType modType, ArrayRef< Attribute > portAttrs, ArrayRef< Location > locAttrs)
bool isOffset(Value base, Value index, uint64_t offset)
Definition HWOps.cpp:1712
llvm::function_ref< void(OpBuilder &, HWModulePortAccessor &)> HWModuleBuilder
Definition HWOps.h:124
FunctionType getModuleType(Operation *module)
Return the signature for the specified module as a function type.
Definition HWOps.cpp:529
LogicalResult checkParameterInContext(Attribute value, Operation *module, Operation *usingOp, bool disallowParamRefs=false)
Check parameter specified by value to see if it is valid within the scope of the specified module mod...
Definition HWOps.cpp:202
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:110
bool isAnyModuleOrInstance(Operation *module)
TODO: Move all these functions to a hw::ModuleLike interface.
Definition HWOps.cpp:523
StringAttr getVerilogModuleNameAttr(Operation *module)
Returns the verilog module name attribute or symbol name of any module-like operations.
Definition HWOps.cpp:547
mlir::Type getCanonicalType(mlir::Type type)
Definition HWTypes.cpp:49
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
ParseResult parseInputPortList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inputs, SmallVectorImpl< Type > &inputTypes, ArrayAttr &inputNames)
Parse a list of instance input ports.
void printOutputPortList(OpAsmPrinter &p, Operation *op, TypeRange resultTypes, ArrayAttr resultNames)
Print a list of instance output ports.
ParseResult parseOptionalParameterList(OpAsmParser &parser, ArrayAttr &parameters)
Parse an parameter list if present.
void printOptionalParameterList(OpAsmPrinter &p, Operation *op, ArrayAttr parameters)
Print a parameter list for a module or instance.
StringRef chooseName(StringRef a, StringRef b)
Choose a good name for an item from two options.
Definition Naming.cpp:47
void printInputPortList(OpAsmPrinter &p, Operation *op, OperandRange inputs, TypeRange inputTypes, ArrayAttr inputNames)
Print a list of instance input ports.
ParseResult parseOutputPortList(OpAsmParser &parser, SmallVectorImpl< Type > &resultTypes, ArrayAttr &resultNames)
Parse a list of instance output ports.
Definition hw.py:1
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
Definition LLVM.h:183
This class represents the namespace in which InnerRef's can be resolved.
InnerSymTarget lookup(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
Operation * lookupOp(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
This holds a decoded list of input/inout and output ports for a module or instance.
PortInfo & at(size_t idx)
PortDirectionRange getOutputs()
mlir::Type type
Definition HWTypes.h:31
mlir::StringAttr name
Definition HWTypes.h:30
This holds the name, type, direction of a module's ports.